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.20.6: the latest bundled SDK, pages that iterate Maps and Sets, business rules on production environments, check-auth and teardown fixes (#783)
Akshay Maloo0a55a88fa285
diff --git a/.github/workflows/model-apps-script-tests.yml b/.github/workflows/model-apps-script-tests.ymlindex 35e44e507..4d9708b86 100644--- a/.github/workflows/model-apps-script-tests.yml+++ b/.github/workflows/model-apps-script-tests.yml@@ -96,6 +96,17 @@ jobs:with:node-version: ${{ matrix.node }}+ # The previous release's SDK bundle (model-apps 2.20.4; 2.20.5 ships the same bytes), for the upgrade tests: a workspace it wrote must be read by+ # this release's (scripts/tests/workspace-upgrade-*-real-bundle.test.js, helpers/previous-bundle.js, which checks its+ # SHA-256). The checkout is shallow, so the release commit is fetched by its hash and only the bundle is extracted. In CI+ # the tests FAIL without it rather than skip.+ - name: fetch-previous-sdk-bundle+ shell: bash+ run: |+ git fetch --no-tags --depth=1 origin c159268b994b218729ff69ccdd74be3c83c56f86+ git cat-file blob FETCH_HEAD:plugins/model-apps/scripts/vendor/cds-maker-sdk.cjs > "$RUNNER_TEMP/previous-cds-maker-sdk.cjs"+ echo "MODEL_APPS_PREVIOUS_BUNDLE=$RUNNER_TEMP/previous-cds-maker-sdk.cjs" >> "$GITHUB_ENV"+# run-tests.js is the plugin's own regression gate: it runs every# scripts/tests/*.test.js and exits non-zero on any failure. Invoking it# (rather than a bare `node --test`) keeps CI and the documented local@@ -220,6 +231,17 @@ jobs:echo "BASE_LIB_PATH=$RUNNER_TEMP/model-apps-2.13.0/plugins/model-apps/scripts/lib" >> "$GITHUB_ENV"echo "MODEL_APPS_RELEASED_SCRIPTS=$RUNNER_TEMP/model-apps-2.13.0/plugins/model-apps/scripts" >> "$GITHUB_ENV"+ # The previous release's SDK bundle (model-apps 2.20.4; 2.20.5 ships the same bytes), for the upgrade tests: a workspace it wrote must be read by+ # this release's (scripts/tests/workspace-upgrade-*-real-bundle.test.js, helpers/previous-bundle.js, which checks its+ # SHA-256). The checkout is shallow, so the release commit is fetched by its hash and only the bundle is extracted. In CI+ # the tests FAIL without it rather than skip.+ - name: fetch-previous-sdk-bundle+ shell: bash+ run: |+ git fetch --no-tags --depth=1 origin c159268b994b218729ff69ccdd74be3c83c56f86+ git cat-file blob FETCH_HEAD:plugins/model-apps/scripts/vendor/cds-maker-sdk.cjs > "$RUNNER_TEMP/previous-cds-maker-sdk.cjs"+ echo "MODEL_APPS_PREVIOUS_BUNDLE=$RUNNER_TEMP/previous-cds-maker-sdk.cjs" >> "$GITHUB_ENV"+# The same command as the matrix job, with those paths set: the oracle and A/B tests run instead of skipping.- name: run-model-apps-script-tests-with-parsersshell: bashdiff --git a/evals/model-apps/genpage/tests/iteration-runtime.test.js b/evals/model-apps/genpage/tests/iteration-runtime.test.jsindex 8e5aeef04..3b3468538 100644--- a/evals/model-apps/genpage/tests/iteration-runtime.test.js+++ b/evals/model-apps/genpage/tests/iteration-runtime.test.js@@ -1,8 +1,10 @@'use strict';// Eval 26's customer choices, run the way the page is compiled. The bundled SDK compiles every page with TypeScript's-// `transpileModule` and `{ target: ES5, module: ES2020, jsx: React }` — no `downlevelIteration` and no type check — and under-// those options a spread copies by `length` and index. A Map's iterator has neither, so `return [...seen.values()];`-// contributed nothing: the page's "Change customer" Dropdown opened with no options, and the compile reported nothing.+// `transpileModule` and `{ target: ES5, module: ES2020, jsx: React, downlevelIteration: true }` — no type check. The bundles before+// model-apps 2.20.6 compiled without `downlevelIteration`, as an older maker portal and `pac` still do, and under those options a spread+// copies by `length` and index. A Map's iterator has neither, so `return [...seen.values()];` contributed nothing: the page's "Change+// customer" Dropdown opened with no options, and the compile reported nothing. The committed page converts with `Array.from`, which+// is right under both.//// The page's own `choices` callback and the trusted top-level helpers it calls are lifted out of the committed source with the// vendored parser (never by line number), compiled alone with the SDK's options and run on the fixture's synthetic rows@@ -25,9 +27,10 @@ const HELPERS = ['LOOKUP_GUID', 'LOOKUP_QUALIFIED', 'normalizeLookupReference',let typescript;const ts = () => (typescript ||= loadVendoredTypeScript());-// The vendored SDK's own compile options, exactly: a test is never made to pass by changing the target or adding downlevelIteration.-const sdkCompile = (source) => ts().transpileModule(source, {- compilerOptions: { target: ts().ScriptTarget.ES5, module: ts().ModuleKind.ES2020, jsx: ts().JsxEmit.React },+// The vendored SDK's own compile options, exactly (plugins/model-apps/scripts/tests/iteration-emit.test.js holds them to what the bundle+// stores), and those of a compiler without iterator support: a test is never made to pass by changing either.+const sdkCompile = (source, { iteratorSupport = true } = {}) => ts().transpileModule(source, {+ compilerOptions: { target: ts().ScriptTarget.ES5, module: ts().ModuleKind.ES2020, jsx: ts().JsxEmit.React, ...(iteratorSupport ? { downlevelIteration: true } : {}) },reportDiagnostics: true,});@@ -61,7 +64,7 @@ function pieces(source) {// The callback compiled with the SDK's options and called with `rows` — optionally with its final return expression replaced,// which is how the control below puts the iterator spread back without touching the committed file.-function choicesOf(rows, { returnExpression } = {}) {+function choicesOf(rows, { returnExpression, iteratorSupport = true } = {}) {const { file, helpers, callback, returned } = pieces(PAGE);let text = callback.getText(file);if (returnExpression !== undefined) {@@ -70,7 +73,7 @@ function choicesOf(rows, { returnExpression } = {}) {text = `${text.slice(0, start)}${returnExpression}${text.slice(end)}`;}const source = `${helpers.join('\n\n')}\n\nconst choicesOf = (opportunities: any[]) => (${text})();\n`;- const { outputText, diagnostics } = sdkCompile(source);+ const { outputText, diagnostics } = sdkCompile(source, { iteratorSupport });assert.deepEqual((diagnostics || []).map((d) => `TS${d.code}`), [], 'the helpers and the callback compile without a diagnostic');const run = vm.runInNewContext(`${outputText}\n;choicesOf;`, {}, { filename: 'customer-lookup-choices.js' });return { choices: JSON.parse(JSON.stringify(run(rows))), outputText };@@ -97,14 +100,18 @@ test('eval 26: the customer choices, compiled as the SDK compiles the page, areassert.deepEqual(expected.map((choice) => choice.label), ['Fabrikam', 'Rene Valdes', 'Contoso', 'Contoso']);assert.deepEqual(expected.slice(2).map((choice) => choice.table), ['account', 'contact']);assert.equal(expected[2].id, expected[3].id, 'one GUID in two tables stays two choices');- const { choices } = choicesOf(ROWS.rows.map((entry) => entry.row));- assert.deepEqual(choices, expected);+ assert.deepEqual(choicesOf(ROWS.rows.map((entry) => entry.row)).choices, expected);+ assert.deepEqual(choicesOf(ROWS.rows.map((entry) => entry.row), { iteratorSupport: false }).choices, expected, 'and as a compiler without iterator support compiles it');});-test('eval 26: the same callback with the Map iterator spread back in offers no choice under the SDK options', () => {- const { choices, outputText } = choicesOf(ROWS.rows.map((entry) => entry.row), { returnExpression: '[...seen.values()]' });- assert.deepEqual(choices, [], 'the spread copies by length and index, which an iterator does not have');- assert.match(outputText, /__spreadArray\(\[\], seen\.values\(\), true\)/, 'ES5 emit copies the iterator as an array-like');+test('eval 26: the same callback with the Map iterator spread back in offers every choice under the SDK options and none without iterator support', () => {+ const rows = ROWS.rows.map((entry) => entry.row);+ const sdk = choicesOf(rows, { returnExpression: '[...seen.values()]' });+ assert.deepEqual(sdk.choices, recordedChoices(), 'the SDK reads the iterator through Symbol.iterator');+ assert.match(sdk.outputText, /__spreadArray\(\[\], __read\(seen\.values\(\)\), false\)/);+ const legacy = choicesOf(rows, { returnExpression: '[...seen.values()]', iteratorSupport: false });+ assert.deepEqual(legacy.choices, [], 'without iterator support the spread copies by length and index, which an iterator does not have');+ assert.match(legacy.outputText, /__spreadArray\(\[\], seen\.values\(\), true\)/, 'ES5 emit without iterator support copies the iterator as an array-like');});test('eval 26: the committed callback converts the iterator before returning it, and keeps its dedupe loop', () => {diff --git a/plugins/model-apps/.claude-plugin/plugin.json b/plugins/model-apps/.claude-plugin/plugin.jsonindex 30f36f4b3..15e8bb988 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.20.5",+ "version": "2.20.6","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 30f36f4b3..15e8bb988 100644--- a/plugins/model-apps/.plugin/plugin.json+++ b/plugins/model-apps/.plugin/plugin.json@@ -1,6 +1,6 @@{"name": "model-apps",- "version": "2.20.5",+ "version": "2.20.6","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 ae8849004..06407095c 100644--- a/plugins/model-apps/AGENTS.md+++ b/plugins/model-apps/AGENTS.md@@ -540,7 +540,7 @@ the pipeline and delegates each script's **behavioral spec** to the entries belofiles, its conversation messages) that the SDK writes as **one atomic `$batch` change set**, so a write either landed whole or wrote nothing, and the SDK compiles the page itself (a pagethat does not compile is refused before anything is written). What a write that cannot say what it did leaves behind follows from that.A **create** mints the page's id on the client before anything is sent, so what it did can always be found out by reading that id. Only a failure that PROVES nothing was written is reported as `nothing` and- not sent again: a typed refusal the SDK raises before it sends a write request (`PRE_WRITE_REFUSALS` in the module lists each, and where the SDK raises it — a page that does not compile or whose elements nest too deeply to compile (`PAGE_NESTING_TOO_DEEP`: split the page into components), a write plan it cannot+ not sent again: a typed refusal the SDK raises before it sends a write request (`PRE_WRITE_REFUSALS` in the module lists each, and where the SDK raises it — a page that does not compile or whose elements nest too deeply to compile (`PAGE_NESTING_TOO_DEEP`: split the page into components — the plugin's guard over the compiler raises it, and the SDK's own `GENPAGE_COMPILE_DEPTH_EXCEEDED` for the same page is reported as it), a write plan it cannotmake, a workspace copy that cannot be pushed) or a 4xx the service answered (a change set is atomic, so a rejected one leaves nothing). Any other error at or after the send is *unknown*: a reset, a 5xx from anintermediary, an answer the SDK cannot account for — and an error that merely has a string `code`, since a full disk (`ENOSPC`) is raised by the SDK's own workspace write AFTER the service committed the changeset. It is settled by reading the id: present — it landed (published, and said so in a warning); absent — nothing has landed *yet*, so it is sent **once more under the same id**: a first send that lands late@@ -579,10 +579,10 @@ the pipeline and delegates each script's **behavioral spec** to the entries belobundle pins that. What it sends you to look at depends on the caller (`update()`'s `caller`): the upload script'smessage names `genpage-base.js check` (the deployed page against the file and the base marker beside it), and a re-run goes back through the script's own guards; the **build** keeps nobase marker and reads every page again when it runs, so its message says to run the build again. A `VERSION_CONFLICT` on the first send is a known answer: nothing was written (on a resend it settles nothing).- **What a push's identities and version check do and do not guarantee.** Each push of a page is a new *checkpoint* in one sense only: it has identities of its own. The SDK mints the change-set id (`uxagentproject_<guid>`) for every push, and an update's turn id+ **What a push's identities and version check do and do not guarantee.** Each push of a page is a new *checkpoint* in one sense only: it has identities of its own. The change set's versioning checkpoint is named after the turn the push records (`uxagentproject_<turn id>`, since model-apps 2.20.6; a push that records no turn gets a fresh one), and an update's turn id(`newTurn.id`) is minted by the backend once per `update` call. A create's turn is given no id by the backend; the SDK mints one during push preparation (it keeps a GUID it is given and otherwise adds one to its copy of the page), so a create's turn has an identity of the SDK's too,and the fixed identity a create's resend relies on is the page id. No supported page operation (`create`, `update`, and the scripts and build phases over them) takes a change-set, checkpoint or turn id from its caller, so a caller cannot pin one so that a retry of the whole call reuses it, and cannot bind an- approval to one: a second call of `update` is a new push with new ids, and only the resends *inside* one call share a turn id. (The lower-level SDK, and the `newTurnId` seam the tests use, can be given a turn id; that is not a way to retry a page operation.) Do not treat these ids as an idempotency key or as the identity of a reviewed change.+ approval to one: a second call of `update` is a new push with new ids, and only the resends *inside* one call share a turn id (and so a checkpoint). (The lower-level SDK, and the `newTurnId` seam the tests use, can be given a turn id; that is not a way to retry a page operation.) Do not treat these ids as an idempotency key or as the identity of a reviewed change.The version check is **not an atomic expected-version save**. Before each push the SDK reads the page's row and its file rows again and compares their version tokens with the ones the operation read (a page or file that moved, wasadded or was deleted is refused as `VERSION_CONFLICT`, nothing written); but the writes that follow are separate requests that carry `If-Match: *`, because these rows accept no version validator. A writer that savesthe page *between those reads and the change set* is therefore overwritten without a conflict. The check narrows the window to the length of one push; it does not close it. What it does guarantee is that a page changed@@ -626,6 +626,16 @@ the pipeline and delegates each script's **behavioral spec** to the entries belo`<app-folder>/.maker-workspace/` for reuse/edits. The 16 phases(`solution·data-model·sample-data·web-resources·views·charts·forms·business-rules·business-process-flows·commands·dashboards·app-shell·pages·ai-features·security·publish`)are unchanged; independent ops run with bounded parallelism.+ **Business rules are environment-gated, and the gate has two forms** (`sdk-build.js`, the `business-rules` loop; `skipIf` is the whole decision). An environment that does not declare the+ bound `CreateProcessWithWfomJson` member answers `BUSINESS_RULE_API_UNAVAILABLE`. A **production environment** — the common case — declares the member but has it switched off, and+ answers the FIRST create with HTTP 400 `0x80040216` ("An unexpected error occurred.") whatever the rule says; nothing is created. Both are the same skip: one warning naming the code, the+ rules recorded in `result.skipped.businessRules` (which `--verify` reads as *not applicable on this environment*), the rest of the build running. The 400 is read as the gate only when the+ call is to that member (`isConfirmedBusinessRuleRefusal`: the request's path, status and code — never the words or a substring of a URL) AND no rule of this build was created before it AND it is the+ **definitive answer to the first send** of the create. A 400 says nothing of an earlier send that got no answer or a gateway's 5xx (the plugin's HTTP client sends such a create again, and the SDK can call it+ again): `sdk-http-client.js` marks a failure's body with the history of the sends (`HTTP_SEND_HISTORY`: `{ sends, earlierAmbiguous }`, a per-request ledger kept for the client's life), the gate needs+ `earlierAmbiguous: false`, and an unknown or partial outcome anywhere in the error chain (`outcome: 'unknown'`, a `…outcome-unknown` code, a status 0, 5xx or 2xx link) wins over a match.+ A transport that reports no history is not confirmed. The same 400 after a rule was created, an ambiguous attempt, or any other code or status, still halts. The remaining rules are then not sent. A rule that already exists is reused and does not count as a create.+ Even then the 400 is only a candidate: the same answer comes from a create the platform saved and then failed to finish (#482). So the create step reads the rule's definitions again (`refusedCreateWroteNothing`: a complete, paginated read, ids compared case-insensitively), and `skipIf` also needs that read to find no id the snapshot taken just before the push lacked. A new id halts and names the row without attributing it to this create (another writer can add one meanwhile); a read that fails or is incomplete halts too.Off-sitemap ids require a local CREATE receipt for this app/key/id plus an exact decoded stored-namematch, including when the spec and remote manifest agree. Otherwise `unproven-manifest-id` causes`pages-identity-conflict`, never a replacement CREATE. Names corroborate identity, never establish it.@@ -2367,7 +2377,11 @@ the pipeline and delegates each script's **behavioral spec** to the entries beloabort signals only the `cmd.exe` wrapper. The early WhoAmI is sent with `refreshOn401: false`: a 401would otherwise refresh the token with a synchronous `az` call (seconds, with every other probe's timerfrozen), so a 401 on the early request is re-sent at WhoAmI's old place, after `pac`, where that refresh- costs nothing.+ costs nothing. After a passing WhoAmI one more GET (`solutions?$select=solutionid&$top=1`, the first read+ a build makes) is the **capability probe**: HTTP 403 `0x80042f09` ("has not been assigned any roles") is+ `ok: false`, blocker `no_customization_role`, because WhoAmI answers for a user who holds no role and+ every customization read then fails. Any other outcome of the probe is a warning, never a verdict (a+ role count would be wrong: privileges also come through teams). The script is byte-identical in `plugins/pcf`.- **Download** overlaps each table's auxiliary reads (entity and attribute labels, the moneybase-currency flags, option sets) and the per-table relationship reads, bounded at 4(`runDownload({ concurrency })`; `1` is the sequential oracle), and merges them in the original fixed@@ -2752,7 +2766,7 @@ scripts/launch-playwright-mcp.js ← Playwright MCP server launcher (fullscreen; uses lib/detect-browser.js)playwright-mcp-fullscreen.config.json ← Fullscreen browser config for the launcherregenerate-verified-icons.js ← Regenerates references/verified-icons.txt from npm- check-auth.js ← Pre-flight: az present + logged in, pac identity, WhoAmI, identity match (the az probes, the token read + WhoAmI and pac overlap; the verdict order is fixed); a CLI too slow to answer is `az_timeout`/`pac_timeout`+ check-auth.js ← Pre-flight: az present + logged in, pac identity, WhoAmI, one `solutions` read that tells an identity with no security role (`no_customization_role`), identity match (the az probes, the token read + WhoAmI and pac overlap; the verdict order is fixed); a CLI too slow to answer is `az_timeout`/`pac_timeout`check-version.js ← Skill-start update notice: compares the plugin clone with its origin/main (git runs in the plugin, never the user's repo)resolve-interaction-mode.js ← Reports whether a human can answer in this run (unattended defaults)lint-app-spec.js ← Validate + lint an App Spec without touching an environment@@ -2837,7 +2851,7 @@ scripts/source-literals.js ← TSX lexer (code/comment/string/template/regex/JSX) — see "Known limits" belowsdk-teardown.js ← app-builder teardown engine (planTeardown is pure)sdk-http-client.js ← az-token HttpClient for the vendored SDK; a caller can name requests that are sent exactly once (`sendOnce(method, url)`: no retry on a transport failure, a 429 or 5xx, or a 401 refresh, and none of the replays special to a record delete and a `$batch` either) — `solution-settings.js` does for the three long solution actions; a caller can hand it the run's throttle budget (`deps.throttle`, lib/throttle-budget.js): every wait it takes before it sends a throttled request (HTTP 429, alone or as every operation of a `$batch`) again is then drawn from the budget — the answer's `Retry-After` whole, past the cap of a minute, or the schedule's wait when that is longer, placed on the clock so that requests throttled together are charged once — and a wait that does not fit is not taken: the 429 comes back as it came and the budget is told what the service asked (`decline`); every other wait (a 5xx, a reset connection, a deadlock victim's re-send) keeps its own schedule, and the budget is duck-typed and never loaded here, so the pcf copy, which has none, waits as it always did; an answer that is not a success comes back with the access token taken out of it (and a transport failure's text too, the error that carries Node's code included), a success untouched — the one `scrub` / `scrubAnswer` the Power Apps client uses as well; `needlesOf(token)` and `TOKEN_MARKER` are `lib/output-redaction.js`'s: the one list of texts a scrubber takes out of one token (the token and each of its parts of 24 characters or more) and the one marker, so the client's scrubber and what the process writes are kept free of a token by the same list, and each token the client sends is noted there (`noteToken`); `throttleBackoffMs(attempt, random)` is the capped, jittered schedule every throttled request waits on (1 s, 2 s, 4 s, 8 s, 8 s), exported because the page backend waits out a throttled page write on it (the client never re-sends a page's `$batch`: `lib/genpage-sdk.js` does, a push at a time); `retryAfterMs(headers, now, cap)` and `batchRetryAfterMs(res, now, cap)` cap what a response asks at a minute for the client's own retries, and a caller with a bound of its own passes `Infinity`: the page backend spends it inside the run's budget, the client itself does when it has that budget, and `solution-settings.js` inside the one budget of its import resend; `completeBatchStatus(res)` is the one status a COMPLETE multipart answer reports for every operation (the page backend reads a change set refused as a whole with it); the parser behind it, `isBatchThrottled` and `isBatchDeadlockVictim` is strict — an answer is read only when its outer boundary closes, every change set in it closes, and every part is a complete response whose first line is a status line; a part that declares a change set (`Content-Type: multipart/mixed; boundary=…`) must open and close exactly that boundary before the outer one goes on, a part with no response in it is an operation nobody answered, and a body is as long as the `Content-Length` its response gives, counted by the line breaks the answer has; a part that declares a `Transfer-Encoding` (chunked or any other) is not read at all, whole stream or not — the delimiters around it say nothing of whether its chunk stream is finished, so it never certifies a refusal or a deadlock victim; anything missing or malformed makes the WHOLE answer unproven (an answer that closes its outer boundary and is incomplete inside proves nothing); `isTransientTransportFailure(text, code)` says which failures of the transport are sent again — decided by Node's own error code when `makeRequest` reported one (`TRANSIENT_TRANSPORT_CODES`: `ECONNRESET`, `ETIMEDOUT`, `ESOCKETTIMEDOUT`, `ECONNABORTED`, `EPIPE`, `EAI_AGAIN`; any other code is final whatever the words say) and by the words only when it did not (a certificate's own phrases first): a reset, a timeout, an answer cut off, a temporary DNS failure, the same list `lib/retry-policy.js` calls a blip, and nothing else — a certificate that does not verify (whatever names it quotes), an unknown host and a message nobody recognises return at once; the error it throws carries the code beside the same message (this file is copied into the pcf plugin, so a test holds the two lists equal); a publish (`PublishXml`, `PublishAllXml`) is sent ONCE but for a 401 and a 429 of the service protection limits (`isServiceProtectionRefusal`, `SERVICE_PROTECTION_CODES`: the three codes the api-limits page documents) — never for the customization lock's 429, a 5xx or a failure of the transport — and its deadlock victim is the layer above's to re-send (`isSqlDeadlockVictim` and `DEADLOCK_RESENDS` are exported for `publish-xml.js`). Copied verbatim into `plugins/pcf` (`scripts/validate-plugin-copies.js`)- maker-sdk.js ← the one way a script makes an SDK: the vendored bundle with the vendored TypeScript compiler as its page compiler, and with the client it is handed guarded by `app-header-text.js`; `connectivity: true` (opt-in) also gives the instance the Power Apps service client, so no script wires a credential-carrying client by hand; and the `httpClient` it is given is handed over with the read of the environment's TABLE LIST held to being a list (`lib/collection-answers.js` `guardTableLists`), so every script's `findTables()` meets a failure (`TABLES_UNREADABLE`, an `SdkError`, so `error.code`) where the bundle alone would read a sign-in page, `{}` or `null` as "no tables" — none can forget it; and the `workspaceStorage` it is given is handed over with every text it is asked to write taken clean of the access tokens the process obtained (`lib/output-redaction.js` `guardWorkspaceStorage`: the SDK writes every file of its workspace through `writeTextAtomic`, and the wrapper is the storage in everything else), so a token a service repeated in an answer cannot land in a workspace file. The SDK itself — its errors, its warnings, its results — is exactly what the bundle makes: what a script WRITES is what is cleaned+ maker-sdk.js ← the one way a script makes an SDK: the vendored bundle with the vendored TypeScript compiler as its page compiler, and with the client it is handed guarded by `app-header-text.js`; `connectivity: true` (opt-in) also gives the instance the Power Apps service client, so no script wires a credential-carrying client by hand; and the `httpClient` it is given is handed over with the read of the environment's TABLE LIST held to being a list (`lib/collection-answers.js` `guardTableLists`), so every script's `findTables()` meets a failure (`TABLES_UNREADABLE`, an `SdkError`, so `error.code`) where the bundle alone used to read a sign-in page, `{}` or `null` as "no tables" (the bundled SDK now refuses one, but as a bare `CONNECTION_ERROR`, without that code) — none can forget it; and the `workspaceStorage` it is given is handed over with every text it is asked to write taken clean of the access tokens the process obtained (`lib/output-redaction.js` `guardWorkspaceStorage`: the SDK writes every file of its workspace through `writeTextAtomic`, and the wrapper is the storage in everything else), so a token a service repeated in an answer cannot land in a workspace file. The SDK itself — its errors, its warnings, its results — is exactly what the bundle makes: what a script WRITES is what is cleanedoutput-redaction.js ← keeps every access token the process obtained out of everything it WRITES, and out of nothing the service or the SDK made: `noteToken(token)` (called where a token is read from the Azure CLI — `dataverse-auth.js`, both reads — and where `dataverseRequest` and the SDK's HTTP client send one) is the registry, and the first token noted guards the process: `guardStream` wraps `process.stdout.write` and `process.stderr.write` (every `console.*` call, every script's result and warning printer, a library's own output end there; a text cleaned as a string, bytes — a Buffer, a Uint8Array, a string in `base64` or `hex` — masked byte for byte with as many `*` in a copy, the very bytes when they hold none), and `guardFatalErrors` prints — cleaned — what Node itself prints when an error ends the process, which never passes through `process.stderr.write` (only when nothing else handles the error: a test runner's own listener is left alone). `redactFileData(data, opts)` is what the file writers call (`safe-fs.js` `writeFileSafe` and `appendFileSafe`, `apply-snapshot-store.js` `writeFileAtomic`: a text cleaned as `redactOutput(text)` cleans it; bytes — every ArrayBuffer view: a Buffer, any typed array, a DataView — and a string given with a `hex`, `base64` or `base64url` encoding read as the bytes the file gets, a hit masked with as many `*` in a copy; data it cannot read with a token noted is refused before anything is written) and `guardWorkspaceStorage` wraps the SDK's `writeTextAtomic` (`maker-sdk.js`). `redactTokens(text, tokens)` is the matcher: it reads the text as it SPELLS a token, one character at a time — the character itself or an escape of it (`\uXXXX` in either case, `\xXX`, `\/`), with a fold between any two of them (white space, `\r\n` `\t` `\b` and the like as JSON writes them, a run of backslashes before an escape: JSON inside JSON, a stray backslash, a terminal colour code, the quote-plus-line-break `util.inspect` prints between the pieces of a long string, in colours or not) and an escape that can also be a literal backslash and letters (`\n` before a signature that starts with `n`) read both ways — every needle (the token and each part of 24 characters or more: `needlesOf`, and the base64 of each of those, percent-encoded and HTML spellings: `spellingsOf`) in ONE linear pass with a bounded set of readings beside it (a text that would need more is refused: the writer fails closed), the whole span from the token's first character to its last becoming `<token>`, so that JSON that was written is JSON still. It never touches an error, a warning or an answer: the SDK's errors keep every word the SDK gave them, and the strict `$batch` readers see the bytes the service sent. The beginning of a needle, 24 characters or more, goes too where a text says it was cut (`util.inspect`'s `... N more characters`, an ellipsis) and at the end of a whole text the process writes, and the end of a needle at its start (`redactOutput`; `redactTokens(text, tokens, { edges: true })`); `maskTokenBytes(bytes, tokens)` is the same for bytes. Each write is read on its own and nothing is held back for the next one. Not read: a token another process obtained; a piece of a token shorter than 24 characters (the shorter piece of a token written in two); a piece from the middle of one (a token written in three pieces or more); the piece an escape cut between two writes leaves on its far side when it is shorter than 24 characters; base64 of a piece that is not a whole part; and a token split between two appends to a file (the module's header lists them all). `makeWritesBlocking(...streams)` makes a stream's writes blocking for the last writes of a process — `emitResult`, `guardFatalErrors`, and every printer of a script's own that ends the process after writing (a result, a usage error, a last-resort handler, a hook's message, the warnings a script prints right before its result) — because on Linux and macOS a pipe's writes are queued and `process.exit` does not wait for them, so a large result reached its reader cut short (`tests/result-whole-before-exit.test.js`, `tests/printers-whole-before-exit.test.js`: each process records the order in which it makes its streams blocking and writes to them — the check that fails on every runtime for a printer without the call — and the text a reader receives; nothing else about the stream changes, the guard included). `tests/exit-writes-inventory.test.js` is a syntactic tripwire, not a proof: it fails on a new exit with no such call before it in its block (or that is not listed with the bound that makes it safe: it writes nothing, or a constant), and on a call that comes after a write of its block or leaves out a stream written before the exit; it does not follow calls or control flow, and does not see writes made in an enclosing block, before an `await`, or through a helper. Copied verbatim into `plugins/pcf` (`scripts/validate-plugin-copies.js`), where it also cleans `pcf-push.js`'s receipt and guards the SDK workspace `makePcfSdk` makesapp-header-text.js ← an app's header texts (`name`, `description`) held to plain text at the HTTP client every SDK is made with (wired in `maker-sdk.js`): a PATCH of an app module row that carries one that is not a string is refused before any byte is sent — `APP_HEADER_NOT_PLAIN_TEXT`, an `SdkError` marked `transient: false` — whether it is the SDK's `patch`, a `patchRaw`, or a PATCH inside a raw change set (`postRaw` / `post` to `$batch`), because the SDK writes every text its workspace copy holds whenever its own comparison read of the header cannot be made (503, 403, a thrown error, an empty 200). The build takes such a text off the copy before its push, so this is the last line of defence, for a push of a copy it did not clean. A batch that names the app module table and cannot be read is refused too. A delegating Proxy: every member it does not judge runs on the client itself. Also how such a text reads in a message (`describeHeldAppText`), which the guard's refusals sharebatch-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 it@@ -2845,7 +2859,7 @@ scripts/plan-sections.js ← the three Markdown primitives every genpage-plan reader shares (`planSection` — one `## ` section, any letter case; `findMarkdownTable`; `parseMarkdownRows`), moved unchanged from the eval harness, which re-exports themgenpage-plan-semantics.js ← the plan's semantic records, read with no I/O (references/plan-schema.md, "Assumptions, data semantics and lookup metadata"): the written plan (`## Assumptions` / `### A<n>`; per page `#### Data semantics` / `##### R<n>`, `F<n>` and `#### Lookup metadata`) and the approval preview at its own levels (`### Assumptions` first, `### Data Semantics` / `### Lookup Metadata` grouped by page file), every entry rule and cross-reference (an assumption that exists, a quote the requirements hold, the exact `Unattended default:` record), the field-by-field comparison `genpage-plan-provenance.js` gates on, and the check of observed lookups against `get-lookup-metadata.js` evidence. Proves structure and agreement, not entailmentlookup-metadata.js ← `readLookupMetadata(sdk, tables)`: composes the SDK's `fetchEntityMetadata` (complete lookup targets) with `relationship-metadata.js` `readRelationshipsOf(…, 'ManyToOne', cache, { lookupDetails: true })` (every page; `ReferencedAttribute` and `ReferencingEntityNavigationPropertyName`, which the SDK projection drops) into concrete and shared paths; owns no HTTP. Every incomplete read fails the whole read. The table name, primary-id name, lookup-column names and target names the reader takes from the metadata answer must be strings; a null, boolean or array is never coerced to one of them and fails the read as incomplete (the primary name column is passed through as the SDK states it). A table the environment does not have is `LOOKUP_TABLE_NOT_FOUND`, not the SDK's `CONNECTION_ERROR`: the SDK's own read of the table is the first request made for it, and only a 404 of that read (`genpage-sdk.js` `missingTableOf`, as for `genpage.js types`) or of the lookup-details read says so; any other failure keeps the SDK's code- collection-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+ collection-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()` was `body.value ?? []` (the bundled one now refuses such an answer, as a bare `CONNECTION_ERROR`), and the bundle is not editedtemp-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 not used and is removed by the run that made it, which waits up to 10 s for other runs' holds to leave it (a listing Windows refuses for a moment is waited out too), removes it only while it is still the folder it made, and stops waiting once a listing shows anything but holds — when the wait runs out, or the run is killed while it waits, the folder is left; 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. On Windows a run HOLDS the folder while it judges it (three programs, about a second) — an empty file of its own, `.hold-<machine>-<pid>-<6 hex>`, put in once the access list of a folder it made is set and removed once its workspace is in it and recorded — because the end of every run that leaves nothing in the folder removes it (`rmdir`), and with several runs starting and ending at once the folder kept being removed and made again under each other's judgement until a run ran out of attempts and went to the plain temp folder; `rmdir` refuses a folder with a hold in it, and a sweep on Windows removes the hold of a run that is gone — only a hold carrying its own machine tag (`<machine>` is eight hex digits of a hash of the host name, as an owner record names its host), since a temp folder can be shared between machines and a pid says nothing on another (two host names can, rarely, share a tag; on a temp folder they share, the old fallback can then return); a POSIX sweep takes nothing for a hold. 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 build lock and the pages lock (`app-operation-lease.js`), the recovery records' writer lease (`record-lease.js`), 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?, unreadable?, inherited? }` — 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. A "no" about a list that is still only what the folder inherited (not protected, every entry `ID`) is `inherited`: that is also the list a folder another run made moments ago has until that run's icacls lands, and where the temp folder lets others write (`TEMP` on a data drive gives Authenticated Users "modify") a run that judged it then was refused the folder for the rest of its life; `temp-workspace.js` asks again about such a "no" after a pause while the folder is younger than `PROTECT_WINDOW_MS` (15 s), never remembers it meanwhile, and does not refuse the folder for good on it (the workspace goes to the plain temp folder only after the last attempt); 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 user@@ -2870,7 +2884,7 @@ scripts/workspace-storage-guard.js ← wraps the SDK's workspace storage so it can be CLOSED: once closed every call rejects, and the calls under way can be waited for (`guardWorkspaceStorage`) — what lets `genpage-sdk.js` remove a folder only after the storage calls that were writing into it have settledleft-on-disk.js ← `leftOnDiskWarning(disposed)`: the one wording of "the page workspace could not be removed, so page source may be left on disk: <folders>" — what every command that makes a page backend says when `dispose()` answers a non-empty `{ left }` (verify on stderr and in the result's `warnings`, the others in the result's `warnings` or on stderr), kept apart from the backend so a test that replaces the backend module does not have to replace it toogenpage-subarea.js ← `genPageSubArea(base, genPageId)`, `genPageSubAreaId(pageId)` and `GENPAGE_DEFAULT_VECTOR_ICON` (the icon the platform gives a page entry that names none, so a rebuild does not take it for a designer edit): the one shape a generative page has as a sub-area of an app's navigation (`{ ...base, type: 'GenPage', genPageId }`). The build's `appDef` and `placeInApp` — and a script that creates an app around a first page — all build it here- app-component-scope.js ← what an edit of an app that is not about its components may ADD to them, held at the SDK's transport (`makeAppComponentScope()`: `wrap(httpClient)`, `limit(appId, { views }, work)`). Every `pushArtifact('app', …)` of an existing app (the bundle's `appApi.update`) PATCHes the sitemap and then posts ONE AddAppComponents whose list it DERIVES: for each Entity sub-area the table, EVERY active Main form, EVERY active public view and EVERY chart, for each DashBoard sub-area the dashboard — whether or not the app has them, and `components.mainFormsByTable` narrows the Main forms alone. AddAppComponents only adds, so a page edit that went through it put back what the app's maker had taken out, and its publish made it live. The bundle is never patched and cannot be told to skip the derivation, so the page backend (`placeInApp`, `removeFromApp`) keeps the SDK's sitemap write and has the post limited where it leaves the process: to the views the edit pins, and — when none is left — not sent at all (the SDK is answered with the service's 204). The action is found by the PATH of the address, percent-decoded as a whole before its trailing slashes are dropped and its last segment is read (a query string or fragment that mentions the name is not it; `AddAppComponents%2F` and `%41ddAppComponents` are it, in another spelling), and every POST is read ONCE while an edit is open — its address as text, its body as the plugin's transport takes it (text as it is, bytes copied, an object serialized as the transport serializes it and read back as plain data) — decided on in that CANONICAL form and sent in that form in every branch (the action it cuts, another app's request, a request to another address, a batch), never the object, bytes or address the caller holds, which the transport would read again: a `toJSON`, a getter or an address that answers differently the second time cannot undo the limit, and JSON text and the UTF-8 bytes of it are parsed for the action. While an edit is open, a request that IS the action in a shape the limit does not read — another spelling of the name, an address or path that cannot be decoded, a body that is JSON text (for a `post`), is not JSON or cannot be serialized, or has no list — or that does not carry every view the edit pins (a view named as a reference, or left out), or a `$batch` that may carry the action, through `post` and `postRaw` alike (a part of a batch cannot be limited: one classifier reads a multipart batch request line by line and a JSON batch entry by entry, each address as any address is read, and a JSON batch after its JSON is), is REFUSED with the bundle's `SdkError` `APP_COMPONENTS_NOT_LIMITED`: not sent whole and not answered as done. A raw POST (`postRaw`: a real POST whose body the transport does not touch, which the bundle uses for `$batch` only) is told by its address exactly as a `post` is, so the action cannot escape the limit by the method that carries it: one to the action's address is limited as the object form is when its body is JSON text of the same object, the UTF-8 bytes of it or an object, and what goes on is a form the transport sends as it is — JSON text for text and for bytes (the transport would send a Buffer as `{"type":"Buffer",…}`), the plain object for an object — with any `Content-Length` the caller declared, in whatever spelling, rewritten to one header with the exact length of what is written; it is refused when its body cannot be read that way. The SDK reports that as a warning of the push ("one or more components were not pinned"), so the sitemap the edit saved stays saved and nothing unlimited reaches the app. A page is a GenPage sub-area, which needs nothing from the app's components, and everything the SDK derives belongs to a sub-area that was there before the edit. The build owns the whole app and never opens an edit; an SDK lent to the backend keeps its owner's transport, and is not limited. Pinned against the real bundle by `genpage-app-edit-real-bundle.test.js` — the re-vendor tripwire for the request's shape, which also pushes the app through the limit — over the plugin's own transport, under a fake service that reads the wire (the body as JSON, a `Content-Length` that must be its length) — with that request changed, or sent through the raw method, to see the limit and the refusal as the user does+ app-component-scope.js ← what an edit of an app that is not about its components may ADD to them, held at the SDK's transport (`makeAppComponentScope()`: `wrap(httpClient)`, `limit(appId, { views }, work)`). Every `pushArtifact('app', …)` of an existing app (the bundle's `appApi.update`) PATCHes the sitemap and then posts ONE AddAppComponents whose list it DERIVES: for each Entity sub-area the table, EVERY active Main form, EVERY active public view and EVERY chart, for each DashBoard sub-area the dashboard — whether or not the app has them, and `components.mainFormsByTable` narrows the Main forms alone. AddAppComponents only adds, so a page edit that went through it put back what the app's maker had taken out, and its publish made it live. The bundle is never patched and cannot be told to skip the derivation, so the page backend (`placeInApp`, `removeFromApp`) keeps the SDK's sitemap write and has the post limited where it leaves the process: to the views the edit pins, and — when none is left — not sent at all (the SDK is answered with the service's 204). The action is found by the PATH of the address, percent-decoded as a whole before its trailing slashes are dropped and its last segment is read (a query string or fragment that mentions the name is not it; `AddAppComponents%2F` and `%41ddAppComponents` are it, in another spelling), and every POST is read ONCE while an edit is open — its address as text, its body as the plugin's transport takes it (text as it is, bytes copied, an object serialized as the transport serializes it and read back as plain data) — decided on in that CANONICAL form and sent in that form in every branch (the action it cuts, another app's request, a request to another address, a batch), never the object, bytes or address the caller holds, which the transport would read again: a `toJSON`, a getter or an address that answers differently the second time cannot undo the limit, and JSON text and the UTF-8 bytes of it are parsed for the action. While an edit is open, a request that IS the action in a shape the limit does not read — another spelling of the name, an address or path that cannot be decoded, a body that is JSON text (for a `post`), is not JSON or cannot be serialized, or has no list — or that does not carry every view the edit pins (a view named as a reference, or left out), or a `$batch` that may carry the action, through `post` and `postRaw` alike (a part of a batch cannot be limited: one classifier reads a multipart batch request line by line and a JSON batch entry by entry, each address as any address is read, and a JSON batch after its JSON is), is REFUSED with the bundle's `SdkError` `APP_COMPONENTS_NOT_LIMITED`: not sent whole and not answered as done. The one change set read whole is the bundle's guarded pin (since model-apps 2.20.6: an unpublished default-mode push that holds the app token and reads a derived component missing from the current layer sends `PATCH {}` under that token, the action and an echoed `PATCH {}` as ONE change set): for an app with an edit open, exactly that change set is not sent, and the SDK is answered with a refused guard, so it sends its plain action once, limited as above — no app-row write, the writes of earlier releases; any other change set that names the action is refused. `placeInApp` reports in `pinnedViews` only the views the app's current layer is read back holding after the push, and warns of the rest. A raw POST (`postRaw`: a real POST whose body the transport does not touch, which the bundle uses for `$batch` only) is told by its address exactly as a `post` is, so the action cannot escape the limit by the method that carries it: one to the action's address is limited as the object form is when its body is JSON text of the same object, the UTF-8 bytes of it or an object, and what goes on is a form the transport sends as it is — JSON text for text and for bytes (the transport would send a Buffer as `{"type":"Buffer",…}`), the plain object for an object — with any `Content-Length` the caller declared, in whatever spelling, rewritten to one header with the exact length of what is written; it is refused when its body cannot be read that way. The SDK reports that as a warning of the push ("one or more components were not pinned"), so the sitemap the edit saved stays saved and nothing unlimited reaches the app. A page is a GenPage sub-area, which needs nothing from the app's components, and everything the SDK derives belongs to a sub-area that was there before the edit. The build owns the whole app and never opens an edit; an SDK lent to the backend keeps its owner's transport, and is not limited. Pinned against the real bundle by `genpage-app-edit-real-bundle.test.js` — the re-vendor tripwire for the request's shape, which also pushes the app through the limit — over the plugin's own transport, under a fake service that reads the wire (the body as JSON, a `Content-Length` that must be its length) — with that request changed, or sent through the raw method, to see the limit and the refusal as the user doesgenpage-base.js ← base-marker hash, compare, and read/write (sibling dotfile of the code file; no environment URL; `appId` is optional — a page created before any app held it is recorded with the page alone, and the first update that names the app it was then placed in goes ahead on that marker and records the app; `unfinished` (`publish` or `place`) is set only by an upload that CREATED the page and did not finish it, and is what lets `genpage-upload.js --page-id` finish exactly that page — it is cleared when the page is finished, and `genpage-base.js record` never writes it)safe-fs.js ← confined output writes and deletes: the named directory's final component must not be a link or junction (readlink, not a path-text compare, so an 8.3 name and a share root stay usable); write via exclusive temp + rename, or — with `exclusive: true` — never replace a name: the content goes to a sibling file this process created exclusively and is published with a hard link to the target name (which fails if the name exists, so the file system decides and a file that appeared meanwhile is never overwritten: `IO_ERROR` with `reason: 'exists'`; where hard links do not exist the write fails closed, `reason: 'no-hard-links'`), and only that sibling is ever removed — retried, and reported (a warning after a publish, the error after a failure) when it cannot be — and a later write of a file that still has its second name is refused naming it. Everything it writes or appends has the access tokens the process obtained taken out first (`lib/output-redaction.js` `redactFileData`: a text as a text; bytes — any ArrayBuffer view, or a string given with a `hex`, `base64` or `base64url` encoding — masked with as many `*`, and data it cannot read refused before anything is written): it is the one writer of the build's journal and status file, of a download's files and of a page's file and its deployed copy. Shared by genpage markers and later callershydrate-spec.js ← reconstruct an App Spec from a deployed app (edit flow)@@ -3110,7 +3124,7 @@ Feature dependencies remain separate from their committed defaults:Note the maker-facing name is "Custom API" while the shipped wire contract stays`actionBindings` / `executeAction` (see `references/custom-api.md`).- **`custom-telemetry` (OFF)** — the page telemetry facade in the UCI host runtime, the GenUX- authoring control (power-platform-ux), the AIBuilder CoderAgent telemetry prompt, and the+ authoring control, the AIBuilder CoderAgent telemetry prompt, and the`GenUxEnableCustomTelemetry` ECS setting (see `references/page-telemetry.md`).- **`dataverse-operations` (OFF)** — a host runtime that implements `executeFunction`, the page`actionBindings` the plugin writes into `config.json`, and the `GenUxPluginActionAllowList`@@ -4191,7 +4205,7 @@ Dataverse simply are not in it.| Hatch | Use for | Examples in tree ||---|---|---|-| `dataverseRequest()` in `lib/dataverse-auth.js` (and the `dataverse-request.js` CLI) | Dataverse surfaces the SDK does not model at all | `WhoAmI` (`check-auth.js` — an authentication probe, never a page's built-in operation binding), `customapis` (`list-custom-apis.js`), `connectionreferences` (`create-connection-reference.js`), solution-component adds (`add-page-to-solution.js`) |+| `dataverseRequest()` in `lib/dataverse-auth.js` (and the `dataverse-request.js` CLI) | Dataverse surfaces the SDK does not model at all | `WhoAmI` (`check-auth.js` — an authentication probe, never a page's built-in operation binding; and its one capability read of `solutions`, which tells a user with no security role from one who can build), `customapis` (`list-custom-apis.js`), `connectionreferences` (`create-connection-reference.js`), solution-component adds (`add-page-to-solution.js`) || The raw `httpClient` from `createAzHttpClient` | A surface the SDK *does* touch but whose response it **projects away** | **No caller today.** The one that existed — `entityPrivileges` in `verify-model-app.js` — is gone: the SDK had no privilege READ at all, and `fetchEntityMetadata` drops `Privileges` permanently by design, so the check composed its own `EntityDefinitions(...)?$select=Privileges` request. The vendored bundle now carries `getEntityPrivileges`, and the reader takes it. The hatch stays documented because the *category* recurs; opening it again needs the same justification |**Prefer `dataverseRequest()` over the raw client.** It already handles the API path, auth, headers@@ -4272,7 +4286,7 @@ When you do go direct, all four of these apply:node scripts/run-tests.js# Plugin suite + the vendored SDK's Jest suite (Node 20):-NODE20_BIN=/path/to/node20/bin node scripts/run-tests.js --with-sdk /path/to/power-platform-ux+NODE20_BIN=/path/to/node20/bin node scripts/run-tests.js --with-sdk /path/to/sdk-repo```- `run-tests.js` runs the full `scripts/tests/*.test.js` suite and prints a combined PASS/FAIL.@@ -4315,20 +4329,20 @@ NODE20_BIN=/path/to/node20/bin node scripts/run-tests.js --with-sdk /path/to/powstep fails the PR.**The vendored SDK lives in a separate repo.** The Dataverse mechanics are in-`power-platform-ux` (Azure DevOps `msazure/OneAgile`), package `packages/cds-maker-sdk`. This plugin+that repo's `packages/cds-maker-sdk` package. This pluginships a **self-contained bundle** at `scripts/vendor/cds-maker-sdk.cjs` (NOT the SDK source). The SDKowns deterministic wire formats (create/query/delete, AI settings/row-summaries, `seedRecordGraph`,`enrichDefaultViews`, artifact resolve/cascade); the plugin owns judgment (spec validation, candidateselection, prompt authoring). To change SDK behavior:```bash-# 1. Build the SDK (emits lib/) — from <ppux>/packages/cds-maker-sdk:-npm run build # tsc/ppux-build+# 1. Build the SDK (emits lib/) — from <sdk-repo>/packages/cds-maker-sdk:+npm run build # tscnpm test # Jest (Node 20)-npm run lint # ppux-lint (Node 20)+npm run lint # (Node 20)# 2. Rebuild the vendored bundle here (reads the SDK's lib/, so build the SDK first) — from repo root:-node plugins/model-apps/scripts/_vendor-build/build.js --sdk /path/to/power-platform-ux+node plugins/model-apps/scripts/_vendor-build/build.js --sdk /path/to/sdk-repo# → rewrites scripts/vendor/cds-maker-sdk.cjs (~540 KB). COMMIT the rebuilt bundle.```@@ -4342,7 +4356,14 @@ reverts it and the hash in `PROVENANCE.json` stops matching. Fix it upstream and`PROVENANCE.json`), loaded by `scripts/lib/typescript-compiler.js` and passed to the SDK as`MakerSdkOptions.typescript`. The SDK compiles a page's source itself on every push that changes it — TypeScript's`transpileModule` plus its checker, to resolve enum names — and accepts only the minor version the maker portal compiles-with (5.8; another is refused with `GENPAGE_COMPILER_VERSION`), so a page is stored as the portal would store it. That compile is a+with (5.8; another is refused with `GENPAGE_COMPILER_VERSION`), so a page is stored as the portal would store it. Since model-apps+2.20.6 the bundled SDK compiles with iterator support (ES5 with `downlevelIteration`, its default iteration profile), as the maker+portal's page compiler source does: a spread, a `for...of` loop or an array destructure of a Map, Set, iterator or string reads it as+modern JavaScript does. A tool that compiles the page again without it (an older portal, `pac`) reads them by length and index and+loses their values, so `references/rules.md` Critical Rule 24 keeps `Array.from`; `iteration-emit.test.js` runs both emits and pins the+one the bundle stores. A push keeps a page's usable stored compiled output only when its source AND its data sources are unchanged; any+other push compiles again, so a page uploaded by an earlier release keeps the old emit until its source or its data sources change, and+that compile then reads the iterable values the old emit lost. That compile is atranspile, not a type check: a page with type errors, or a reference to a column its table does not have, compiles and deploys, and onlya page that does not parse, has no default export or imports a value `RuntimeTypes` does not hold is refused(`genpage-sdk-real-bundle.test.js` runs it against the real bundle). The page-builder's Step 2.6 says so, and@@ -4477,6 +4498,23 @@ artifacts, 2xx statuses, green build. The test therefore does two things: a **sofails on any un-awaited `provision.*`/`sdk.*` call to those methods (annotate a deliberate one with`sdk-async-ok`), and a **dynamic check** that the real bundle still returns Promises for exactly thatlist — so if a future SDK makes one synchronous again, the scan can't go on enforcing a dead rule.++Four more files watch the SDK boundary at every re-vendor:++- **Lifecycle request trail.** `scripts/tests/lifecycle-trail-golden-real-bundle.test.js` pins every request of the kitchen-sink lifecycle+ (build, unchanged rebuild, edit rebuild, download, verify, teardown) over the real bundle: method, path and query, body shape with list+ lengths, status, and everything each publish names (`scripts/tests/golden/lifecycle-trail.*.txt`). On a difference, map each one to a+ release-note line (or to the change that made it), then regenerate on a developer machine:+ `UPDATE_GOLDENS=1 node --test scripts/tests/lifecycle-trail-golden-real-bundle.test.js` — that run FAILS by design (a run that rewrites a+ golden never passes); run it again without `UPDATE_GOLDENS` and review the goldens' diff. Under CI (`CI`, `GITHUB_ACTIONS` or `TF_BUILD`+ set) `UPDATE_GOLDENS=1` is refused: the run fails and never rewrites the committed goldens.+- **SDK codes.** `scripts/tests/sdk-error-codes-real-bundle.test.js` fails when the bundle can report a code that+ `scripts/tests/fixtures/sdk-error-codes.json` does not classify (or no longer reports one it lists). Classify a new code first — a write+ whose outcome is unknown goes to `OUTCOME_UNKNOWN_CODES` (`lib/retry-policy.js`), a page refusal raised before any write to+ `PRE_WRITE_REFUSALS` (`lib/genpage-sdk.js`), a maker step to `operatorRemedy` (`lib/entity-provision.js`) — then add it to the fixture.+- **SDK options and publication.** `sdk-options-real-bundle.test.js` fails when an option a script passes is no longer read by the bundle+ or no longer has its effect; `sdk-publication-real-bundle.test.js` pins what the SDK publishes by itself (a page push: nothing; an app+ update: only with `published: true`).The same file pins the **throwaway-workspace lifecycle**: a CLI that makes a temporary workspace mustbuild its SDK behind a `try` whose own `catch` or `finally` removes it (`cleanup()`, `dispose()` or`rmSync`), or a failed construction strands the directory. The guard is read from the syntax tree — the@@ -4550,6 +4588,20 @@ to look at the change in Maker and put into the spec what should stay, then makere-download is no substitute: it captures no forms, views or charts, and an interrupted first buildcan leave them before the app exists.)+`scripts/tests/workspace-upgrade-real-bundle.test.js` and `workspace-upgrade-entry-real-bundle.test.js` prove the+upgrade end to end with BOTH bundles (`tests/helpers/workspace-upgrade.js`): the previous release's bundle builds the+lifecycle kitchen-sink app, and the FIRST thing the vendored one does on that workspace — an unchanged rebuild, an+edited rebuild (with verify), a download, or a teardown, each its own path from the state the previous bundle left — is+compared with the same step on a workspace the vendored bundle wrote (same writes, same features, same verify report,+same downloaded spec). The edited path also keeps, by content, a view filter the typed view model does not hold (a+Quick Find marker below the top-level filter and a multi-value condition) that a maker added and the previous bundle+read. `bpf-stage-edits.test.js` and `business-rules.test.js` hold the same for a flow and a rule the previous bundle+created. A command bar's or a rule's old copy is never re-read: the build never pushes an existing one, so it is never+refused either. The previous bundle comes from `tests/helpers/previous-bundle.js` — the file `MODEL_APPS_PREVIOUS_BUNDLE`+names (CI fetches the release commit by hash in both suite jobs) or else git history, its SHA-256 checked; without it+the tests skip locally and FAIL in CI. On the next re-vendor, point `PREVIOUS_RELEASE` and `PREVIOUS_BUNDLE_SHA256`+there, and the workflow's fetch (`run-tests.test.js` holds them equal), at the release being replaced.+**Newer SDK behaviors the plugin adopts, and the options it leaves off.** Each is pinned against thereal bundle, because a stub stays green through a change in the SDK's own rule.@@ -4721,8 +4773,9 @@ real bundle, because a stub stays green through a change in the SDK's own rule.option and filters nothing of its own for `custom`. Without `--search` and `--type` the answer is everytable (about 200 KB for 1,700): the planner's dominant-prefix read, which wants only the custom tables,can ask for `--type custom`, and a caller that needs a few tables searches for them.- **An answer that is no list of tables.** `findTables()` reads a 2xx answer with no `value` list as `[]`- (`body.value ?? []`), and the HTTP client keeps a body that is not JSON as text, so a sign-in or proxy page, `{}`+ **An answer that is no list of tables.** The SDK's `findTables()` used to read a 2xx answer with no `value` list as `[]`+ (`body.value ?? []`; the bundled SDK now refuses it itself, but as a bare `CONNECTION_ERROR` of the 200 it read — "malformed+ page" — with no code of this plugin's and no remedy), and the HTTP client keeps a body that is not JSON as text, so a sign-in or proxy page, `{}`and `null` all read as an environment with no table — and `--exact` would then report every searched table as`missing`, which the planner reads as "create it". The bundle is not edited, so `lib/maker-sdk.js`, the one way ascript makes an SDK, hands every SDK a client whose read of the table list (`/EntityDefinitions?…`, which only@@ -4745,8 +4798,10 @@ real bundle, because a stub stays green through a change in the SDK's own rule.reason and no delete is sent, while teardown's other steps run as usual. Read as "no tables" it skipped thesystem-table check, and where an environment answers every request with a page it answered the DELETE with one too,which the SDK takes for done and `tolerateNotFound`- for gone — a table reported deleted that nothing deleted; any other failure of that read keeps its documented- handling, and the delete goes on. **The verifier's catalog** (`verify-model-app.js`) fails the verify, where "no+ for gone — a table reported deleted that nothing deleted. Any other failure of that read fails the step closed too+ (since 2.20.6): the bundled SDK reads the list to its end and refuses one that says more rows exist without a link,+ or whose next page fails, and a refused read (403) says no more — after any of them nothing says the table is gone+ or not a system table, so no DELETE is sent from half an answer (`unreadable-table-list-callers.test.js`). **The verifier's catalog** (`verify-model-app.js`) fails the verify, where "notables" reported every declared table missing. `apps.js list` (`collectionRows`: `no readable result set`) and`list-languages.js` (the SDK's strict reader: `ENVIRONMENT_LANGUAGES_UNREADABLE`) were probed with the same bodiesand do not have the hole. `unreadable-collection-answers.test.js` runs those three over the real client and the real@@ -5638,11 +5693,16 @@ that keeps an `external` web resource. Expect a clean environment afterwards *exconfirming it owns no other solution.**`appmodulecomponent` rows also survive an app delete, and teardown deliberately leaves them** — this-has been re-reported as a teardown bug and re-measured. The platform exposes no way to remove them:-the table registers only `Retrieve`/`RetrieveMultiple` (a direct `DELETE` 400s), and-`RemoveAppComponents` returns `204` while removing nothing as long as the app exists, then `404`s once-it is gone. Calling it would report a cleanup that never happened. The rows are unreachable metadata-that a rebuild neither adopts nor trips over; revisit only if the platform adds a delete or a cascade.+has been re-reported as a teardown bug and re-measured. Measured: the component rows an app records, of+every type (tables, forms, views, charts, the sitemap), survive its delete, and no tested sequence removes+them all. The table registers only `Retrieve`/`RetrieveMultiple` (an exact-id `DELETE` answers 400+`0x80040800`). `RemoveAppComponents` before the delete acts on the app's current layer only: a published+app gains a pending copy of its components, publishing it without its sitemap is refused (`0x80050114`),+and even one atomic change set of the removal, the app delete and the sitemap delete leaves the published+layer's rows. After the delete, `RemoveAppComponents` answers 404 (`0x80040217`). The bundled SDK's app+delete is unchanged for the same reason, and teardown does not try a removal that would report a cleanup+that never happened. The rows are unreachable metadata that a rebuild neither adopts nor trips over;+revisit only if the platform adds a delete or a cascade.**After modifying the plugin also:** run `claude --debug` to confirm the plugin loads, exercise theskill (`/genpage` or `/app-builder`), and for genpage verify Playwright browser checksdiff --git a/plugins/model-apps/CHANGELOG.md b/plugins/model-apps/CHANGELOG.mdindex 28e340469..49d655ac7 100644--- a/plugins/model-apps/CHANGELOG.md+++ b/plugins/model-apps/CHANGELOG.md@@ -5,9 +5,38 @@ 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.20.6]++The bundled SDK is updated (commit 59ae2d72e2a8).++### Fixed++- **Pages that loop over or spread a `Map`, `Set`, iterator or generator now show their values**; an existing page takes+ the fix at its next upload that changes its source or data sources.+- **Where the environment refuses every business rule** (HTTP 400 `0x80040216`, common on production), a build warns once,+ skips the rules and builds the rest of the app.+- **`check-auth` rejects an account Dataverse reports as having no security role** (`0x80042f09`) instead of calling it ready.+- **Teardown never deletes a table after an incomplete table listing.**+- **Date and Time columns state their behaviour (User local, as before)**, so later columns on the table are not refused.+- **A page too deep to compile is refused as `PAGE_NESTING_TOO_DEEP` with nothing written**, also when the SDK's+ compiler catches it.++### Changed++- **Eligible app rebuilds check the app's version before adding components** (one read, two more on a match, more when results+ page); missing components then use one version-guarded change set; later publishes re-read the app.+- **Adding a page to an app, or removing it, reads the app more**; it keeps its plain, limited component add, and `pinnedViews`+ lists only views the app holds afterwards.+- **Every view update names its table**, as the maker portal does.+- **Workspaces from an earlier release refresh on the first build**; interrupted, unpushed edits still need the build's reset.+- **A page update's version checkpoint is named after its conversation turn.**+- **Page compilation reads array-destructuring elements before their defaults run**; if a default changes a later element, split+ those assignments as the page rules show.+- **A Date and Time column without a behaviour stops the build**, naming the columns to set to User local.+## [2.20.4]-The bundled SDK is unchanged (power-platform-ux a3443479).+The bundled SDK is unchanged (commit a3443479).### Fixed@@ -21,7 +50,7 @@ The bundled SDK is unchanged (power-platform-ux a3443479).## [2.20.3]-The bundled SDK is unchanged (power-platform-ux a3443479).+The bundled SDK is unchanged (commit a3443479).### Fixed@@ -38,7 +67,7 @@ The bundled SDK is unchanged (power-platform-ux a3443479).## [2.20.2]-The bundled SDK is unchanged (power-platform-ux a3443479).+The bundled SDK is unchanged (commit a3443479).### Fixed@@ -47,7 +76,7 @@ The bundled SDK is unchanged (power-platform-ux a3443479).## [2.20.1]-The bundled SDK is unchanged (power-platform-ux a3443479).+The bundled SDK is unchanged (commit a3443479).### Fixed@@ -57,7 +86,7 @@ The bundled SDK is unchanged (power-platform-ux a3443479).## [2.20.0]-The bundled SDK is unchanged (power-platform-ux a3443479).+The bundled SDK is unchanged (commit a3443479).### Added@@ -90,7 +119,7 @@ The bundled SDK is unchanged (power-platform-ux a3443479).- Evals: an ungraded fixture is not counted as passed; the label check reads comments and character references.## [2.19.0]-The bundled SDK is unchanged (power-platform-ux a3443479, as in 2.18.0).+The bundled SDK is unchanged (commit a3443479, as in 2.18.0).### Changed@@ -117,7 +146,7 @@ The bundled SDK is unchanged (power-platform-ux a3443479, as in 2.18.0).## [2.18.0]-The bundled SDK is updated to power-platform-ux a3443479.+The bundled SDK is updated to commit a3443479.### Added@@ -149,7 +178,7 @@ The bundled SDK is updated to power-platform-ux a3443479.## [2.17.0]-The bundled SDK is updated to power-platform-ux d603c799.+The bundled SDK is updated to commit d603c799.### Changed@@ -179,7 +208,7 @@ The bundled SDK is updated to power-platform-ux d603c799.## [2.16.0]-The bundled SDK is updated to power-platform-ux ccf2c1a1. A new table's primary column is created required when the spec says so,+The bundled SDK is updated to commit ccf2c1a1. A new table's primary column is created required when the spec says so,and navigation titles survive a download and rebuild in any base language.### Changeddiff --git a/plugins/model-apps/agents/genpage-page-builder.md b/plugins/model-apps/agents/genpage-page-builder.mdindex 360aa398b..970b935ef 100644--- a/plugins/model-apps/agents/genpage-page-builder.md+++ b/plugins/model-apps/agents/genpage-page-builder.md@@ -192,21 +192,24 @@ and look at each match: one inside a `makeStyles` object is the defect, and onea string, a comment or an inline `style={{ … }}` is fine. Do not return a file thatstill has one in a `makeStyles` object.-## Step 2.7 — Iteration that compiles to nothing--The page compiler targets ES5 without iterator downleveling or full type checking.-Spreading, looping over, or array-destructuring a Map, Set or iterator reads length-and indices instead of the iterator: values can disappear, defaults can replace them,-or rest destructuring can throw. This includes `[...new Set(xs)]`, `[...m.values()]`,-`[...seen.values()]`, `for (const [k, v] of m)`, `new Set([...prev, id])`,-`[...selected]` and `[...text.matchAll(re)]`. Convert with `Array.from(...)` before-spreading, looping or destructuring; copy a Set with `new Set(prev)` then `.add(id)`.-Ordinary array spreads and loops remain valid. `Object.keys`, `Object.values` and-`Object.entries` return arrays. Spreads of `arguments` and ordinary indexed array-likes-work; rest destructuring of an array-like without `slice` does not. String spread-throws, and an ES5 string loop visits UTF-16 code units rather than Unicode code-points. See **Common Errors > 5. Iteration that compiles to nothing** in-`references/rules.md` for the pairs.+## Step 2.7 — Iteration that another page compiler can lose++Pages this plugin uploads are compiled with iterator support (ES5 with+`downlevelIteration`), so a spread, a `for...of` loop or an array destructure of a Map,+Set, iterator, generator or string reads it as modern JavaScript does. A tool that+compiles the page again without that support — an older maker portal, or `pac` — reads+length and indices instead: values disappear, defaults replace them, and rest+destructuring or a string spread throws, all with a clean compile. Keep the page correct+under every compiler: convert with `Array.from(...)` before spreading, looping or+destructuring, for example `[...new Set(xs)]`, `[...m.values()]`, `[...seen.values()]`,+`for (const [k, v] of m)`, `new Set([...prev, id])`, `[...selected]` and+`[...text.matchAll(re)]`; copy a Set with `new Set(prev)` then `.add(id)`. Ordinary+array spreads and loops remain valid. `Object.keys`, `Object.values` and+`Object.entries` return arrays. Rest destructuring of a non-iterable array-like without `slice`+throws under every compiler. A destructuring default must not write to the array being+destructured: `const [a = (values[1] = 3), b] = values` leaves `b` at its old value+here, unlike modern JavaScript. See **Common Errors > 5. Iteration that another page+compiler can lose** in `references/rules.md` for the pairs.Before returning, review every spread (`...`), `for...of` loop and array destructureyou wrote. Wherever the value can be a Map, a Set, one of their `keys()`, `values()`diff --git a/plugins/model-apps/docs/app-builder-capabilities.md b/plugins/model-apps/docs/app-builder-capabilities.mdindex 3cced7e73..9e25ec874 100644--- a/plugins/model-apps/docs/app-builder-capabilities.md+++ b/plugins/model-apps/docs/app-builder-capabilities.md@@ -23,7 +23,7 @@ apart deliberately.- **All Dataverse access via the vendored headless SDK**; metadata cached under `<app-folder>/.maker-workspace/` for reuse.- Phase selection (`--only`/`--skip`/`--from`/`--to`), `[n/total]` narration, `BuildHalt` gate, dry-run by default, `--sample-data` / `--publish` opt-in.- Bounded-concurrency for independent ops; one publish round-trip per entity + the app. A rebuild that changes nothing writes almost nothing: an existing view or form is pushed only when it differs from what was last synced, under `--publish` the tables the build changed, the tables whose Main forms its own pushes of the app add (those of the navigation each push sends), and the tables whose forms or charts the app is known to hold, are published together in one round-trip before the app (a publish naming only the app, sent first, leaves a saved form's label changes unpublished, whoever saved them) instead of once per view and form — a table the app is not known to hold a form or chart of (declared only, a lookup column's target, read only by a page, or only pinned in `app.tables`) is not published by it — and a solution's membership is read once so only the components it lacks are added. `az`-token HttpClient with transient (429 / 5xx) retry, honouring `Retry-After` up to 60 s (a 429 is waited out inside the run's throttle budget, below); a record delete, or a change set of conditional deletes (an app and its sitemap), is sent once unless its answer proves it did not run: SQL rolled it back as a deadlock victim (`Sql Number: 1205` — the last SQL number the answer gives, so a name a maker chose that quotes it in front of another SQL error is not one; for a change set, on every operation it answers; re-sent up to three times), or the server refused to start it with a 429 (re-sent on the throttle schedule). A change set that only creates columns (a new table's ordinary columns) is re-sent on a 429 alone, because a change set can commit behind any other lost or failed answer. The SDK separately re-sends an app delete that meets the platform's search-index insert race (HTTP 400, SQL 547) — a different answer, so the two layers add and never multiply. A generative page's change set is not re-sent by the client at all (an update's writes carry `If-Match: *`, so a replay would skip the SDK's version check): the page backend (`lib/genpage-sdk.js`) waits out a 429 on it — the same schedule, or the answer's `Retry-After` when that is longer, whole — and sends it again, a push at a time and through the SDK's version check each time, because a refused change set committed nothing and the page's ids and the turn's identity were fixed before the first send; six sends at most, inside one budget of five minutes for the waiting a throttled page write costs a build run (the build's own waits before it runs a phase again count too, and so do the HTTP client's own waits for a throttled read, publish, delete or column create — the answer's `Retry-After` whole, past the client's cap of a minute — and a wait of the client's that does not fit is not taken: the 429 comes back as it came and the build stops with the budget's halt; a 5xx, a reset connection and a deadlock victim's re-send are not throttling and keep their own schedule; and a change set the service refuses as a whole — answered HTTP 200 with the one part that failed — is read the same way, when the answer is complete and well-formed: a 429 is waited out, a 400, 403 or 404 is final after one send, and an answer that is incomplete inside — or holds a part that declares a transfer coding, which is not read — stays an unknown outcome), and a throttle that outlasts them leaves the build to run the pages phase again after the wait the service asked for, or to stop with a `throttle-budget-exhausted` halt that says what it asked when the next wait does not fit. A failure of the transport is sent again only when it is a reset, a timeout, an answer cut off or a temporary DNS failure — decided by Node's own error code when it has one and by its words only when it has none: a certificate that does not verify returns at once, whatever names it quotes.-- Guardrail lint (`spec-lint.js`) + hard validator (`app-spec.js`). 🧪 full `node:test` suite + the vendored SDK's Jest suite green (`node scripts/run-tests.js --with-sdk <ppux>`).+- Guardrail lint (`spec-lint.js`) + hard validator (`app-spec.js`). 🧪 full `node:test` suite + the vendored SDK's Jest suite green (`node scripts/run-tests.js --with-sdk <sdk-repo>`).### Data model (Tier 1) — ✅ verified live- All column types: Text · Memo · Choice · MultiChoice · Boolean · Money · DateTime · Integer · BigInt · Decimal · Double · File · Image · AutoNumber · Customer (with per-type options), incl. AutoNumber primary columns.@@ -59,7 +59,9 @@ apart deliberately.that did not say what the author wrote. An environment that does not declare that member **cannothost business rules** — and that is the common case rather than an edge case. Where the member isdeclared, a rule can still fail with a server-side MissingMethodException, which is a platform- defect on that environment rather than a rule-shape problem. The build then skips them,+ defect on that environment rather than a rule-shape problem. A production environment declares the+ member but answers the first rule with HTTP 400 `0x80040216` ("An unexpected error occurred."),+ a platform limit; nothing is created. The build then skips them,warns once naming the member, and builds everything else normally; `--verify` reports them as *notapplicable on this environment* rather than missing, so the exit code, the deployed baseline andthe `--changed-only` snapshot are unaffected.diff --git a/plugins/model-apps/references/app-spec-schema-advanced.md b/plugins/model-apps/references/app-spec-schema-advanced.mdindex 4069dc875..2b042e9c2 100644--- a/plugins/model-apps/references/app-spec-schema-advanced.md+++ b/plugins/model-apps/references/app-spec-schema-advanced.md@@ -131,10 +131,17 @@ Reference from a column via `"globalChoice": "new_priority"` (built before the c- **Environment gate — read this first.** The SDK writes a rule through the bound`CreateProcessWithWfomJson` member, the same one the modern business-rule designer uses, and has**no fallback**. An environment that does not declare that member cannot host business rules at- all, and that is the common case rather than an edge case. The build then- **skips** `businessRules[]`, warns once naming the member, and builds everything else normally —- so you get a working app without the rules, not a half-built one. `--verify` will report those- rules as not deployed, which is the truth.+ all, and that is the common case rather than an edge case. **Production environments are the+ other common case**: they declare the member but have it switched off, so the first rule fails+ with HTTP 400 `0x80040216` ("An unexpected error occurred.") whatever the rule says, and nothing is+ created — a platform limit, not a fault in the rule. In both cases the build+ **skips** `businessRules[]`, warns once (naming the member or the code), and builds everything+ else normally — so you get a working app without the rules, not a half-built one. A 400+ `0x80040216` is read this way only for the first rule of a build, and only when a read right+ after it finds no new definition of that rule (the platform can also save a rule and then fail+ with the same answer). Otherwise — a new definition, a rule created earlier in the build, or any+ other code or status — the build halts as before. `--verify` will report those+ rules as not applicable on this environment, which is the truth.- **Same-name definitions are not automatically disposable.** Rebuild reuses the oldest matchingdefinition and keeps additional pre-existing ids with a warning. After a create, the SDK's returneddefinition is kept. Every other same-name id is reported as not attributable to this run, includingdiff --git a/plugins/model-apps/references/rules.md b/plugins/model-apps/references/rules.mdindex 7abe8c76a..87606e186 100644--- a/plugins/model-apps/references/rules.md+++ b/plugins/model-apps/references/rules.md@@ -29,7 +29,7 @@ Comprehensive rules for generating generative page code. Read this file during c21. **End final type-argument statements with `;`**: If the file's last statement ends in a type argument list (`Page<string>`, `Array<Row>`), terminate it with a semicolon.22. **Consistent errors**: Route failed data operations through the page's single top-level `reportPageError`, retain bounded code and message diagnostics, and put its returned view in the operation's error state. Render errors as escaped Fluent MessageBar text with localized application fallbacks. Offer manual retry only for proven-safe reads or the documented pre-dispatch Custom API network result; never retry an indeterminate result automatically. Wrap PageBody in the page's one top-level React PageErrorBoundary. Instrument only explicitly authorized failure sites, only through the helper. Expected null/empty states are not failures. See “Missing Error Handling” for the canonical patterns and the static check's declared limits.23. **Lookup identities**: A lookup reference is a validated table-and-bare-id pair, not its label or the first metadata target. Normalize bare GUID and `/<table>(<guid>)` read values using the logical-name annotation and/or qualified prefix, checking both against metadata and rejecting conflicts. Use the bare id for filters, retrieval and navigation; rebuild the qualified value only for writes. Record every lookup used by a join/filter and its complete target set in Per-Page Specifications. Ask about unresolved relationship/filter meaning; never broaden a failed typed query. Unresolved references cannot trigger target-dependent actions. See **DataAPI Rules > Lookup references** for the canonical `normalizeLookupReference` and the five WRONG/CORRECT pairs.-24. **Convert iterables to arrays**: The page compiler targets ES5 without iterator downleveling or full type checking. Spreading, looping over, or array-destructuring a Map, Set or iterator reads length and indices instead: values can disappear, defaults can replace them, or rest destructuring can throw. Never write `[...new Set(xs)]`, `[...m.values()]`, `for (const [k, v] of m)`, `new Set([...prev, id])`, `[...selected]` or `[...text.matchAll(re)]` directly; convert with `Array.from` or copy a Set natively. See **Common Errors > 5. Iteration that compiles to nothing**.+24. **Convert iterables to arrays**: Pages this plugin uploads compile with iterator support, but a page compiled again by an older maker portal or `pac` reads a Map, Set or iterator by length and indices: values can disappear, defaults can replace them, or rest destructuring can throw. Write `[...new Set(xs)]`, `[...m.values()]`, `for (const [k, v] of m)`, `new Set([...prev, id])`, `[...selected]` and `[...text.matchAll(re)]` through `Array.from`, or copy a Set natively, so the page is correct under every compiler. See **Common Errors > 5. Iteration that another page compiler can lose**.---@@ -1331,16 +1331,16 @@ const useStyles = makeStyles({});```-### 5. Iteration that compiles to nothing+### 5. Iteration that another page compiler can lose-The page compiler targets ES5 without iterator downleveling or full type checking. Spreading, looping over, or array-destructuring a Map, Set or iterator reads length and indices instead of the iterator: values can disappear, defaults can replace them, or rest destructuring can throw. This includes `[...new Set(xs)]`, `[...m.values()]`, `[...seen.values()]`, `for (const [k, v] of m)`, `new Set([...prev, id])`, `[...selected]` and `[...text.matchAll(re)]`. Convert with `Array.from(...)` before spreading, looping or destructuring; copy a Set with `new Set(prev)` then `.add(id)`. Ordinary array spreads and loops remain valid. `Object.keys`, `Object.values` and `Object.entries` return arrays. Spreads of `arguments` and ordinary indexed array-likes work; rest destructuring of an array-like without `slice` does not. String spread throws, and an ES5 string loop visits UTF-16 code units rather than Unicode code points. See **Common Errors > 5. Iteration that compiles to nothing** in `references/rules.md` for the pairs.+Pages this plugin uploads are compiled with iterator support (ES5 with `downlevelIteration`), so a spread, a `for...of` loop or an array destructure of a Map, Set, iterator, generator or string reads it as modern JavaScript does. A tool that compiles the page again without that support — an older maker portal, or `pac` — reads length and indices instead: values disappear, defaults replace them, and rest destructuring or a string spread throws, all with a clean compile. Keep the page correct under every compiler: convert with `Array.from(...)` before spreading, looping or destructuring, for example `[...new Set(xs)]`, `[...m.values()]`, `[...seen.values()]`, `for (const [k, v] of m)`, `new Set([...prev, id])`, `[...selected]` and `[...text.matchAll(re)]`; copy a Set with `new Set(prev)` then `.add(id)`. Ordinary array spreads and loops remain valid. `Object.keys`, `Object.values` and `Object.entries` return arrays. Rest destructuring of a non-iterable array-like without `slice` throws under every compiler. A destructuring default must not write to the array being destructured: `const [a = (values[1] = 3), b] = values` leaves `b` at its old value here, unlike modern JavaScript. See **Common Errors > 5. Iteration that another page compiler can lose** in `references/rules.md` for the pairs.-A Dropdown built from `[...seen.values()]` can open with no options despite a clean compile. The same problem affects native collection iterators, generators, native `matchAll` results, `URLSearchParams`, `FormData` and `Headers`. JSX expressions use the same emit.+Under such a compiler a Dropdown built from `[...seen.values()]` opens with no options despite a clean compile — what pages uploaded before model-apps 2.20.6 did. The same problem affects native collection iterators, generators, native `matchAll` results, `URLSearchParams`, `FormData` and `Headers`. JSX expressions use the same emit. Each WRONG example below except the last works in a page this plugin uploads and fails as its comment says under a compiler without iterator support; each CORRECT example works under both.**Map values**```typescript-// WRONG — the spread contributes no values+// WRONG — without iterator support the spread contributes no valuesconst seen = new Map([["a", 1], ["b", 2]]);const choices = [...seen.values()];```@@ -1354,7 +1354,7 @@ const choices = Array.from(seen.values());**Unique values**```typescript-// WRONG — unique becomes []+// WRONG — without iterator support unique becomes []const xs = [1, 1, 2];const unique = [...new Set(xs)];```@@ -1368,7 +1368,7 @@ const unique = Array.from(new Set(xs));**Map pairs**```typescript-// WRONG — the loop runs zero times+// WRONG — without iterator support the loop runs zero timesconst m = new Map([["a", 1], ["b", 2]]);const rows: Array<[string, number]> = [];for (const [k, v] of m) rows.push([k, v]);@@ -1386,7 +1386,7 @@ A native Map's `m.forEach((v, k) => { rows.push([k, v]); })` is an alternative,**Selection state — component-body examples; state values are not statically inferred**```typescript-// WRONG — the updater loses prior ids; chosen loses every selected value+// WRONG — without iterator support the updater loses prior ids; chosen loses every selected valueconst [selected, setSelected] = React.useState(new Set<string>());function addSelected(id: string) {setSelected(prev => new Set([...prev, id]));@@ -1412,7 +1412,7 @@ The Map and Set constructors consume iterables natively: `new Set(prev)` and `ne**Native matchAll result**```typescript-// WRONG — the match iterator has no array length+// WRONG — without iterator support the match iterator has no array lengthconst text = "a1 b2";const re = /\d/g;const hits = [...text.matchAll(re)].map(match => match[0]);@@ -1428,7 +1428,7 @@ const hits = Array.from(text.matchAll(re)).map(match => match[0]);**Destructuring**```typescript-// WRONG — first is undefined+// WRONG — without iterator support first is undefinedconst [first] = new Set([1, 2]);```@@ -1438,7 +1438,7 @@ const [first] = Array.from(new Set([1, 2]));``````typescript-// WRONG — fallback replaces the actual value+// WRONG — without iterator support fallback replaces the actual valueconst [first = "fallback"] = new Set(["actual"]);```@@ -1448,7 +1448,7 @@ const [first = "fallback"] = Array.from(new Set(["actual"]));``````typescript-// WRONG — throws because the emitted rest operation calls slice+// WRONG — without iterator support this throws: the emitted rest operation calls sliceconst [...rest] = new Set([1, 2]);```@@ -1460,7 +1460,7 @@ const [...rest] = Array.from(new Set([1, 2]));**String spread — a separate throw, not an empty iterable result**```typescript-// WRONG+// WRONG — without iterator support this throwsconst name = "A😀";const chars = [...name];```@@ -1473,6 +1473,24 @@ const chars = Array.from(name);Call and constructor arguments need the same conversion: write `f(...Array.from(iterator))` and `new C(...Array.from(iterator))`, not direct iterator spreads.-These operations remain ordinary valid patterns: `[...rows]`, `[...Object.keys(row)]`, `for (const row of rows)`, `const [first] = rows`, `{ ...tokens }`, `<div {...props} />`, rest parameters, `selected.has(id)`, `seen.set(key, value)`, `new Set(prev)` and `new Map(entries)`. A first-element binding of a string reads its indexed UTF-16 element, not a whole Unicode code point.+These operations remain ordinary valid patterns: `[...rows]`, `[...Object.keys(row)]`, `for (const row of rows)`, `const [first] = rows`, `{ ...tokens }`, `<div {...props} />`, rest parameters, `selected.has(id)`, `seen.set(key, value)`, `new Set(prev)` and `new Map(entries)`. Without iterator support a first-element binding of a string reads its indexed UTF-16 element, not a whole Unicode code point.++**A default that writes the array it destructures — the one difference from modern JavaScript under iterator support**++The elements are copied before a default runs, so a default that writes a later element of the same array is not seen by that element.++```typescript+// WRONG — b is 2 here; modern JavaScript and a compiler without iterator support give 3+const values: Array<number | undefined> = [undefined, 2];+const [a = (values[1] = 3), b] = values;+```++```typescript+// CORRECT — compute the values first, then read them+const values: Array<number | undefined> = [undefined, 2];+if (values[0] === undefined) values[1] = 3;+const a = values[0] === undefined ? values[1] : values[0];+const b = values[1];+```The authoring rule also applies when an iterable comes from props, parameters, React state, a ref, a cache or another function. Static checks cannot prove all of those origins. Do not mistake a lack of findings for proof that arbitrary iteration is safe.diff --git a/plugins/model-apps/scripts/_vendor-build/build.js b/plugins/model-apps/scripts/_vendor-build/build.jsindex 3bab9c58f..acc762cd9 100644--- a/plugins/model-apps/scripts/_vendor-build/build.js+++ b/plugins/model-apps/scripts/_vendor-build/build.js@@ -1,6 +1,6 @@/* Dev-only bundler: @maker-studio/cds-maker-sdk -> self-contained CJS the plugin vendors.- * Run: node plugins/model-apps/scripts/_vendor-build/build.js --sdk <path-to-ppux>- * or set POWER_PLATFORM_UX_SDK_ROOT=<path-to-ppux>+ * Run: node plugins/model-apps/scripts/_vendor-build/build.js --sdk <path-to-sdk-repo>+ * or set POWER_PLATFORM_UX_SDK_ROOT=<path-to-sdk-repo>* Not shipped. Re-run only when the SDK source changes.** After rebuilding, run the vendored-SDK contract tests against the new bundle:@@ -27,8 +27,8 @@ const argSdk = (() => {return process.env.POWER_PLATFORM_UX_SDK_ROOT;})();if (!argSdk) {- console.error('Usage: node plugins/model-apps/scripts/_vendor-build/build.js --sdk <path-to-ppux>');- console.error(' or: set POWER_PLATFORM_UX_SDK_ROOT=<path-to-ppux>');+ console.error('Usage: node plugins/model-apps/scripts/_vendor-build/build.js --sdk <path-to-sdk-repo>');+ console.error(' or: set POWER_PLATFORM_UX_SDK_ROOT=<path-to-sdk-repo>');process.exit(2);}const SDK_ENTRY = path.join(argSdk, 'packages/cds-maker-sdk/lib/index.js');diff --git a/plugins/model-apps/scripts/check-auth.js b/plugins/model-apps/scripts/check-auth.jsindex 47675bbcb..e40f68680 100644--- a/plugins/model-apps/scripts/check-auth.js+++ b/plugins/model-apps/scripts/check-auth.js@@ -20,7 +20,7 @@// {// "ok": true|false,// "blocker": null | "az_missing" | "az_not_logged_in" | "az_timeout" | "pac_not_logged_in" | "pac_timeout"-// | "no_env_url" | "whoami_403" | "whoami_401" | "whoami_error",+// | "no_env_url" | "whoami_403" | "whoami_401" | "whoami_error" | "no_customization_role",// "message": "human-readable next step",// "warnings": ["..."],// "azUser": "...",@@ -37,6 +37,10 @@// read the environment; a missing/for-different-identity pac login is surfaced as a WARNING, not a hard// blocker.//+// After a passing WhoAmI one more GET (`solutions?$select=solutionid&$top=1`, the first read a build makes)+// checks the identity can read customizations: an HTTP 403 `0x80042f09` ("has not been assigned any roles")+// is `ok: false` with blocker `no_customization_role`. Any other outcome of that read is a warning only.+//// Exit code 0 always (so callers can parse stdout). Use `ok` field to gate.const { execFileAsync } = require('./lib/process-runner.js');@@ -54,6 +58,9 @@ const PAC_PROBE_TIMEOUT_MS = 60000;// print model-apps' flows.const PAC_OPTIONAL_NOTE = 'That does not block a step that signs in with the az token alone: only a step that runs `pac` needs the login, and so does reading the environment when --env is omitted.';+// The Dataverse error code of a read refused to a user who holds no security role (see the capability probe in main()).+const NO_ROLE_CODE = '0x80042f09';+// Read the env URL from either `--env <url>` (the flag the build/verify/teardown scripts use) or// the first positional arg, so a caller can copy the `--env` form here without silently passing// the literal string "--env" as the URL (the prior positional-only parse did exactly that).@@ -371,6 +378,46 @@ async function main() {);}+ // 4) Capability probe. WhoAmI answers for ANY user the environment knows, role or not, so it said "ready" for an identity+ // that holds no security role: every customization read then fails, and the first build step is where the maker found out.+ // One read the build itself starts with (its solution) tells. Measured on an identity with no role:+ // GET solutions?$select=solutionid&$top=1 -> HTTP 403+ // {"error":{"code":"0x80042f09","message":"The user with id <id> has not been assigned any roles. They need a role with the prvReadCustomization privilege."}}+ // (`sitemaps`, `roles` and `publishers` answered the same.) A COUNT of the user's roles would be wrong: privileges also come+ // through teams, so a user with no role of their own can read customizations. The code decides, never the words — the platform+ // answers in the caller's language. Any other outcome of the probe (another 403 code, a 5xx, a transport failure) proves nothing+ // about roles, so it is a warning and never a verdict: a false "no role" would send a working maker to an administrator.+ // https://learn.microsoft.com/power-platform/admin/security-roles-privileges+ let probe = null;+ try {+ probe = await dataverseRequest(envUrl, 'GET', 'solutions?$select=solutionid&$top=1', null, { timeout: 30000 });+ } catch (e) {+ warnings.push(`Could not confirm the identity can read customizations (${e.message}). WhoAmI passed, so this is not taken as a missing role.`);+ }+ if (probe) {+ const probeCode = probe.data && probe.data.error && probe.data.error.code;+ if (probe.status === 403 && String(probeCode || '').toLowerCase() === NO_ROLE_CODE) {+ const otherIdentity = pacUser && !identitiesMatch+ ? ` Or sign in as the PAC user if that identity holds a role: \`az login --username ${pacUser}\`.`+ : '';+ return emit(+ buildResult({+ azUser,+ pacUser,+ envUrl,+ identitiesMatch,+ warnings,+ whoAmI: { ok: true, userId: whoRes.data?.UserId, organizationId: whoRes.data?.OrganizationId },+ blocker: 'no_customization_role',+ message: `WhoAmI passed, but "${azUser}" has no security role in ${envUrl}, so it cannot read customizations (HTTP 403 ${NO_ROLE_CODE}: the prvReadCustomization privilege is missing). Ask an environment administrator to assign a role such as System Customizer.${otherIdentity}`,+ })+ );+ }+ if (probe.status < 200 || probe.status >= 300) {+ warnings.push(`Could not confirm the identity can read customizations (HTTP ${probe.status}${probeCode ? ` ${probeCode}` : ''}). WhoAmI passed, so this is not taken as a missing role.`);+ }+ }+// A pac probe that ran out of time says THAT here too — its warning already does, and "not logged in" beside// it contradicted it: a slow PAC CLI's login is unknown, not missing.const readyMessage = !pacUserdiff --git a/plugins/model-apps/scripts/lib/app-component-scope.js b/plugins/model-apps/scripts/lib/app-component-scope.jsindex 5e7b279d7..c88708050 100644--- a/plugins/model-apps/scripts/lib/app-component-scope.js+++ b/plugins/model-apps/scripts/lib/app-component-scope.js@@ -52,6 +52,17 @@// (percent-escapes decoded; one that cannot be read refuses the batch); a JSON batch, as text, bytes or an object, after its JSON is (`\u0041` is `A`); and the name is looked for in the rest of the text as it is and with its// escapes decoded.//+// THE SDK'S GUARDED PIN (bundles from model-apps 2.20.6 on). On an unpublished default-mode push that holds the app row's token, the bundle reads the app's current layer after the sitemap write, and when a component its+// derived list names is missing from it (every app whose maker took a form, view or chart out) it sends the AddAppComponents in ONE change set of its own instead of alone (`pinDefaultComponents`):+// PATCH <api>/appmodules(<app>) If-Match: <held token>, body {} the guard: the change set runs only on the version the push holds+// POST <api>/AddAppComponents { "AppId": "<app>", "Components": [ …the whole derived list… ] }+// PATCH <api>/appmodules(<app>)?$select=appmoduleid Prefer: return=representation, body {} the echo: the app row's token after the change set, which the SDK keeps+// Its action carries the whole derived list, so it is not forwarded; and its parts are not cut either — the change set would then be a write this tool composed (two app-row writes no earlier release made), sent as the SDK's.+// For an app with an edit open, that change set (`guardedPinOf`: exactly those three parts, for that one app, and nothing else) is NOT sent, and the SDK is answered as the service answers a change set whose FIRST part+// was refused: the service rolls such a change set back whole, and the bundle then sends the plain action once (its documented fallback for a refused guard), which this limits as it limits every other — exactly what+// a page edit sent before 2.20.6. Nothing was sent, so the plain action is not the resend of a write whose outcome is unknown; the app's row is not written; and the SDK keeps the app token it held, as every bundle before+// did (a page edit reads the app again before each push, so it never depends on that token). Any other change set that names the action is refused, as above. Another app's guarded pin is not this edit's and goes on as it was read.+//// The SDK reads the app's tables back after the post and reports a table its sitemap opens that is not a component (`APP_COMPONENTS_NOT_PERSISTED`) as a warning of the push — which is// what a page edit of an app whose navigation opens a table the app does not hold still says: the edit does not add it.// An SDK lent to a backend (`deps.sdk`) keeps the lender's transport, so a page edit through it is NOT limited. The bundle's request is pinned by genpage-app-edit-real-bundle.test.js:@@ -249,6 +260,111 @@ function optionsFor(body, options) {return { ...options, headers: { ...Object.fromEntries(Object.entries(headers).filter(([key]) => !names.includes(key))), [names[0]]: length } };}+// The SDK's guarded pin (THE SDK'S GUARDED PIN, above), read from the text of a `$batch` exactly as the bundle renders one (renderChangeSet) — or null for anything else. Parts are separated by CRLF, the CRLF before a+// delimiter belongs to the delimiter, and each part is its MIME headers, a blank line, the embedded request line and headers, a blank line and the body:+// --batch_<id>+// Content-Type: multipart/mixed;boundary=changeset_<id>+//+// --changeset_<id>+// Content-Type: application/http+// Content-Transfer-Encoding: binary+// Content-ID: 1+//+// PATCH https://contoso.crm.dynamics.com/api/data/v9.0/appmodules(<app>) HTTP/1.1+// Content-Type: application/json;type=entry+// MSCRM.SolutionUniqueName: contoso_solution (only when the SDK names a solution)+// If-Match: W/"1234"+//+// {}+// --changeset_<id>+// …Content-ID: 2… POST …/AddAppComponents HTTP/1.1 … {"AppId":"<app>","Components":[…]}+// --changeset_<id>+// …Content-ID: 3… PATCH …/appmodules(<app>)?$select=appmoduleid HTTP/1.1 … Prefer: return=representation … {}+// --changeset_<id>--+// --batch_<id>--+// Answers `{ appId, guardId }` (the app, lower case, and the Content-ID of the guard) only when the batch is exactly that: one change set of three parts in that order, every app id the same, the guard and the echo+// with empty bodies, the guard conditional, the echo asking for the row back, no header beyond the ones above, and the action's own body naming the same app with a list. A change set that differs in anything is not+// recognised, and is refused as any other batch that names the action is.+const GUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;+const PART_HEADERS = new Set(['content-type', 'mscrm.solutionuniquename', 'if-match', 'prefer']);+function changeSetPartOf(segment) {+ // `\r\n<mime headers>\r\n\r\n<request line and headers>\r\n\r\n<body>\r\n`+ if (!segment.startsWith('\r\n') || !segment.endsWith('\r\n')) return null;+ const blocks = segment.slice(2, -2).split('\r\n\r\n');+ if (blocks.length !== 3 || /[\r\n]/.test(blocks[2])) return null;+ const mime = blocks[0].split('\r\n');+ const id = /^Content-ID: (\d+)$/.exec(mime[2] || '');+ if (mime.length !== 3 || mime[0] !== 'Content-Type: application/http' || mime[1] !== 'Content-Transfer-Encoding: binary' || !id) return null;+ const [line, ...headerLines] = blocks[1].split('\r\n');+ const request = /^(PATCH|POST) (\S+) HTTP\/1\.1$/.exec(line);+ if (!request) return null;+ const headers = {};+ for (const header of headerLines) {+ const named = /^([A-Za-z0-9.-]+): (.*)$/.exec(header);+ const name = named && named[1].toLowerCase();+ if (!named || !PART_HEADERS.has(name) || name in headers) return null;+ headers[name] = named[2];+ }+ return { contentId: id[1], method: request[1], address: request[2], headers, body: blocks[2] };+}+function guardedPinOf(read) {+ const text = read.kind === 'text' ? read.text : read.kind === 'bytes' && isUtf8(read.bytes) ? read.bytes.toString('utf8') : null;+ if (text === null) return null;+ const head = /^--(batch_[A-Za-z0-9-]+)\r\nContent-Type: multipart\/mixed;boundary=(changeset_[A-Za-z0-9-]+)\r\n\r\n/.exec(text);+ if (!head) return null;+ const segments = text.slice(head[0].length).split(`--${head[2]}`);+ if (segments.length !== 5 || segments[0] !== '' || segments[4] !== `--\r\n--${head[1]}--\r\n`) return null;+ const parts = segments.slice(1, 4).map(changeSetPartOf);+ if (parts.some((part) => part === null)) return null;+ const [guard, action, echo] = parts;+ // `<api>/appmodules(<guid>)`, with no query (the guard) or with exactly `?$select=appmoduleid` (the echo).+ const appOf = (part, query) => {+ const at = /^(.*\/api\/data\/v\d+(?:\.\d+)?)\/appmodules\(([^)]+)\)(\?.*)?$/.exec(part.address);+ return at && GUID.test(at[2]) && (at[3] || '') === query ? at[2].toLowerCase() : null;+ };+ const appId = appOf(guard, '');+ if (!appId || guard.method !== 'PATCH' || guard.body !== '{}' || !guard.headers['if-match'] || 'prefer' in guard.headers) return null;+ if (appOf(echo, '?$select=appmoduleid') !== appId || echo.method !== 'PATCH' || echo.body !== '{}' || echo.headers.prefer !== 'return=representation' || 'if-match' in echo.headers) return null;+ if (action.method !== 'POST' || kindOf(action.address) !== 'action' || 'if-match' in action.headers || 'prefer' in action.headers) return null;+ let body;+ try {+ body = JSON.parse(action.body);+ } catch {+ return null;+ }+ if (!body || typeof body.AppId !== 'string' || guidKey(body.AppId) !== appId || !Array.isArray(body.Components)) return null;+ return { appId, guardId: guard.contentId };+}++// The answer to a guarded pin that was NOT sent: a change-set answer, in the form the service gives one (its own boundaries, and the Content-ID it answers), whose one part refuses the guard. The bundle reads a refused+// first part as a change set the service rolled back whole, and sends the plain action once (`pinDefaultComponents`); the status and the error say what happened, though the bundle reports neither. A raw request is+// answered with its body as text.+// See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/execute-batch-operations-using-web-api#change-sets+function guardNotSent(guardId) {+ const { randomUUID } = require('node:crypto');+ const batch = `batchresponse_${randomUUID()}`;+ const changeSet = `changesetresponse_${randomUUID()}`;+ const error = JSON.stringify({ error: { code: 'APP_COMPONENTS_GUARD_NOT_SENT', message: 'this change set was not sent: a page edit adds only the views it pins, so the plain AddAppComponents is limited and sent instead' } });+ const body = [+ `--${batch}`,+ `Content-Type: multipart/mixed; boundary=${changeSet}`,+ '',+ `--${changeSet}`,+ 'Content-Type: application/http',+ 'Content-Transfer-Encoding: binary',+ `Content-ID: ${guardId}`,+ '',+ 'HTTP/1.1 400 Bad Request',+ 'Content-Type: application/json; odata.metadata=minimal',+ '',+ error,+ `--${changeSet}--`,+ `--${batch}--`,+ '',+ ].join('\r\n');+ return { status: 200, headers: { 'content-type': `multipart/mixed; boundary=${batch}` }, body };+}+function makeAppComponentScope() {// app id (lower case) -> the ids of the views the edit under way ownsconst open = new Map();@@ -293,6 +409,9 @@ function makeAppComponentScope() {if (kind === 'lookalike') throw refusal(`its address (${pathOf(address)}) is not the SDK's /api/data/v<version>/AddAppComponents, though it names that action`);const read = readBody(body);if (kind === 'other') {+ // The SDK's guarded pin, to the `$batch` address (THE SDK'S GUARDED PIN, above): not sent for an app with an edit open — the bundle then sends the plain action, limited below — and sent as it was read for another app.+ const pin = raw && /\/\$batch$/.test(pathOf(address) || '') ? guardedPinOf(read) : null;+ if (pin) return open.has(pin.appId) ? guardNotSent(pin.guardId) : client[method](address, read.send, options);// Not the action's address, so not the action's — but the body may be a `$batch` that NAMES the action, which cannot be limited, whichever method carries it. Anything else goes on as it was read.const problem = batchProblem(read);if (problem) throw refusal(problem);diff --git a/plugins/model-apps/scripts/lib/collection-answers.js b/plugins/model-apps/scripts/lib/collection-answers.jsindex c36336230..b6bdedcde 100644--- a/plugins/model-apps/scripts/lib/collection-answers.js+++ b/plugins/model-apps/scripts/lib/collection-answers.js@@ -3,10 +3,11 @@//// Dataverse answers a read of a collection as// { "@odata.context": "…", "value": [ … ], "@odata.nextLink": "…" }-// (https://learn.microsoft.com/power-apps/developer/data-platform/webapi/query-data-web-api). Some of the SDK's readers take a 2xx answer with no `value` list for "no rows" — `findTables()`-// is `body.value ?? []` — and the plugin's HTTP client keeps a body that is not JSON as the text it is, so a sign-in page, a proxy's error page, `{}` or `null` read as an environment with+// (https://learn.microsoft.com/power-apps/developer/data-platform/webapi/query-data-web-api). SDKs before the one bundled now took a 2xx answer with no `value` list for "no rows" — `findTables()`+// was `body.value ?? []` — and the plugin's HTTP client keeps a body that is not JSON as the text it is, so a sign-in page, a proxy's error page, `{}` or `null` read as an environment with// no table at all. A script that turns "no rows" into a conclusion (`list-tables.js --exact`: every searched table is `missing`, which the planner reads as "create it") must not be handed-// that. The bundle is vendored and is not edited, so the shape is enforced here, on the one read, between the script and the SDK. `{ "value": [] }` is a real, empty answer and passes.+// that. The bundle is vendored and is not edited, so the shape is enforced here, on the one read, between the script and the SDK. (The bundled SDK now refuses such an answer itself, as a+// ConnectionError of the 200 it read — "paginated read returned a malformed page" — with no code of the plugin's and no remedy; this guard answers first, so a script still meets its own.) `{ "value": [] }` is a real, empty answer and passes.//// const client = requireCollectionAnswers(httpClient, {// reads: (url) => /\/EntityDefinitions\?/.test(url), // the reads whose answer must be a collection (the SDK passes the full URL)diff --git a/plugins/model-apps/scripts/lib/entity-provision.js b/plugins/model-apps/scripts/lib/entity-provision.jsindex 1d7a91922..88534482d 100644--- a/plugins/model-apps/scripts/lib/entity-provision.js+++ b/plugins/model-apps/scripts/lib/entity-provision.js@@ -1847,6 +1847,17 @@ const RESET_WORKSPACE = 'stop any other build or teardown using the .maker-works// 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`.+//+// DATETIME_BEHAVIOR_MISSING: the bundled SDK's diagnosis of a column, lookup or relationship refused with 400 0x80048550 on a table whose Date+// and Time columns have no behaviour — what Dataverse stores for such a column created INSIDE a table's create (this build never makes one+// that way: it adds columns by their own request or in a change set, which the platform gives UserLocal). The SDK names the columns and its+// own repair call (`updateColumn(..., { dateTimeBehavior: 'UserLocal' })`), which an operator of this plugin cannot make, so the halt names the+// maker's step. A run again meets the same refusal (the error is typed: never retried).+//+// COMMAND_IMMUTABLE_COLUMN_CHANGED: the bundled SDK refuses, before any request, to push a command row whose location or type changed (the+// platform ignored such an update while reporting it saved). The build never pushes an existing command bar — a bar that exists is reused,+// and button edits are not reapplied (sdk-build.js, commands) — so only a push of a bar this build is creating could meet it, which has no+// existing row; the remedy is said all the same, in case a later path pushes one.function operatorRemedy(err) {// A create refused with the lag of a table this attempt just created, still refused when the bounded check ran out (createInLagWindow,// recoverRefusedBatch, drainLagStatuses). Recognised by the error object itself, never by its words: the event the step reported while the@@ -1861,6 +1872,12 @@ function operatorRemedy(err) {if (err && err.code === 'LOCAL_EDITS_WOULD_BE_LOST') {return ` — the environment's copy changed after this workspace copy was fetched, and the workspace copy holds edits no build pushed (an interrupted build, or one halted by a concurrent edit). A re-run applies the spec over that change, so first look at it in Maker and put into the spec anything that should stay; then ${RESET_WORKSPACE}, and re-run.`;}+ if (err && err.code === 'DATETIME_BEHAVIOR_MISSING') {+ return ' — nothing was created by the refused request. Those Date and Time columns were created without a behaviour (by a tool that put them in the table\'s own create), and Dataverse then refuses every new column or lookup on the table. Set the behaviour of each to User local — the one their values are already stored with — in the column\'s advanced options in Power Apps, then run the build again.';+ }+ if (err && err.code === 'COMMAND_IMMUTABLE_COLUMN_CHANGED') {+ return ' — nothing was written. A command\'s location and type cannot be changed on a row that exists (the platform ignores the change). Remove the command in Power Apps, then run the build again to create it as the spec says.';+ }return '';}diff --git a/plugins/model-apps/scripts/lib/feature-flags.js b/plugins/model-apps/scripts/lib/feature-flags.jsindex 0abf7521f..1b90998b1 100644--- a/plugins/model-apps/scripts/lib/feature-flags.js+++ b/plugins/model-apps/scripts/lib/feature-flags.js@@ -50,8 +50,8 @@ const FLAGS = {"exceptions to the customer's Application Insights resource via an optional props.appInsights " +'surface, emitted only when the maker explicitly asks to measure or track something.',dependencies:- 'the page telemetry facade in the UCI host runtime, the GenUX authoring control ' +- '(power-platform-ux), the AIBuilder CoderAgent telemetry prompt, and the ' ++ 'the page telemetry facade in the UCI host runtime, the GenUX authoring control, ' ++ 'the AIBuilder CoderAgent telemetry prompt, and the ' +'GenUxEnableCustomTelemetry ECS setting — all live in PROD.',enableEnv: 'GENPAGE_ENABLE_CUSTOM_TELEMETRY=1',},diff --git a/plugins/model-apps/scripts/lib/genpage-sdk.js b/plugins/model-apps/scripts/lib/genpage-sdk.jsindex dd1f760a3..7e596f50d 100644--- a/plugins/model-apps/scripts/lib/genpage-sdk.js+++ b/plugins/model-apps/scripts/lib/genpage-sdk.js@@ -49,6 +49,7 @@ const { makeThrottleBudget, waitDoesNotFit, spentNote } = require('./throttle-buconst { mergeBindings } = require('./page-bindings.js');const { isRestrictedSolution } = require('./system-solutions.js');const { readTargetSolution, readPageComponentType, pageComponent } = require('./page-solution.js');+const { asPageNestingRefusal } = require('./page-nesting.js');const GUID_RE = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;@@ -123,6 +124,8 @@ const codeOf = (error) => (error && typeof error.code === 'string' && error.code// PAGE_NESTING_TOO_DEEP the page's elements nest so deeply that the compiler ran out of stack space (lib/page-nesting.js raises it from the// compiler the SDK is given; the SDK compiles ahead of every write, so a push that raises it wrote nothing to the// service, though its metadata reads may already have been made)+// GENPAGE_COMPILE_DEPTH_EXCEEDED the SDK's own refusal of the same page, from a stage of its compile the guard above does not wrap; pushOnce reports it+// as PAGE_NESTING_TOO_DEEP (lib/page-nesting.js, asPageNestingRefusal), and it is listed here so the proof never depends on that// GENPAGE_CONTENT_WRITE_UNSUPPORTED, GENPAGE_TURN_NOT_ATOMIC// the transport cannot write this page as one change set (assertContentWritable / assertTurnWritable)// GENPAGE_TURN_CONFLICT the pending turn's id is already recorded as a different message (`unrecordedTurn`, a read)@@ -135,7 +138,7 @@ const codeOf = (error) => (error && typeof error.code === 'string' && error.code// be one of these, on an SdkError.const PRE_WRITE_REFUSALS = new Set(['VALIDATION_ERROR',- 'GENPAGE_COMPILER_UNAVAILABLE', 'GENPAGE_COMPILER_VERSION', 'GENPAGE_COMPILER_INVALID', 'GENPAGE_RUNTIME_TYPES_INVALID', 'PAGE_NESTING_TOO_DEEP',+ 'GENPAGE_COMPILER_UNAVAILABLE', 'GENPAGE_COMPILER_VERSION', 'GENPAGE_COMPILER_INVALID', 'GENPAGE_RUNTIME_TYPES_INVALID', 'PAGE_NESTING_TOO_DEEP', 'GENPAGE_COMPILE_DEPTH_EXCEEDED','GENPAGE_CONTENT_WRITE_UNSUPPORTED', 'GENPAGE_TURN_NOT_ATOMIC', 'GENPAGE_TURN_CONFLICT','GENPAGE_RETAIN_ON_CREATE', 'GENPAGE_RETAINED_ROW_MISSING', 'GENPAGE_CONTENT_NOT_TEXT', 'GENPAGE_WRITE_UNKNOWN','ARTIFACT_NOT_FOUND', 'ARTIFACT_LANGUAGE_MISMATCH', 'ARTIFACT_PROJECTION_STALE',@@ -167,6 +170,14 @@ function writeOutcome(error) {return PRE_WRITE_REFUSALS.has(error.code) ? 'nothing' : 'unknown';}+// A push's failure as the maker is told it: the SDK's own refusal of a page too deep to compile is the plugin's PAGE_NESTING_TOO_DEEP, with the plugin's instruction+// ("split the page into components"), so the maker sees one refusal whichever layer caught the overflow (lib/page-nesting.js). Only the SDK's typed error is translated.+function nestingRefusalOf(error) {+ if (!isSdkError(error)) return error;+ const { SdkError } = require('./maker-sdk.js');+ return asPageNestingRefusal(error, (code, message) => new SdkError(code, message));+}+// A send the service refused with a throttle: the SDK's typed `ConnectionError` with status 429, read from its structure and never from its words. Dataverse's service protection limits answer a request they will not// START this way (HTTP 429, with a `Retry-After`), so no part of the change set ran.// See: https://learn.microsoft.com/power-apps/developer/data-platform/api-limits#retry-operations@@ -807,11 +818,12 @@ function makeGenpageSdk(env, deps = {}) {let result;try {result = await sdk.pushArtifact('genPage', id);- } catch (error) {+ } catch (thrown) {+ const error = nestingRefusalOf(thrown);return unsaved(writeOutcome(error), error);}if (result && result.saved === true) return { saved: true, result };- const error = result && result.error;+ const error = nestingRefusalOf(result && result.error);if (error && error.code === 'ARTIFACT_ALREADY_EXISTS') return unsaved('exists', error);if (error && error.code === 'VERSION_CONFLICT') return unsaved('conflict', error);return unsaved(error ? writeOutcome(error) : 'unknown', error || new Error('the SDK did not report the page as saved'));@@ -1326,7 +1338,7 @@ function makeGenpageSdk(env, deps = {}) {// navigation it pushes — the one the server holds: this call fetches the app, adds the page entries and the views it was asked for, and pushes that — into their active Main forms, public views and// charts; but on the transport of an SDK this backend made, the push's AddAppComponents is cut down to the views this edit pins (`appScope`, `pushApp`), so it adds no Main form and// `entityTables` is empty. Only through a lent SDK, whose transport is its owner's, does the push add them all: then `entityTables` is the tables of those Entity entries (`entityTablesOfSiteMap`).- // Returns { added: [pageId…], alreadyPlaced: [pageId…], pinnedViews: [viewId…], warnings: [...], appEdited, provedPublished? }. It throws, with+ // Returns { added: [pageId…], alreadyPlaced: [pageId…], pinnedViews: [viewId…], warnings: [...], appEdited, provedPublished? } — `pinnedViews` the views it asked for that the app is read back holding. It throws, with// the page unplaced, when the app cannot be read, the edit is refused, `beforeAppWrite` throws, or the app's publish fails — and with `finish`, when the published// navigation does not show the page after the app was published.async placeInApp(appId, options = {}) {@@ -1395,6 +1407,25 @@ function makeGenpageSdk(env, deps = {}) {await options.beforeAppWrite({ pushes: edited, entityTables: limited ? [] : entityTablesOfSiteMap(app.siteMap), mainFormsByTable: app.components && app.components.mainFormsByTable });}if (edited) await pushApp(sdk, appId, warnings, appScope, { views: pin });+ // `pinnedViews` is what the app's current layer holds after the push, read back — not what was asked: the SDK reports a pin it could not make (a refusal, an answer it could not read) as a warning of the+ // push and saves the navigation all the same, so a view asked for is not a view added. One that is not there, or not seen to be, is said in a warning of its own.+ let pinnedViews = pin;+ if (edited && pin.length) {+ let held = null;+ try {+ held = await viewsHeldBy(sdk, appId);+ } catch {+ // Unread: nothing is confirmed, and the warning below says so.+ }+ pinnedViews = held ? pin.filter((id) => held.has(id)) : [];+ const absent = pin.filter((id) => !pinnedViews.includes(id));+ if (absent.length) {+ const views = `the default view${absent.length === 1 ? '' : 's'} ${absent.join(', ')} of the tables the pages read`;+ warnings.push(held+ ? `${views} ${absent.length === 1 ? 'was' : 'were'} not added to app ${appId} — the maker's "/" picker may not list ${absent.length === 1 ? 'its table' : 'their tables'}; run the same command again to add ${absent.length === 1 ? 'it' : 'them'}`+ : `${views} could not be confirmed in app ${appId}: its components could not be read back — treat ${absent.length === 1 ? 'it' : 'them'} as added only once seen to be`);+ }+ }const published = await publish(sdk, 'app', appId, undefined);// The failures below name the app and the page(s) the caller asked for, as `removeFromApp`'s do, so a caller that prints one can go on from it.const asked = wantedPages.map((p) => String(p.pageId));@@ -1408,7 +1439,7 @@ function makeGenpageSdk(env, deps = {}) {: `the default views of the tables the pages read were saved in app ${appId}`;throw genpageError(`${saved}, but publishing the app failed (${published.detail}) — ${navigation ? "the pages are in the app's saved navigation and show once it is published" : 'they take effect once the app is published'}`, { code: 'GENPAGE_APP_PUBLISH_FAILED', saved: true, ...who });}- const result = { added: added.map((p) => String(p.pageId)), alreadyPlaced, pinnedViews: pin, warnings, appEdited: edited };+ const result = { added: added.map((p) => String(p.pageId)), alreadyPlaced, pinnedViews, warnings, appEdited: edited };if (!finishing) return result;// The publish was accepted (a refused one threw above); what runs is the app's published navigation, so that is what confirms it. PublishXml is asynchronous@@ -1891,12 +1922,17 @@ async function defaultViewsOf(sdk, tables, warnings) {async function viewsToPin(sdk, appId, tables, warnings) {const ids = (await defaultViewsOf(sdk, tables, warnings)).map((view) => view.viewId);if (!ids.length) return [];+ const held = await viewsHeldBy(sdk, appId);+ return held ? ids.filter((id) => !held.has(id)) : ids;+}++// The ids of the views the app's CURRENT layer holds, or null when that layer cannot be read. The layer is the one an edit now would change, and the one an edit just made wrote.+// appmodulecomponent rows of type 26 (savedquery): [{ objectid: '<view id>', componenttype: 26 }]+async function viewsHeldBy(sdk, appId) {const { currentAppLayer, appComponentRows } = require('./app-components.js');const layer = sdk.dataverse ? await currentAppLayer(sdk.dataverse, appId) : { ok: false };- if (!layer.ok) return ids;- // appmodulecomponent rows of type 26 (savedquery): [{ objectid: '<view id>', componenttype: 26 }]- const held = new Set((await appComponentRows(sdk, layer.appModuleIdUnique, 26)).map((row) => String(row.objectid).replace(/[{}]/g, '').toLowerCase()));- return ids.filter((id) => !held.has(id));+ if (!layer.ok) return null;+ return new Set((await appComponentRows(sdk, layer.appModuleIdUnique, 26)).map((row) => String(row.objectid).replace(/[{}]/g, '').toLowerCase()));}// The apps whose navigation names a page, in either layer: [{ uniqueName, savedOnly, appId?, name? }]. It is the scan the build makes for a page shared across apps (sitemap-pages.js `fetchAppsForPages`: every app'sdiff --git a/plugins/model-apps/scripts/lib/maker-sdk.js b/plugins/model-apps/scripts/lib/maker-sdk.jsindex d5240a5ea..f01012b91 100644--- a/plugins/model-apps/scripts/lib/maker-sdk.js+++ b/plugins/model-apps/scripts/lib/maker-sdk.js@@ -18,9 +18,10 @@// client the factory gives: the SDK's reads through the Power Platform API (a Test org's, and a connector's tables) need a `powerPlatformApiClient`, and the// tables a `connectorRuntimeClient` too, which an Azure CLI token cannot back (lib/sdk-first.js, "No Power Platform API client").//-// The `httpClient` the caller names is handed to the SDK with two additions, each of which looks at one kind of request and leaves every other request as it is. The first (lib/collection-answers.js): the read of the environment's table list must answer a list. The SDK's findTables() reads a 2xx with no `value` list+// The `httpClient` the caller names is handed to the SDK with two additions, each of which looks at one kind of request and leaves every other request as it is. The first (lib/collection-answers.js): the read of the environment's table list must answer a list. The SDK's findTables() used to read a 2xx with no `value` list// as "no tables" (`body.value ?? []`) — and a sign-in or proxy page, `{}` and `null` are such answers — and every script that asks it turns "no tables" into a conclusion: a table is missing, create it, nothing clashes, it is not a-// system table, so delete it. Guarded here, once, no script that makes an SDK can forget it, and no request is added or changed: only that answer is looked at. It then fails as an SdkError (TABLES_UNREADABLE), which the+// system table, so delete it. The bundled SDK now refuses such an answer itself, but as a ConnectionError of the 200 it read, with no word of what to do; the guard answers first, so+// every script still meets TABLES_UNREADABLE (which the callers recognise, lib/collection-answers.js unreadableAnswer) and the remedy it names. Guarded here, once, no script that makes an SDK can forget it, and no request is added or changed: only that answer is looked at. It then fails as an SdkError (TABLES_UNREADABLE), which the// bundle rethrows as it is.// The second (lib/app-header-text.js): a PATCH of an app module row whose name or description is not a string — through `patch`, through// `patchRaw`, or in a change set a caller sends raw (`dataverse.postBatch`) — is refused before it is sent. The SDK's push of an app writes every text its workspace copy holds whenever its own comparisondiff --git a/plugins/model-apps/scripts/lib/page-nesting.js b/plugins/model-apps/scripts/lib/page-nesting.jsindex 1260d82af..24e54a27f 100644--- a/plugins/model-apps/scripts/lib/page-nesting.js+++ b/plugins/model-apps/scripts/lib/page-nesting.js@@ -4,10 +4,10 @@// TypeScript parses and transforms a page with recursive functions, one level of recursion per nested JSX element (and one more per nested// expression). Around a thousand nested elements exhaust V8's default stack, and the compiler then throws// RangeError: Maximum call stack size exceeded-// out of `transpileModule`. The SDK compiles a page on every push that changes its source and does not catch that, so without this module the-// maker was shown a bare RangeError — or, through the page backend's own settling of a push that "got no usable answer", a message about a+// out of `transpileModule`. The SDK compiles a page on every push that changes its source, and the bundles before model-apps 2.20.6 did not catch that, so+// without this module the maker was shown a bare RangeError — or, through the page backend's own settling of a push that "got no usable answer", a message about a// create that "was sent twice", although the SDK compiles BEFORE it writes anything: the page was not written to the service (its metadata reads-// may already have been made).+// may already have been made). The bundle now refuses such a page itself (SDK_COMPILE_DEPTH_EXCEEDED below); this module keeps the plugin's code for both.//// The depth that overflows is not a fixed number: the first compile in a process runs in the interpreter, whose frames are larger, so it// overflows at roughly two thirds of the depth that a later, optimised, compile reaches (measured: a page nested 600 deep overflowed a cold@@ -29,6 +29,22 @@ function isStackOverflow(error) {&& typeof error.message === 'string' && error.message.startsWith('Maximum call stack size exceeded');}+// The bundled SDK refuses the same page itself: every stage of its compile — TypeScript's parse, emit and checker, and its own walks over the tree — sits behind one+// boundary that turns a stack overflow into an SdkError with this code, before any write. The guard below fires first wherever the overflow is in one of the compiler's+// entry points (measured: deep elements, and chains of operators, calls, brackets and parentheses all overflow in the parse), so the SDK's code reaches a caller only+// from a stage the guard does not wrap. It is the same refusal, so the page backend reports it as this module's (lib/genpage-sdk.js): one code and one instruction for the+// maker, whichever layer fired.+const SDK_COMPILE_DEPTH_EXCEEDED = 'GENPAGE_COMPILE_DEPTH_EXCEEDED';++// `error` as the maker is told it: the SDK's compile-depth refusal becomes `makeError(PAGE_NESTING_TOO_DEEP, PAGE_NESTING_MESSAGE)`, keeping the SDK's own error as its+// `cause`; every other error is returned as it is. The caller decides that `error` is the SDK's (an SdkError): the code alone is not the proof.+function asPageNestingRefusal(error, makeError) {+ if (!error || typeof error !== 'object' || error.code !== SDK_COMPILE_DEPTH_EXCEEDED) return error;+ const refusal = makeError(PAGE_NESTING_TOO_DEEP, PAGE_NESTING_MESSAGE);+ Object.defineProperty(refusal, 'cause', { value: error, configurable: true, writable: true, enumerable: false });+ return refusal;+}+// The compiler's entry points that recurse over a page's syntax: the transpile (which also runs the SDK's own walk over the tree, as a transformer),// the parse and the program (the checker) the SDK builds to resolve enum names.const GUARDED = ['transpileModule', 'createSourceFile', 'createProgram'];@@ -59,4 +75,4 @@ function guardPageNesting(ts, makeError) {return guarded;}-module.exports = { PAGE_NESTING_TOO_DEEP, PAGE_NESTING_MESSAGE, isStackOverflow, guardPageNesting };+module.exports = { PAGE_NESTING_TOO_DEEP, PAGE_NESTING_MESSAGE, SDK_COMPILE_DEPTH_EXCEEDED, isStackOverflow, guardPageNesting, asPageNestingRefusal };diff --git a/plugins/model-apps/scripts/lib/retry-policy.js b/plugins/model-apps/scripts/lib/retry-policy.jsindex 1705c57d5..299abe53d 100644--- a/plugins/model-apps/scripts/lib/retry-policy.js+++ b/plugins/model-apps/scripts/lib/retry-policy.js@@ -8,7 +8,7 @@//// THE RULE, in the order it is applied (`judgeFailure`). The failure is the halt and the chain of `cause`s behind it, outermost first:// 1. NEVER. Any error in the chain that says `transient: false`, however deep: a refusal a run again cannot change, an outcome that must not be sent again, a prerequisite.-// It wins over everything below, a 503 included.+// It wins over everything below, a 503 included. So does an SDK error whose code says a write's outcome is unknown (OUTCOME_UNKNOWN_CODES).// 2. STATUS. The HTTP status the service answered — 429 (throttled) and 502, 503, 504 (the gateway or the service is down or behind) — on any error of the chain. The SDK's own// ConnectionError carries it as `statusCode`, and 0 for a failure of the transport. See https://learn.microsoft.com/en-us/power-apps/developer/data-platform/api-limits// and https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/compose-http-requests-handle-errors@@ -100,6 +100,13 @@ const CAUSE_WRAPPER_CODES = Object.freeze(new Set(['WEB_RESOURCE_UNVERIFIED']));// How far down the chain of causes the decision looks. Deeper than any failure the build raises (a halt, a step's wrapper, the SDK's error, the system error under it).const MAX_CHAIN = 8;+// The SDK's errors for a write it SENT and whose answer it lost: the write may have committed, and the SDK never sends it again. Each keeps the+// failure the write met — a 503, a 429, a reset — as its `cause` (and a status of its own), which rule 2 or 4 would read as "run the build again":+// that is the re-send the SDK refuses to make, so these are NEVER, as an explicit `transient: false` is (rule 1). Typed by the bundled SDK:+// UPSERT_OUTCOME_UNKNOWN upsertRecord: "the row MAY have been written; never re-read or re-sent"+// APP_UPDATE_OUTCOME_UNKNOWN an app update whose change set's answer proves nothing+const OUTCOME_UNKNOWN_CODES = Object.freeze(new Set(['UPSERT_OUTCOME_UNKNOWN', 'APP_UPDATE_OUTCOME_UNKNOWN']));+// An error that says a run again cannot change it. `refusal` makes one; `neverRetry` marks one that exists. The message is the maker's to read and nobody's to judge.function refusal(message, props = {}) {const { cause, ...rest } = props;@@ -306,7 +313,7 @@ const statusesOf = (error) => [error.statusCode, embeddedStatus(error)].filter((// `declares(table, column)` is the caller's (it knows the spec): whether the build creates that column, for the lag of a column that is not visible yet.function judgeFailure(error, { declares } = {}) {const chain = causeChain(error);- const explicit = chain.some((e) => e.transient === false);+ const explicit = chain.some((e) => e.transient === false || OUTCOME_UNKNOWN_CODES.has(typedCode(e)));const statuses = chain.flatMap(statusesOf);const transientStatus = statuses.some(isTransientStatus);const transport = chain.some(isTransportBlip);diff --git a/plugins/model-apps/scripts/lib/sdk-build.js b/plugins/model-apps/scripts/lib/sdk-build.jsindex 436fa7f2a..4493c3d63 100644--- a/plugins/model-apps/scripts/lib/sdk-build.js+++ b/plugins/model-apps/scripts/lib/sdk-build.js@@ -153,6 +153,7 @@ const { isAppTextMap, appTextKind, localizedAppText } = require('./app-header-te// raises itself is made by refusal() (deterministic) or serviceFailure() (the plugin's words around a failure of the service), because the build's retry reads a failure's STRUCTURE and the// service's words, never a message that quotes what the maker named. tests/halt-retry-policy.test.js enumerates the halts in this file and holds each to a table.const { RETRY, isTransientStatus, judgeFailure, retryPolicyFor, retryFrom, refusal, serviceFailure, withCause } = require('./retry-policy.js');+const { HTTP_SEND_HISTORY } = require('./sdk-http-client.js');// Re-export from entity-provision so the export surface stays unchangedconst BuildHalt = _BuildHalt;@@ -369,6 +370,59 @@ const FORM_EVENTS = new Set(['onload', 'onsave', 'onchange']);// WWF XAML substitute. Environments where the member is undeclared therefore cannot host business// rules at all; that is a platform-side rollout, not something a spec can work around.const BUSINESS_RULE_MEMBER = 'Microsoft.Dynamics.CRM.CreateProcessWithWfomJson';+// What an environment that declares the member but has it switched off answers to EVERY create, whatever the rule holds (garbage content+// included) — the answer a platform feature gate gives, which names nothing:+// POST <env>/api/data/v9.0/workflows(00000000-0000-0000-0000-000000000000)/Microsoft.Dynamics.CRM.CreateProcessWithWfomJson+// HTTP 400 {"error":{"code":"0x80040216","message":"An unexpected error occurred."}}+// The code is generic (0x80040216 is the platform's "unexpected error"), so it is read together with the status AND the member that was+// asked, and only for the FIRST create of a build (see isConfirmedBusinessRuleRefusal). Measured on every production-geo environment tried.+// The SAME answer also comes from a create the platform SAVED and then failed to finish (#482: the workflow row commits, then generating+// its UiData faults — measured as live, firing rows), so the answer alone never proves nothing was written: the build reads the rule's+// definitions again before it calls rules unavailable (refusedCreateWroteNothing, in the business-rules phase).+const BUSINESS_RULE_SWITCHED_OFF_CODE = '0x80040216';++// True when `err` is the DEFINITIVE answer to the first send of a business-rule create that the platform answers when the member is switched off — the HTTP 400 above to+// a call of the business-rule member — and nothing in it or behind it leaves the create's outcome open. The SDK throws the answer as+// Error 'HTTP 400 from <url>: An unexpected error occurred.' { code: 'CONNECTION_ERROR', statusCode: 400, url, cause: <the response body> }+// and, where a push reports it by value, `requireSuccessfulPush` wraps it in a BuildHalt whose `cause` is that error — so the chain is walked rather than only the top.+// The words of the message are never read: the platform answers in the caller's language, the code does not change.+//+// A 400 is a refusal OF THE SEND THAT GOT IT, and says nothing of one before it. An earlier send of the same create that got no answer, or a gateway's 5xx, can have+// created the rule; the plugin's HTTP client sends such a create again, and the SDK may call it again, and the 400 that finally comes would then read as "nothing was+// created". So the answer is accepted only when+// - nothing in the chain says the outcome is unknown or partial (`outcome: 'unknown'`, a code naming an unknown outcome such as UPSERT_OUTCOME_UNKNOWN, the rule left+// deactivated) or is itself an answer that proves nothing (no answer, status 0; a 5xx; a success status the SDK could not use): that wins over a match further down.+// (`transient: false` alone is NOT such a mark: the halt requireSuccessfulPush makes around a refusal carries it, and that wrapper is transparent.) And+// - the plugin's HTTP client reports, on the answer's body, that no earlier send of this request was ambiguous (HTTP_SEND_HISTORY). A transport that reports nothing is+// not confirmed: it halts, as it did before this gate. This does not depend on the create being sent only once by anything else.+// Even then the answer is only a CANDIDATE: a create the platform saved and then failed to finish answers the same 400 (see BUSINESS_RULE_SWITCHED_OFF_CODE). The+// business-rules phase accepts it only after a fresh, complete read finds no definition of the rule that the snapshot taken just before the push lacked.+// The member is told by the request, never by a substring of a URL: the build's own reads of the rule's name (workflows?$filter=name eq '…') can quote the member's name.+function isConfirmedBusinessRuleRefusal(err) {+ const chain = [];+ for (let e = err; e && typeof e === 'object' && chain.length < 6 && !chain.includes(e); e = e.cause) chain.push(e);+ for (const e of chain) {+ const status = e.statusCode != null ? e.statusCode : e.status;+ if (e.outcome === 'unknown' || /outcome[-_ ]?unknown/i.test(String(e.code || '')) || e.code === 'BUSINESS_RULE_LEFT_DEACTIVATED') return false;+ if (Number.isInteger(status) && (status === 0 || status >= 500 || (status >= 200 && status < 300))) return false;+ }+ const answered = chain.find((e) => (e.statusCode != null ? e.statusCode : e.status) === 400 && isBusinessRuleMemberUrl(e.url));+ const body = answered && answered.cause;+ if (!body || typeof body !== 'object') return false;+ const code = body.error && body.error.code;+ if (typeof code !== 'string' || code.toLowerCase() !== BUSINESS_RULE_SWITCHED_OFF_CODE) return false;+ const history = body[HTTP_SEND_HISTORY];+ return Boolean(history) && history.earlierAmbiguous === false;+}++// Whether a request URL is a call of the business-rule member: a path that ends with it. The create is a POST of+// <env>/api/data/v9.0/workflows(00000000-0000-0000-0000-000000000000)/Microsoft.Dynamics.CRM.CreateProcessWithWfomJson+// and nothing else the build sends ends so; a query string that quotes the name (…/workflows?$filter=name eq 'Microsoft.Dynamics.CRM.CreateProcessWithWfomJson') is not it.+function isBusinessRuleMemberUrl(url) {+ let pathname;+ try { pathname = new URL(String(url), 'https://placeholder.invalid').pathname; } catch { return false; }+ return pathname.endsWith(`/${BUSINESS_RULE_MEMBER}`);+}// The per-app setting name that turns on the modern ("new look") shell. Verified live against a real// organization: `settingdefinition` uniquename `NewLookAlwaysOn`, datatype 2 (boolean), default@@ -5913,6 +5967,12 @@ async function runSdkBuildPhases(spec, opts, owed) {// Warn ONCE per build, not once per rule: on an environment without the member every rule skips,// and N copies of the same paragraph buries the rest of the build output.let businessRuleApiWarned = false;+ // The two ways a rule is refused "for this environment", and what they allow. `created` counts the rules THIS build created: the+ // switched-off answer (isConfirmedBusinessRuleRefusal) is read as "this environment does not host rules" only while it is the+ // answer to the first create. After a rule was created the environment plainly hosts them, and the same answer is a failure to halt on.+ // A rule that already existed is not a create — it proves nothing about what the member does now.+ let businessRulesCreated = 0;+ let businessRulesSwitchedOff = false;// A rule is skipped only for this ONE reason; anything else still halts. Matching is on the// SDK's documented `code`, never on `err.name` — the bundle is minified, so the class name is a// rebuild-unstable string (`Xe`, which is really the base SdkError), and matching it would@@ -5937,6 +5997,32 @@ async function runSdkBuildPhases(spec, opts, owed) {if (codes.includes('BUSINESS_RULE_LEFT_DEACTIVATED')) return false;return codes.includes('BUSINESS_RULE_API_UNAVAILABLE') ? 'unsupported in this environment' : false;};+ // Whether a business-rule create that got the switched-off answer left no definition of this rule that the snapshot taken just+ // before its push lacked. Only that proves the refused create wrote nothing: the same HTTP 400 comes from a create the platform+ // saved and then failed to finish (#482). `workflows` answers { "value": [ { "workflowid": "<id>" } ] }; a complete read is required.+ // A new id is never attributed to this create (another writer can add a same-name definition meanwhile); either way it halts.+ // { nothing: true } no id the snapshot lacked: nothing was created+ // { nothing: false, why: <warning> } a new id (saved then failed, or another writer's), or a read that failed or was incomplete+ const refusedCreateWroteNothing = async (name, entityLogical, beforeCreate) => {+ const prefix = `business rule "${name}" on ${entityLogical}: the create answered HTTP 400 ${BUSINESS_RULE_SWITCHED_OFF_CODE}`;+ let after;+ try {+ after = await provision.queryRecords('workflow', {+ select: ['workflowid'], filter: businessRuleFilter(name, entityLogical), paginate: true,+ });+ } catch (e) {+ return { nothing: false, why: `${prefix}, and the read that would show whether the platform saved the rule anyway failed (${String((e && e.message) || e).replace(/\s+/g, ' ').slice(0, 200)}), so the build stops instead of calling business rules unavailable here.` };+ }+ if (!Array.isArray(after) || after.some((w) => !w || typeof w.workflowid !== 'string' || !w.workflowid.trim())) {+ return { nothing: false, why: `${prefix}, and the read that would show whether the platform saved the rule anyway returned an unreadable id set, so the build stops instead of calling business rules unavailable here.` };+ }+ const before = new Set(beforeCreate.map((w) => w.workflowid.toLowerCase()));+ const added = after.map((w) => w.workflowid).filter((id) => !before.has(id.toLowerCase()));+ if (added.length) {+ return { nothing: false, why: `${prefix}, yet a definition of this rule that was not there just before the create now exists (${added.join(', ')}). Either the platform saved this create and then failed to finish it, or something else added that rule meanwhile, so the answer does not show that business rules are unavailable here and the build stops. Check that rule in Power Apps (it may be active) before running the build again; the next run reuses it.` };+ }+ return { nothing: true };+ };for (const rule of spec.businessRules || []) {const entityLogical = String(rule.entity).toLowerCase();const existing = await provision.queryRecords('workflow', {@@ -6008,6 +6094,15 @@ async function runSdkBuildPhases(spec, opts, owed) {}continue;}+ if (businessRulesSwitchedOff) {+ // The first create showed this environment does not host rules: the rest are not sent (each would be refused the same way).+ result.skipped.businessRules.push(`${entityLogical}|${rule.name}`);+ runner.skip('business-rules', `business rule "${rule.name}" on ${rule.entity} (unsupported in this environment)`);+ continue;+ }+ // Set by the create step when the switched-off answer was checked against a fresh read of this rule's definitions and nothing+ // was created (refusedCreateWroteNothing); read by the step's skipIf, which is synchronous and cannot read the service itself.+ let refusedRuleWroteNothing = false;await runner.run('business-rules', `business rule "${rule.name}" on ${rule.entity}`, async () => {const def = businessRuleDef(rule);const art = await provision.createArtifact('businessRule', def);@@ -6045,8 +6140,21 @@ async function runSdkBuildPhases(spec, opts, owed) {if (!Array.isArray(beforeCreate) || beforeCreate.some((w) => !w || typeof w.workflowid !== 'string' || !w.workflowid.trim())) {throw refusal(`business rule "${rule.name}" on ${entityLogical}: before-create id snapshot is unreadable — refusing to push or delete rules without a complete id set`);}- const pushed = requireSuccessfulPush(await provision.pushArtifact('businessRule', art.id), `business rule ${rule.name}`, opts.warn);+ let pushed;+ try {+ pushed = requireSuccessfulPush(await provision.pushArtifact('businessRule', art.id), `business rule ${rule.name}`, opts.warn);+ } catch (err) {+ // Only the answer the gate could accept is checked (every other failure halts as it is, without a read). The read decides+ // between "switched off here" (nothing new: the step may skip) and a rule the platform saved anyway, or an unknown (halt).+ if (businessRulesCreated === 0 && isConfirmedBusinessRuleRefusal(err)) {+ const verdict = await refusedCreateWroteNothing(rule.name, entityLogical, beforeCreate);+ refusedRuleWroteNothing = verdict.nothing;+ if (!verdict.nothing && typeof opts.warn === 'function') opts.warn(verdict.why);+ }+ throw err;+ }result.created.businessRules[`${entityLogical}|${rule.name}`] = pushed.id;+ businessRulesCreated += 1;await provision.addSolutionComponent({ componentId: pushed.id, componentType: COMPONENT_TYPE.workflow, solutionUniqueName: sol.uniqueName });// The SDK returns the primary saved id, which is kept. It supplies no receipts for other// definitions, so a before/after delta cannot distinguish its retries from concurrent creates.@@ -6073,12 +6181,22 @@ async function runSdkBuildPhases(spec, opts, owed) {// must not happen. The skip is recorded on the result so `--verify` and the run summary can// report it rather than implying the rules exist.skipIf: (err) => {- const reason = businessRuleApiUnavailable(err);+ let reason = businessRuleApiUnavailable(err);+ let notCreated = `this environment does not expose the '${BUSINESS_RULE_MEMBER}' member that the modern business-rule designer uses, so there is no supported way to author them here.`;+ let remedy = 'Re-run against an environment that exposes the member, or drop businessRules[] from the spec.';+ if (!reason && businessRulesCreated === 0 && refusedRuleWroteNothing && isConfirmedBusinessRuleRefusal(err)) {+ // The member is declared but switched off: the refusal is the definitive answer to the first send of the create, and a fresh+ // read of the rule's definitions shows nothing was created.+ reason = 'unsupported in this environment';+ businessRulesSwitchedOff = true;+ notCreated = `this environment answered HTTP 400 ${BUSINESS_RULE_SWITCHED_OFF_CODE} ("An unexpected error occurred") to the '${BUSINESS_RULE_MEMBER}' member, which means business-rule creation is not available on it. That is a platform limit, commonly on production environments, not a fault in the rule; the first rule was refused and the remaining rules were not sent.`;+ remedy = 'Use an environment where business-rule creation is available, or drop businessRules[] from the spec.';+ }if (!reason) return false;result.skipped.businessRules.push(`${entityLogical}|${rule.name}`);if (!businessRuleApiWarned && typeof opts.warn === 'function') {businessRuleApiWarned = true;- opts.warn(`business rules were NOT created: this environment does not expose the '${BUSINESS_RULE_MEMBER}' member that the modern business-rule designer uses, so there is no supported way to author them here. Everything else in the app was built normally. Re-run against an environment that exposes the member, or drop businessRules[] from the spec. Detail: ${String((err && err.message) || err).replace(/\s+/g, ' ').slice(0, 300)}`);+ opts.warn(`business rules were NOT created: ${notCreated} Everything else in the app was built normally. ${remedy} Detail: ${String((err && err.message) || err).replace(/\s+/g, ' ').slice(0, 300)}`);}return reason;},diff --git a/plugins/model-apps/scripts/lib/sdk-http-client.js b/plugins/model-apps/scripts/lib/sdk-http-client.jsindex 2d14267f5..fdd66f494 100644--- a/plugins/model-apps/scripts/lib/sdk-http-client.js+++ b/plugins/model-apps/scripts/lib/sdk-http-client.js@@ -16,6 +16,10 @@const { dataverseOrigin, getAuthToken, makeRequest, tokenFailureMessage } = require('./dataverse-auth.js');const { needlesOf, noteToken, TOKEN_MARKER } = require('./output-redaction.js');+// The key under which a failure's body carries the history of the sends that led to it (`{ sends, earlierAmbiguous }`, see `ambiguousSends` in createAzHttpClient).+// Symbol.for, so a module that reads it need not load this client, and the copy of this file in another plugin agrees with it.+const HTTP_SEND_HISTORY = Symbol.for('power-platform-skills.http-send-history');+// How Dataverse reports that SQL Server chose a request's transaction as a deadlock VICTIM and rolled// it back. Two live captures, both HTTP 500 (a process-flow delete during a teardown, and PublishXml):// HTTP 500 from …/api/data/v9.0/workflows(<id>): Sql error: Generic SQL error. CRM ErrorCode: -2147204784 Sql ErrorCode: -2146232060 Sql Number: 1205@@ -709,6 +713,14 @@ function createAzHttpClient(orgUrl, deps = {}) {// Every access token this client has sent — the one a 401 refresh replaced as well as the one that replaced it, because a service may repeat either — for taking it out of an answer that is not a success// and out of a transport failure's text (the scrubber above). A success is never given to these.const tokensSent = new Set();++ // The sends of a write that may have run, whatever answered them: `POST <url>` -> true once a send of it got no answer, was cut off, or was answered by the+ // service being down or throttling (5xx; a 429 that is not the service protection limits). Such a send can have been applied; an answer to a LATER send of the+ // same request — a re-send of this client's loop, or the SDK's own re-call — says nothing about it. A failure delivered afterwards says so (HTTP_SEND_HISTORY),+ // so a caller that reads the later answer as a definitive refusal (the business-rule gate in lib/sdk-build.js) can tell it is not. Kept for the client's life and+ // never cleared: it only ever turns a caller's skip into the halt it always was.+ const ambiguousSends = new Set();+ const isAmbiguousAnswer = (res) => Boolean(res.error) || res.statusCode >= 500 || (res.statusCode === 429 && !isServiceProtectionRefusal(res));const scrubText = (text) => [...tokensSent].reduce((out, sent) => scrub(out, sent), String(text));const scrubValue = (value) => [...tokensSent].reduce((out, sent) => scrubAnswer(out, sent), value);// A Buffer is returned as it is unless it holds the token as text: bytes that are not text, or hold no token, are never decoded into something else.@@ -808,14 +820,20 @@ function createAzHttpClient(orgUrl, deps = {}) {// What the caller is given for an answer that is not sent again — the last the loop got, or a throttled one a budgeted client did not wait for. An answer that is not a success is what an SDK makes an error message of (it quotes the body, and the// scripts print that message), so the token is taken out of it first — the body in whatever mode it is read in, and the headers. A success is the caller's data and is returned exactly as it came.- const deliver = (res) => {+ const deliver = (res, history) => {if (!(res.statusCode >= 200 && res.statusCode < 300)) {const text = (value) => (typeof value === 'string' ? scrubText(value) : value);- return {+ const answer = {status: res.statusCode,headers: scrubValue(res.headers || {}),body: ctl.bytes ? scrubBytes(res.body) : ctl.rawBody ? text(res.body) : scrubValue(parseBody(text(res.body))),};+ // The SDK keeps a failure's body as the `cause` of the error it raises, the same object, so this reaches the caller of the SDK. A body that is not an+ // object (text, bytes) carries nothing, and a caller that needs the history then has none to read.+ if (history && answer.body && typeof answer.body === 'object' && !Buffer.isBuffer(answer.body)) {+ Object.defineProperty(answer.body, HTTP_SEND_HISTORY, { value: history, enumerable: false });+ }+ return answer;}return {status: res.statusCode,@@ -853,6 +871,10 @@ function createAzHttpClient(orgUrl, deps = {}) {}const res = await request({ url, method, headers, body: bodyOut, includeHeaders: true, timeout: isWrite ? WRITE_TIMEOUT_MS : READ_TIMEOUT_MS, ...(ctl.bytes ? { binary: true } : {}) });+ // Read before this answer is recorded: what matters to a caller is whether an EARLIER send was ambiguous.+ const sendKey = `${method_} ${url}`;+ const history = { sends: attempt + 1, earlierAmbiguous: ambiguousSends.has(sendKey) };+ if (isWrite && isAmbiguousAnswer(res)) ambiguousSends.add(sendKey);if (res.error) {if (conditional) {throw transportError(res, `Request failed: ${scrubText(res.error)} — this conditional ${method_} was not re-sent, because it may still commit and a re-send could only be refused as a false version conflict`);@@ -883,7 +905,7 @@ function createAzHttpClient(orgUrl, deps = {}) {// victim (500), a gateway (502, 503, 504) — is not throttling, and keeps its own schedule.if (throttle && res.statusCode === 429) {if (await waitOutThrottle({ res, attempt, method: method_, url })) continue;- return deliver(res);+ return deliver(res, history);}await sleep(retryWaitMs(res, attempt));continue;@@ -915,7 +937,7 @@ function createAzHttpClient(orgUrl, deps = {}) {if (throttled && !last) {if (throttle) {if (await waitOutThrottle({ res, attempt, method: method_, url, batch: isBatch })) continue;- return deliver(res);+ return deliver(res, history);}// A batch refused operation by operation may carry the wait in that operation's own headers.await sleep(Math.max(retryWaitMs(res, attempt), isBatch ? batchRetryAfterMs(res, now()) : 0));@@ -927,7 +949,7 @@ function createAzHttpClient(orgUrl, deps = {}) {await sleep(1000 * 2 ** attempt);continue;}- return deliver(res);+ return deliver(res, history);}/* istanbul ignore next */throw new Error('Unreachable retry loop');@@ -964,4 +986,4 @@ function createAzHttpClient(orgUrl, deps = {}) {};}-module.exports = { createAzHttpClient, SQL_DEADLOCK_VICTIM, DEADLOCK_RESENDS, isSqlDeadlockVictim, isBatchDeadlockVictim, isBatchThrottled, completeBatchStatus, batchRetryAfterMs, isConditionalDeleteBatch, isColumnCreateBatch, isTransientTransportFailure, TRANSIENT_TRANSPORT_CODES, SERVICE_PROTECTION_CODES, isServiceProtectionRefusal, retryAfterMs, throttleBackoffMs, RETRY_AFTER_CAP_MS, scrub, scrubAnswer, scrubBearer, MIN_SCRUBBED_TOKEN_LENGTH };+module.exports = { createAzHttpClient, HTTP_SEND_HISTORY, SQL_DEADLOCK_VICTIM, DEADLOCK_RESENDS, isSqlDeadlockVictim, isBatchDeadlockVictim, isBatchThrottled, completeBatchStatus, batchRetryAfterMs, isConditionalDeleteBatch, isColumnCreateBatch, isTransientTransportFailure, TRANSIENT_TRANSPORT_CODES, SERVICE_PROTECTION_CODES, isServiceProtectionRefusal, retryAfterMs, throttleBackoffMs, RETRY_AFTER_CAP_MS, scrub, scrubAnswer, scrubBearer, MIN_SCRUBBED_TOKEN_LENGTH };diff --git a/plugins/model-apps/scripts/lib/sdk-teardown.js b/plugins/model-apps/scripts/lib/sdk-teardown.jsindex 8cc39c8ee..492c254d5 100644--- a/plugins/model-apps/scripts/lib/sdk-teardown.js+++ b/plugins/model-apps/scripts/lib/sdk-teardown.js@@ -1130,10 +1130,19 @@ const KIND_HANDLERS = {// table owned elsewhere; and// · any non-custom/system table (account, contact, …) — never created by a build, and// Dataverse refuses to delete it, so a delete attempt would only surface a noisy error.- // A table that can't be discovered is treated as already-gone: fall through to the delete+ // A table the read answered and did not list is treated as already-gone: fall through to the delete// call, which tolerates the cosmetic/absent 404 (see tolerateNotFound).//- // One failure of that read is not "can't be discovered": an answer that is no list of tables — a+ // A read that FAILED is not "not listed", and neither is a list the read could not finish. The bundled SDK reads+ // the table list to its end and refuses an answer that says more rows exist without a link to them+ // (`@Microsoft.Dynamics.CRM.morerecords`), or whose next page fails, e.g.+ // HTTP 200 from …/EntityDefinitions?$select=…: findTables: paginated read returned a page that says more rows exist (…)+ // HTTP 503 from …/EntityDefinitions?$skiptoken=…: Service Unavailable+ // — a refusal of the read (403) is the same. After any of them nothing says the table is there, gone, or a+ // system table, so the step fails CLOSED with the reason (a DELETE from half an answer could be the one sent+ // to a system table the unread rest would have shown), and a re-run once the read answers finishes it.+ //+ // One failure of that read says more: an answer that is no list of tables — a// sign-in or proxy page, `{}`, `null`, which lib/maker-sdk.js turns into TABLES_UNREADABLE — says the// environment is not answering as Dataverse. The SDK reads it as "no tables", so the system-table check// below would go unmade; and where every answer is such a page, the DELETE that follows is answered@@ -1147,20 +1156,24 @@ const KIND_HANDLERS = {}let table = null;// Whether the read said if the table was there before its delete: `true` it listed it, `false` it answered and listed no such- // table, `undefined` it could not tell — it failed, or its matches were cut at `top` (findTables reads every table and keeps the+ // table, `undefined` it could not tell — its matches were cut at `top` (findTables reads every table and keeps the// first 50 whose names contain the query, so a list of 50 may have left the table out).let seen;- try {- const hits = await sdk.findTables(target.logical, { top: 50 });- table = (hits || []).find((t) => String(t.logicalName).toLowerCase() === target.logical) || null;- if (table) seen = true;- else if ((hits || []).length < 50) seen = false;- } catch (err) {- const unreadable = unreadableAnswer(err);- if (unreadable) {- throw Object.assign(new Error(`table '${target.logical}' was not deleted: ${unreadable.message}`), { code: unreadable.code, cause: unreadable, failClosed: true });+ // Every SDK a script makes has findTables (tests/sdk-surface-contract.test.js); a stand-in without it makes no read, as before.+ if (typeof (sdk && sdk.findTables) === 'function') {+ try {+ const hits = await sdk.findTables(target.logical, { top: 50 });+ table = (hits || []).find((t) => String(t.logicalName).toLowerCase() === target.logical) || null;+ if (table) seen = true;+ else if ((hits || []).length < 50) seen = false;+ } catch (err) {+ const unreadable = unreadableAnswer(err);+ if (unreadable) {+ throw Object.assign(new Error(`table '${target.logical}' was not deleted: ${unreadable.message}`), { code: unreadable.code, cause: unreadable, failClosed: true });+ }+ const why = String((err && err.message) || err).trim();+ throw Object.assign(new Error(`table '${target.logical}' was not deleted: the environment's tables could not be read, so whether it is there, and whether it is a system table, is unknown (${why}). Run the teardown again once the environment answers.`), { code: (err && err.code) || 'TABLE_LIST_UNREADABLE', cause: err, failClosed: true });}- table = null;}if (table && table.isCustom === false) {return { items: [], skipReason: 'system table — not created by this build' };diff --git a/plugins/model-apps/scripts/run-tests.js b/plugins/model-apps/scripts/run-tests.jsindex e2b6e2209..fcd0e4aeb 100644--- a/plugins/model-apps/scripts/run-tests.js+++ b/plugins/model-apps/scripts/run-tests.js@@ -1,7 +1,7 @@#!/usr/bin/env node'use strict';// One-command regression gate for model-apps. Runs the full plugin node:test suite and, with-// `--with-sdk <ppux-path>`, the vendored SDK's Jest suite under Node 20 (the canvas native module+// `--with-sdk <sdk-repo-path>`, the vendored SDK's Jest suite under Node 20 (the canvas native module// 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@@ -11,8 +11,8 @@//// Usage:// node scripts/run-tests.js # plugin suite only-// node scripts/run-tests.js --with-sdk D:/Projects/power-platform-ux-sdk-// NODE20_BIN=C:/path/to/node20/dir node scripts/run-tests.js --with-sdk <ppux>+// node scripts/run-tests.js --with-sdk <sdk-repo>+// NODE20_BIN=C:/path/to/node20/dir node scripts/run-tests.js --with-sdk <sdk-repo>const { spawnSync } = require('node:child_process');const { spawnResultSync, withPathFirst } = require('./lib/process-runner.js');@@ -159,7 +159,7 @@ function main(argv) {if (sdkIdx > -1 && !sdkPath) {// `--with-sdk` is a regression gate opt-in; silently skipping on a missing path makes a// supposedly SDK-covered run green, so treat the omitted value as a usage error.- process.stderr.write('Usage: node scripts/run-tests.js [--with-sdk <ppux-path>]\n');+ process.stderr.write('Usage: node scripts/run-tests.js [--with-sdk <sdk-repo-path>]\n');return 2;}const pluginRoot = path.join(__dirname, '..');diff --git a/plugins/model-apps/scripts/tests/app-component-scope.test.js b/plugins/model-apps/scripts/tests/app-component-scope.test.jsindex 962df0483..ad4ff3c75 100644--- a/plugins/model-apps/scripts/tests/app-component-scope.test.js+++ b/plugins/model-apps/scripts/tests/app-component-scope.test.js@@ -366,6 +366,75 @@ test('a $batch that names the action is REFUSED while an edit is open — a partassert.strictEqual(scope.wrap({ post: async () => ({}) }).postRaw, undefined);});+// The bundled SDK's guarded pin (lib/app-component-scope.js, THE SDK'S GUARDED PIN): one change set of guard, action and echo, rendered as the bundle renders it. For an app with an edit open it is+// not sent — the SDK is answered with a refused guard, and sends its plain action, which is limited — and any change set that differs from it in anything is refused as every batch that names the action is.+function guardedPin({ app = APP, action = app, echo = app, solution = false, parts } = {}) {+ const part = (id, line, headers, body) => ['--changeset_7', 'Content-Type: application/http', 'Content-Transfer-Encoding: binary', `Content-ID: ${id}`, '', line, ...headers, '', body].join('\r\n');+ const json = 'Content-Type: application/json;type=entry';+ const named = solution ? ['MSCRM.SolutionUniqueName: contoso_solution'] : [];+ const all = parts || [+ part(1, `PATCH ${ROOT}/appmodules(${app}) HTTP/1.1`, [json, ...named, 'If-Match: W/"41"'], '{}'),+ part(2, `POST ${ADD} HTTP/1.1`, [json, ...named], JSON.stringify(derived(action))),+ part(3, `PATCH ${ROOT}/appmodules(${echo})?$select=appmoduleid HTTP/1.1`, [json, ...named, 'Prefer: return=representation'], '{}'),+ ];+ return { part, json, text: ['--batch_9', 'Content-Type: multipart/mixed;boundary=changeset_7', '', ...all, '--changeset_7--', '--batch_9--', ''].join('\r\n') };+}++test('the SDK\'s guarded pin for an app with an edit open is NOT sent — the SDK is answered with a change set whose guard was refused, so it sends its plain action, which is limited; another app\'s goes on as it was read', async () => {+ const scope = makeAppComponentScope();+ const { client, calls } = rawTransport();+ const wrapped = scope.wrap(client);+ await scope.limit(APP, { views: [VIEW] }, async () => {+ for (const body of [guardedPin().text, Buffer.from(guardedPin({ solution: true }).text), guardedPin({ app: APP.toUpperCase() }).text]) {+ const answer = await wrapped.postRaw(`${ROOT}/$batch`, body, { headers: { 'Content-Type': 'multipart/mixed;boundary=batch_9' } });+ assert.strictEqual(answer.status, 200);+ const boundary = /^--(batchresponse_[0-9a-f-]+)\r\n/.exec(answer.body);+ assert.ok(boundary && answer.body.endsWith(`--${boundary[1]}--\r\n`), 'a whole change-set answer');+ assert.match(answer.body, /\r\nContent-ID: 1\r\n\r\nHTTP\/1\.1 400 Bad Request\r\n/, 'one part, answering the guard, refused');+ assert.strictEqual((answer.body.match(/^HTTP\/1\.1 /gm) || []).length, 1);+ assert.match(answer.body, /"code":"APP_COMPONENTS_GUARD_NOT_SENT"/);+ }+ assert.deepStrictEqual(calls, [], 'nothing was sent');+ const other = guardedPin({ app: OTHER_APP }).text;+ await wrapped.postRaw(`${ROOT}/$batch`, other, {});+ assert.deepStrictEqual(calls, [[`${ROOT}/$batch`, other, {}]], 'another app\'s pin is not this edit\'s');+ });+ calls.length = 0;+ await wrapped.postRaw(`${ROOT}/$batch`, guardedPin().text, {});+ assert.strictEqual(calls.length, 1, 'with no edit open it is nobody\'s to read');+});++test('a change set that is not exactly the SDK\'s guarded pin is REFUSED as any batch that names the action is — another part, another app in one part, a header, a body or a method it does not have — and nothing is sent', async () => {+ const scope = makeAppComponentScope();+ const { client, calls } = rawTransport();+ const wrapped = scope.wrap(client);+ const { part, json, text } = guardedPin();+ const guard = part(1, `PATCH ${ROOT}/appmodules(${APP}) HTTP/1.1`, [json, 'If-Match: W/"41"'], '{}');+ const add = part(2, `POST ${ADD} HTTP/1.1`, [json], JSON.stringify(derived()));+ const echo = part(3, `PATCH ${ROOT}/appmodules(${APP})?$select=appmoduleid HTTP/1.1`, [json, 'Prefer: return=representation'], '{}');+ const variants = {+ 'a fourth part': guardedPin({ parts: [guard, add, echo, part(4, `POST ${ROOT}/RemoveAppComponents HTTP/1.1`, [json], JSON.stringify(derived()))] }).text,+ 'no echo': guardedPin({ parts: [guard, add] }).text,+ 'the parts in another order': guardedPin({ parts: [add, guard, echo] }).text,+ 'the action for another app': guardedPin({ action: OTHER_APP }).text,+ 'the echo of another app': guardedPin({ echo: OTHER_APP }).text,+ 'a guard with a body': guardedPin({ parts: [part(1, `PATCH ${ROOT}/appmodules(${APP}) HTTP/1.1`, [json, 'If-Match: W/"41"'], '{"name":"x"}'), add, echo] }).text,+ 'a guard that is not conditional': guardedPin({ parts: [part(1, `PATCH ${ROOT}/appmodules(${APP}) HTTP/1.1`, [json], '{}'), add, echo] }).text,+ 'an echo that does not ask for the row': guardedPin({ parts: [guard, add, part(3, `PATCH ${ROOT}/appmodules(${APP})?$select=appmoduleid HTTP/1.1`, [json], '{}')] }).text,+ 'a header the SDK does not send': guardedPin({ parts: [guard, part(2, `POST ${ADD} HTTP/1.1`, [json, 'X-Other: 1'], JSON.stringify(derived())), echo] }).text,+ 'the action in another spelling': guardedPin({ parts: [guard, part(2, `POST ${ROOT}/addappcomponents HTTP/1.1`, [json], JSON.stringify(derived())), echo] }).text,+ 'trailing text after the batch': `${text}x`,+ };+ await scope.limit(APP, { views: [VIEW] }, async () => {+ for (const [label, body] of Object.entries(variants)) {+ await assert.rejects(wrapped.postRaw(`${ROOT}/$batch`, body, {}), (e) => e instanceof SdkError && e.code === 'APP_COMPONENTS_NOT_LIMITED', label);+ }+ await assert.rejects(wrapped.post(`${ROOT}/$batch`, text, {}), (e) => e.code === 'APP_COMPONENTS_NOT_LIMITED', 'through post, which is not how the SDK sends a change set');+ await assert.rejects(wrapped.postRaw(`${ROOT}/other`, text, {}), (e) => e.code === 'APP_COMPONENTS_NOT_LIMITED', 'to an address that is not the batch endpoint');+ });+ assert.deepStrictEqual(calls, []);+});+// ── A raw POST is told by its address as a post is ───────────────────────────────────────────────────────────────────────────────────────────────────// `postRaw` is a real POST, not only the SDK's `$batch`: the plugin's transport sends it as `call('POST', url, body, options, { rawBody: true })`, with a body that is text, or the bytes of it, that it// does not touch. The bundle sends the action through `post` today. A request to the action's address through `postRaw` — a drift of the bundle, or another caller — is limited exactly as the objectdiff --git a/plugins/model-apps/scripts/tests/bpf-stage-edits.test.js b/plugins/model-apps/scripts/tests/bpf-stage-edits.test.jsindex 743523ec0..3984a7a7c 100644--- a/plugins/model-apps/scripts/tests/bpf-stage-edits.test.js+++ b/plugins/model-apps/scripts/tests/bpf-stage-edits.test.js@@ -761,6 +761,47 @@ const xamlStages = (row) => [...row.xaml.matchAll(/DisplayName="StageStep\d+: ([const xamlStageIds = (row) => [...row.xaml.matchAll(/x:Key="StageId">([^<]+)</g)].map((m) => m[1]);const xamlSteps = (row) => [...row.xaml.matchAll(/DisplayName="StepStep\d+: ([^"]*)"/g)].map((m) => m[1]);+// REAL BUNDLES: a flow the PREVIOUS release's SDK created, whose copy (stamped with its older projection) is still in the workspace —+// the build's own app folder workspace — edited by this release's SDK on that SAME workspace, the first thing it does there. The stage+// plan fetches the flow with `overwrite: true`, so the old copy is replaced by a current one and pushed: the edit goes over the wire and+// lands exactly as it does for a flow this release created.+const { skipWithoutPrevious, requirePrevious } = require('./helpers/previous-bundle.js');+test('REAL BUNDLES: a flow the previous release created, its old copy still in the workspace, is edited by this release as one it created', { skip: skipWithoutPrevious() }, async () => {+ const d = DEPLOYED();+ const want = flowOf([{ ...d.stages[0], name: 'Intake' }, stage('Resolve', 'Notes:new_notes', 'Confirmed with customer:new_owner', 'Region:new_region'), d.stages[2], stage('Archive', 'Notes:new_notes')]);+ const run = async (creatorBundle) => {+ const fake = fakeWorkflows();+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'bpf-upgrade-'));+ tempDirs.push(dir);+ const open = async (bundle) => {+ const sdk = bundle.createMakerSdk({ workspaceStorage: bundle.createNodeWorkspaceStorage(dir), instanceUrl: 'https://contoso.crm.dynamics.com', httpClient: fake.client });+ await sdk.initWorkspace();+ return sdk;+ };+ const creator = await open(creatorBundle);+ const art = await creator.createArtifact('bpf', bpfDef({ ...d, status: 'Active' }));+ await creator.pushArtifact('bpf', art.id);+ const metaFile = fs.readdirSync(path.join(dir, '.metadata'), { recursive: true }).find((f) => path.basename(String(f)) === `${art.id}.meta.json`);+ assert.ok(metaFile, 'the SDK keeps the flow\'s metadata in the workspace');+ const meta = JSON.parse(fs.readFileSync(path.join(dir, '.metadata', String(metaFile)), 'utf8'));+ fake.log.length = 0;+ const sdk = await open(require(BUNDLE));+ const inspected = await inspectBpfStages(sdk, want, art.id);+ assert.strictEqual(inspected.kind, 'edit', JSON.stringify(inspected));+ const pushed = await applyBpfStages(sdk, want, art.id, inspected.plan, {});+ const row = fake.rows.get(art.id);+ return { projection: meta.projectionVersion, pushed, wire: fake.log.map((l) => `${l.verb} ${l.keys.join(',')} ${l.ifMatch ? 'If-Match' : ''}`), stages: xamlStages(row), steps: xamlSteps(row), statecode: row.statecode };+ };+ const upgrade = await run(requirePrevious());+ const control = await run(require(BUNDLE));+ assert.ok(upgrade.projection < control.projection, `the previous release's copy is an old one (${upgrade.projection} < ${control.projection})`);+ assert.strictEqual(upgrade.pushed.saved, true);+ assert.deepStrictEqual(upgrade.stages, ['Intake', 'Resolve', 'Close', 'Archive']);+ assert.strictEqual(upgrade.statecode, 1, 'the flow is still Active');+ const comparable = ({ wire, stages, steps, statecode }) => ({ wire, stages, steps, statecode });+ assert.deepStrictEqual(comparable(upgrade), comparable(control), 'the same requests and the same flow as for a flow this release created');+});+test('REAL BUNDLE: an Active flow\'s edits go over the wire as ONE conditional change set, and the flow stays Active', async () => {const { sdk, fake, id, row } = await realBpf();const idsBefore = xamlStageIds(row());diff --git a/plugins/model-apps/scripts/tests/build-failure-diagnostics.test.js b/plugins/model-apps/scripts/tests/build-failure-diagnostics.test.jsnew file mode 100644index 000000000..c71c647b8--- /dev/null+++ b/plugins/model-apps/scripts/tests/build-failure-diagnostics.test.js@@ -0,0 +1,170 @@+'use strict';+// The diagnostics a test's unexpectedly failed build keeps (helpers/build-failure-diagnostics.js): the failure of a build that+// should have succeeded must explain itself from the test output alone, without changing what the test asserts and without+// looking outside the folders the scenario owns.+const test = require('node:test');+const assert = require('node:assert/strict');+const fs = require('node:fs');+const path = require('node:path');+const { makeTempDir } = require('./helpers/temp-dirs.js');+const {+ recordBuildFailure, flushBuildFailureDiagnostics, describeBuildFailure, listTree, MAX_LISTING_ENTRIES, MAX_DEPTH,+} = require('./helpers/build-failure-diagnostics.js');++function workspaceWith(files, prefix = 'build-failure-diagnostics-') {+ const dir = makeTempDir(prefix);+ for (const [name, text] of Object.entries(files)) {+ fs.mkdirSync(path.dirname(path.join(dir, name)), { recursive: true });+ fs.writeFileSync(path.join(dir, name), text);+ }+ return dir;+}++function realEnoent(file) {+ try { fs.readFileSync(file); } catch (error) { return error; }+ throw new Error(`${file} exists`);+}++// What a test file's afterEach hook receives; `recorded` is what t.diagnostic printed.+const contextOf = (passed) => { const recorded = []; return { passed, diagnostic: (text) => recorded.push(text), recorded }; };+const discard = () => flushBuildFailureDiagnostics(contextOf(true));++test('build failure diagnostics: a failed build keeps its error chain, the missing path and the workspace apart from the error', () => {+ const dir = workspaceWith({ 'manifest.json': '{}', 'forms/a.json': 'abc', '.metadata/forms/a.meta.json': 'abcdef' });+ const missing = path.join(dir, 'forms', 'gone', 'manifest.json');+ const cause = realEnoent(missing);+ const halt = Object.assign(new Error(`forms failed: Transport failure: ${cause.message}`), { name: 'BuildHalt', code: 'CONNECTION_ERROR', phase: 'forms', cause });+ const original = halt.message;++ const returned = recordBuildFailure(halt, [{ label: 'scenario workspace', dir }]);++ assert.equal(returned, halt, 'the same error comes back');+ assert.equal(halt.message, original, 'its message is exactly what the build threw');+ assert.equal(halt.cause, cause);+ assert.equal(halt.code, 'CONNECTION_ERROR');+ assert.equal(halt.phase, 'forms');+ assert.equal(Object.keys(halt).includes('buildFailureDiagnostics'), false, 'the diagnostics are not an enumerable property of the error');+ const text = halt.buildFailureDiagnostics;+ assert.match(text, /\[0\] BuildHalt \(code="CONNECTION_ERROR", phase="forms"\): forms failed: Transport failure/);+ assert.match(text, /\[1\] Error \(code="ENOENT", errno=-?\d+, syscall="open", path=/, 'the cause is described with its code, syscall and path');+ assert.match(text, /\n {6,}at /, 'a stack is listed for the error and for its cause');+ assert.ok(text.includes(`missing path: ${missing} (exists now: false; nearest existing folder: ${path.join(dir, 'forms')})`), text);+ const listing = text.split('\n').map((line) => line.trim());+ for (const entry of ['.metadata/', '.metadata/forms/a.meta.json (6 bytes)', 'forms/a.json (3 bytes)', 'manifest.json (2 bytes)']) {+ assert.ok(listing.includes(entry), `${entry} is listed: ${text}`);+ }+ assert.ok(text.includes(`scenario workspace: ${dir} (`), 'the folder is named');+ discard();+});++test('build failure diagnostics: a word or number in the listing cannot make an unrelated error satisfy a rejection pattern', () => {+ // The pattern the rebuild-writes tests use to say "this is the failure the test provoked".+ const provoked = /push|500|simulated/i;+ const dir = workspaceWith({ 'artifact.json': 'x'.repeat(500), 'pushed/simulated.json': '' });+ const unrelated = new Error('unrelated failure before the write');+ assert.doesNotMatch(unrelated.message, provoked);++ recordBuildFailure(unrelated, [{ label: 'scenario workspace', dir }]);++ assert.doesNotMatch(unrelated.message, provoked, 'the message is untouched');+ assert.doesNotMatch(String(unrelated.stack).split('\n')[0], provoked);+ assert.match(unrelated.buildFailureDiagnostics, /artifact\.json \(500 bytes\)/, 'the listing, which does hold the words, is kept apart');+ assert.match(unrelated.buildFailureDiagnostics, /pushed\/simulated\.json/);+ discard();+});++test('build failure diagnostics: they are printed only when the test that threw them fails, and only once', () => {+ const error = recordBuildFailure(new Error('boom'), []);+ const passing = contextOf(true);+ flushBuildFailureDiagnostics(passing);+ assert.deepEqual(passing.recorded, [], 'a test that provoked and rejected the failure prints nothing');++ recordBuildFailure(new Error('second'), []);+ const failing = contextOf(false);+ flushBuildFailureDiagnostics(failing);+ assert.equal(failing.recorded.filter((line) => line === '--- build failure diagnostics ---').length, 1, 'only what was recorded since the last test');+ assert.match(failing.recorded.join('\n'), /\[0\] Error: second/);+ const again = contextOf(false);+ flushBuildFailureDiagnostics(again);+ assert.deepEqual(again.recorded, []);+ assert.ok(error.buildFailureDiagnostics, 'the error keeps its own copy');+});++test('build failure diagnostics: a missing workspace lists nothing of its parent or of a path outside the scenario folders', () => {+ const parent = workspaceWith({ 'unrelated-private-project/private-file-name.txt': 'secret', 'scenario/placeholder.txt': 'x' }, 'build-failure-scope-');+ const scenario = path.join(parent, 'scenario');+ const missing = path.join(scenario, 'manifest.json');+ fs.rmSync(scenario, { recursive: true, force: true });+ const outside = workspaceWith({ 'elsewhere/other-name.json': '{}' }, 'build-failure-outside-');+ const outsidePath = path.join(outside, 'elsewhere', 'gone', 'manifest.json');++ const text = describeBuildFailure(+ new Error(`forms failed: ENOENT: no such file or directory, open '${missing}'; then ENOENT: no such file or directory, open '${outsidePath}'`),+ [{ label: 'scenario workspace', dir: scenario }],+ );++ assert.ok(text.includes(`missing path: ${missing} (its scenario workspace no longer exists)`), text);+ assert.ok(text.includes(`scenario workspace: ${scenario} does not exist`), text);+ assert.ok(text.includes(`missing path: ${outsidePath} (outside the folders listed below; not looked at)`), text);+ for (const name of ['unrelated-private-project', 'private-file-name', 'other-name.json', 'placeholder.txt']) {+ assert.equal(text.includes(name), false, `${name} is not disclosed: ${text}`);+ }+});++test('build failure diagnostics: the walk stops at its entry budget, does not count the rest and does not follow links', (t) => {+ const files = {};+ for (let i = 0; i < MAX_LISTING_ENTRIES + 30; i += 1) files[`f${String(i).padStart(3, '0')}.json`] = '';+ const dir = workspaceWith(files);+ const linked = workspaceWith({ 'inside-the-link.txt': 'x' }, 'build-failure-link-target-');+ let linkMade = true;+ try { fs.symlinkSync(linked, path.join(dir, 'aaa-link'), 'junction'); } catch { linkMade = false; }++ const stats = [];+ const original = fs.lstatSync;+ fs.lstatSync = function countingLstat(file, ...rest) { stats.push(file); return original.call(this, file, ...rest); };+ let tree;+ try { tree = listTree(dir); } finally { fs.lstatSync = original; }++ assert.equal(tree.lines.length, MAX_LISTING_ENTRIES);+ assert.equal(tree.truncated, true);+ assert.ok(stats.length <= MAX_LISTING_ENTRIES, `${stats.length} files examined for a listing of ${MAX_LISTING_ENTRIES}`);+ if (linkMade) {+ assert.equal(tree.lines[0], 'aaa-link -> link', 'a link is named, not followed');+ assert.equal(tree.lines.some((line) => line.includes('inside-the-link')), false);+ } else {+ t.diagnostic('links could not be created here; the link case is not exercised');+ }++ const header = describeBuildFailure(new Error('x'), [{ label: 'scenario workspace', dir }]).split('\n').find((line) => line.startsWith('scenario workspace:'));+ assert.ok(header.includes(`(${MAX_LISTING_ENTRIES} entries listed; more exist, the listing stops at`), header);+});++test('build failure diagnostics: the walk goes no deeper than its depth budget', () => {+ const nested = Array.from({ length: MAX_DEPTH + 3 }, (_, i) => `d${i}`).join('/');+ const dir = workspaceWith({ [`${nested}/deep.txt`]: 'x' });+ const tree = listTree(dir);+ assert.equal(tree.truncated, true);+ assert.equal(tree.lines.length, MAX_DEPTH, 'one folder per level, and nothing below the last');+ assert.equal(tree.lines.some((line) => line.includes('deep.txt')), false);+});++test('build failure diagnostics: a credential quoted by a cause is masked, and a frozen or non-Error value is handled', () => {+ const secret = 'abcdefghijklmnop0123456789';+ const dir = workspaceWith({ 'a.json': '{}' });+ const error = new Error('request failed', { cause: new Error(`Authorization: Bearer ${secret} was refused`) });+ recordBuildFailure(error, [{ label: 'scenario workspace', dir }]);+ assert.equal(error.buildFailureDiagnostics.includes(secret), false, error.buildFailureDiagnostics);+ assert.ok(error.buildFailureDiagnostics.includes('Bearer ****'));++ const loop = new Error('outer');+ const inner = new Error('inner', { cause: loop });+ loop.cause = inner;+ assert.equal((describeBuildFailure(loop, []).match(/\[\d\] /g) || []).length, 2, 'each error of a cause loop is described once');++ const frozen = Object.freeze(new Error('frozen'));+ assert.equal(recordBuildFailure(frozen, []), frozen);+ assert.equal(frozen.message, 'frozen');+ assert.equal(recordBuildFailure('refused', []), 'refused');+ assert.equal(recordBuildFailure(undefined, []), undefined);+ discard();+});diff --git a/plugins/model-apps/scripts/tests/build-lease-real-bundle.test.js b/plugins/model-apps/scripts/tests/build-lease-real-bundle.test.jsindex 34298ab98..8cf0282a0 100644--- a/plugins/model-apps/scripts/tests/build-lease-real-bundle.test.js+++ b/plugins/model-apps/scripts/tests/build-lease-real-bundle.test.js@@ -211,10 +211,13 @@ const ALONE = {'POST /webresourceset': 2,},rebuild: {- 'GET /appmodulecomponents': 19,+ // The rebuild's app update re-adds the app's components unpublished; before that action the bundled SDK reads the app row's token+ // (+1 GET /appmodules()) and, as it matches the one it holds, the app's current layer (+1 RetrieveUnpublishedMultiple) and that+ // layer's components (+1 GET /appmodulecomponents). Every component is there, so the action is sent as before: no write changes.+ 'GET /appmodulecomponents': 20,'GET /appmodules': 6,- 'GET /appmodules()': 6,- 'GET /appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()': 22,+ 'GET /appmodules()': 7,+ 'GET /appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()': 23,'GET /EntityDefinitions': 1,'GET /EntityDefinitions()': 10,'GET /EntityDefinitions()/Attributes': 2,diff --git a/plugins/model-apps/scripts/tests/business-rules.test.js b/plugins/model-apps/scripts/tests/business-rules.test.jsindex 3897a73fc..8e25a6a70 100644--- a/plugins/model-apps/scripts/tests/business-rules.test.js+++ b/plugins/model-apps/scripts/tests/business-rules.test.js@@ -203,6 +203,56 @@ test('REAL BUNDLE: the mapped rule reaches the wire as WfomJson naming the authoassert.match(wfom, /new_ticket/, 'the rule is bound to the authored table');});+// REAL BUNDLES: a rule the PREVIOUS release's SDK created leaves its copy, stamped with its older projection, in the workspace. A rule+// that exists is never fetched or pushed again by a build (sdk-build.js: it is reused, and only its state is set, by a record update),+// so that copy is never refused; what this release's SDK does on that same workspace is create the next rule — and it does so exactly+// as on a workspace it wrote, sending nothing for the old rule.+const { skipWithoutPrevious, requirePrevious } = require('./helpers/previous-bundle.js');+test('REAL BUNDLES: on a workspace holding a rule the previous release created, this release creates the next rule as on its own', { skip: skipWithoutPrevious() }, async () => {+ const run = async (creatorBundle) => {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'br-upgrade-'));+ dirs.push(dir);+ const calls = [];+ let n = 0;+ const httpClient = {+ get: async () => ({ status: 200, headers: {}, body: { value: [] } }),+ post: async (url, body) => {+ calls.push({ url: String(url), body });+ n += 1;+ return { status: 204, headers: { 'odata-entityid': `https://x/workflows(5555555${n}-5555-5555-5555-555555555555)` }, body: {} };+ },+ patch: async (url, body) => { calls.push({ url: String(url), body }); return { status: 204, headers: {}, body: {} }; },+ put: async () => ({ status: 204, headers: {}, body: {} }),+ delete: async () => ({ status: 204, headers: {}, body: {} }),+ };+ const open = async (bundle) => {+ const sdk = bundle.createMakerSdk({ workspaceStorage: bundle.createNodeWorkspaceStorage(dir), instanceUrl: 'https://contoso.crm.dynamics.com', httpClient });+ await sdk.initWorkspace();+ return sdk;+ };+ const author = async (sdk, rule) => {+ const def = businessRuleDef(rule);+ const art = await sdk.createArtifact('businessRule', def);+ await sdk.updateElement('businessRule', art.id, '/rootCondition', def.rootCondition);+ return sdk.pushArtifact('businessRule', art.id);+ };+ const first = await author(await open(creatorBundle), RULE);+ assert.strictEqual(first.saved, true);+ calls.length = 0;+ const next = await author(await open(require(BUNDLE)), { ...RULE, name: 'Hide notes when closed' });+ return { saved: next.saved, wire: calls.map((c) => ({ url: c.url, body: c.body })) };+ };+ const upgrade = await run(requirePrevious());+ const control = await run(require(BUNDLE));+ assert.strictEqual(upgrade.saved, true);+ // The first rule was answered the id 55555551-…: nothing this release sends names it.+ assert.ok(upgrade.wire.every((w) => !w.url.includes('55555551-')), JSON.stringify(upgrade.wire.map((w) => w.url)));+ assert.match(upgrade.wire[0].url, /CreateProcessWithWfomJson/i);+ // The WfomJson carries ids the SDK mints at random; the rest is compared as it is.+ const norm = (wire) => JSON.stringify(wire).replace(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi, '<id>');+ assert.strictEqual(norm(upgrade.wire), norm(control.wire), 'the same request as on a workspace this release wrote');+});+test('REAL BUNDLE: a valueless operator emits a unary condition with the IsNull/NotNull opcode', async () => {// A presence operator has nothing to compare against, so the SDK must emit NO right-hand operand// and the dedicated opcode — not `Equals` against an empty string, which is a different question@@ -1231,3 +1281,420 @@ test('a failed solution add on the reuse path WARNS — it never fails an otherwassert.ok(warnings.some((w) => /could not be added to solution/.test(w)),`the operator must be told; got ${JSON.stringify(warnings)}`);});++// --- an environment whose bound member exists but is switched off ------------------------------------+//+// Measured on production-geo environments: the platform declares `CreateProcessWithWfomJson` and answers EVERY create, whatever the+// rule says (garbage content included), with+// HTTP 400 {"error":{"code":"0x80040216","message":"An unexpected error occurred."}}+// and nothing is created. The member-is-missing gate cannot see it (the member IS declared), so a build used to halt at this phase and+// leave an app built only up to it. The SDK throws that answer as+// Error 'HTTP 400 from <env>/api/data/v9.0/workflows(<null guid>)/Microsoft.Dynamics.CRM.CreateProcessWithWfomJson: <message>'+// { code: 'CONNECTION_ERROR', statusCode: 400, url, cause: <the response body> }+// and nothing in it names the gate. The FIRST create of a build answering exactly this is read as "not available here"; the same answer+// after a rule of this build was created, or any other failure, is not.+const MEMBER_URL = 'https://contoso.crm.dynamics.com/api/data/v9.0/workflows(00000000-0000-0000-0000-000000000000)/Microsoft.Dynamics.CRM.CreateProcessWithWfomJson';+const { HTTP_SEND_HISTORY } = require('../lib/sdk-http-client.js');+// `history` is what the plugin's HTTP client says of the sends that led to the answer (lib/sdk-http-client.js): the one send of a first attempt by default;+// null is an answer from a transport that says nothing.+function memberRefusal({ status = 400, code = '0x80040216', url = MEMBER_URL, message = 'An unexpected error occurred.', history = { sends: 1, earlierAmbiguous: false } } = {}) {+ const body = { error: { code, message } };+ if (history) Object.defineProperty(body, HTTP_SEND_HISTORY, { value: history, enumerable: false });+ return Object.assign(new Error(`HTTP ${status} from ${url}: ${message}`),+ { code: 'CONNECTION_ERROR', statusCode: status, url, cause: body });+}++// `answers[i]` is what the i-th push does: an Error is thrown, `'ok'` saves, anything else is returned as the push result.+function provisionPushing(answers) {+ const { provision, calls } = provisionThatCannotAuthorRules();+ let pushes = 0;+ provision.pushArtifact = async () => {+ const answer = answers[Math.min(pushes, answers.length - 1)];+ pushes += 1;+ calls.push(['pushArtifact']);+ if (answer instanceof Error) throw answer;+ if (answer === 'ok') return { id: `br-${pushes}`, saved: true, publish: { kind: 'notRequested' } };+ return answer;+ };+ return { provision, calls };+}+const threeRules = () => {+ const spec = ruleOnlySpec();+ spec.businessRules = [{ ...RULE, name: 'Rule A' }, { ...RULE, name: 'Rule B' }, { ...RULE, name: 'Rule C' }];+ return spec;+};++test('the first rule refused with HTTP 400 0x80040216 on the bound member SKIPS every rule and the build goes on', async () => {+ const { sdk } = require('./helpers/mock-sdk.js').makeSimpleMockSdk();+ const { provision, calls } = provisionPushing([memberRefusal()]);+ const warnings = [];+ const events = [];+ const spec = threeRules();+ const res = await runBuild(spec, {+ sdk, provisionSdk: provision, apply: true, phases: ['business-rules'], warn: (m) => warnings.push(m), emit: (e) => events.push(e),+ });+ assert.strictEqual(res.ok, true, 'the build must complete, exactly as for a missing member');++ // The refused create is the probe: the remaining rules are not sent.+ assert.strictEqual(calls.filter((c) => c[0] === 'pushArtifact').length, 1, 'only the first rule is sent');+ assert.strictEqual(calls.some((c) => c[0] === 'addSolutionComponent'), false);++ assert.strictEqual(warnings.length, 1, `exactly one warning for three rules; got ${JSON.stringify(warnings)}`);+ assert.match(warnings[0], /business rules were NOT created/);+ assert.match(warnings[0], /0x80040216/, 'name the code so it can be searched for');+ assert.match(warnings[0], /platform limit/);+ assert.match(warnings[0], /production environments/);+ assert.match(warnings[0], /Everything else in the app was built normally/);++ const skips = events.filter((e) => e.phase === 'business-rules' && e.status === 'skip');+ assert.strictEqual(skips.length, 3, `every rule is a skip; got ${JSON.stringify(events.map((e) => [e.status, e.label]))}`);+ for (const s of skips) assert.match(s.label, /unsupported in this environment/);+ assert.strictEqual(events.some((e) => e.phase === 'business-rules' && e.status === 'error'), false);++ assert.deepStrictEqual(res.skipped.businessRules, spec.businessRules.map((r) => `${r.entity.toLowerCase()}|${r.name}`));+ assert.strictEqual(Object.keys(res.created.businessRules).length, 0);+});++test('the same refusal reported BY VALUE (a saved:false result) skips too', async () => {+ const { sdk } = require('./helpers/mock-sdk.js').makeSimpleMockSdk();+ const { provision } = provisionPushing([+ { type: 'businessRule', id: 'br-new', saved: false, shipped: false, publish: { kind: 'notRequested' }, error: memberRefusal() },+ ]);+ const warnings = [];+ const res = await runBuild(ruleOnlySpec(), {+ sdk, provisionSdk: provision, apply: true, phases: ['business-rules'], warn: (m) => warnings.push(m),+ });+ assert.strictEqual(res.ok, true);+ assert.strictEqual(res.skipped.businessRules.length, 1);+ assert.strictEqual(warnings.length, 1);+});++test('REAL BUNDLE: the refusal the bundle throws for HTTP 400 0x80040216 skips the rules, and verify treats them as the missing-member gate does', async () => {+ const { createMakerSdk, createNodeWorkspaceStorage } = require(BUNDLE);+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'br-gate-'));+ dirs.push(dir);+ const memberPosts = [];+ // The plugin's own HTTP client over a fake transport: it is the one that tells the SDK's error what the sends before the answer were.+ const { createAzHttpClient } = require('../lib/sdk-http-client.js');+ const httpClient = createAzHttpClient('https://contoso.crm.dynamics.com', {+ getToken: () => 'TOK',+ sleep: async () => {},+ request: async ({ method, url }) => {+ if (method === 'POST' && /CreateProcessWithWfomJson/.test(String(url))) {+ memberPosts.push(String(url));+ return { statusCode: 400, headers: {}, body: JSON.stringify({ error: { code: '0x80040216', message: 'An unexpected error occurred.' } }) };+ }+ return { statusCode: method === 'GET' ? 200 : 204, headers: {}, body: JSON.stringify({ value: [] }) };+ },+ });+ const real = createMakerSdk({ workspaceStorage: createNodeWorkspaceStorage(dir), instanceUrl: 'https://contoso.crm.dynamics.com', httpClient });+ await real.initWorkspace();+ const { sdk } = require('./helpers/mock-sdk.js').makeSimpleMockSdk();+ // The reads (the rows already there) are the double's; what is under test is the real create, update and push of a rule.+ const { provision } = provisionWithRules([]);+ for (const method of ['createArtifact', 'updateElement', 'pushArtifact']) provision[method] = (...args) => real[method](...args);+ const warnings = [];+ const res = await runBuild(threeRules(), {+ sdk, provisionSdk: provision, apply: true, phases: ['business-rules'], warn: (m) => warnings.push(m),+ });+ assert.strictEqual(res.ok, true);+ assert.strictEqual(memberPosts.length, 1, 'the member is asked once; the other two rules are not sent');+ assert.strictEqual(res.skipped.businessRules.length, 3);+ assert.strictEqual(warnings.length, 1);+ assert.match(warnings[0], /0x80040216/);++ const r = await verifySpec(ruleSpec(), baseReader([]), { environmentSkipped: { businessRules: [`new_ticket|Lock when closed`] } });+ assert.strictEqual(ruleCheck(r), undefined, 'a skipped rule is not demanded by verify');+ assert.deepStrictEqual(r.environmentSkipped, ['business-rule:new_ticket.Lock when closed']);+});++test('a refusal that is NOT this one still HALTS: another code, another status, another member', async () => {+ const { sdk } = require('./helpers/mock-sdk.js').makeSimpleMockSdk();+ const refusals = [+ memberRefusal({ code: '0x80040265' }),+ memberRefusal({ status: 500 }),+ memberRefusal({ status: 403, code: '0x80040220' }),+ memberRefusal({ url: 'https://contoso.crm.dynamics.com/api/data/v9.0/workflows' }),+ Object.assign(new Error('HTTP 400 from the bound member'), { code: 'CONNECTION_ERROR', statusCode: 400, url: MEMBER_URL }),+ ];+ for (const refusal of refusals) {+ const { provision } = provisionPushing([refusal]);+ const warnings = [];+ await assert.rejects(+ () => runBuild(ruleOnlySpec(), { sdk, provisionSdk: provision, apply: true, phases: ['business-rules'], warn: (m) => warnings.push(m) }),+ `${refusal.message} (${refusal.statusCode}) must still halt the build`);+ assert.strictEqual(warnings.length, 0, 'a halt is not announced as an environment limit');+ }+});++test('the same refusal AFTER a rule of this build was created still HALTS', async () => {+ // The environment hosted the first rule, so the refusal of the second is not "rules are switched off here".+ const { sdk } = require('./helpers/mock-sdk.js').makeSimpleMockSdk();+ const { provision, calls } = provisionPushing(['ok', memberRefusal()]);+ const warnings = [];+ const events = [];+ const err = await runBuild(threeRules(), {+ sdk, provisionSdk: provision, apply: true, phases: ['business-rules'], warn: (m) => warnings.push(m), emit: (e) => events.push(e),+ }).then(() => null, (e) => e);+ assert.ok(err, 'the build halts');+ assert.match(err.message, /business-rules failed/);+ assert.strictEqual(calls.filter((c) => c[0] === 'pushArtifact').length, 2, 'the third rule is not tried');+ assert.strictEqual(warnings.length, 0);+ assert.strictEqual(events.some((e) => e.phase === 'business-rules' && e.status === 'skip'), false);+});++test('a rule that already exists is reused, not counted as a create: a refusal of the next rule is still the first create of the build', async () => {+ const { sdk } = require('./helpers/mock-sdk.js').makeSimpleMockSdk();+ const { provision } = provisionPushing([memberRefusal()]);+ const queryRecords = provision.queryRecords;+ provision.queryRecords = async (entity, opts) => (entity === 'workflow' && /Rule A/.test(JSON.stringify(opts.filter))+ ? [{ workflowid: 'existing-a', statecode: 1, createdon: '2026-01-01T00:00:00Z' }]+ : queryRecords(entity, opts));+ const res = await runBuild(threeRules(), {+ sdk, provisionSdk: provision, apply: true, phases: ['business-rules'], warn: () => {},+ });+ assert.strictEqual(res.ok, true);+ assert.strictEqual(res.created.businessRules['new_ticket|Rule A'], 'existing-a');+ assert.deepStrictEqual(res.skipped.businessRules, ['new_ticket|Rule B', 'new_ticket|Rule C']);+});++// --- the same 400 from a create the platform SAVED and then failed to finish (#482) ------------------------------------+//+// The workflow row commits, then generating its UiData faults, and the member answers the very same HTTP 400 0x80040216 (measured as live,+// firing rows; pinned in sdk-uptake-contract.test.js). So the answer alone never proves nothing was written: only a fresh, complete read of+// the rule's definitions that finds none the before-create snapshot lacked lets the build call rules unavailable here.+function provisionRefusedThenRead({ before = async () => [], readAfter }) {+ const { provision, calls } = provisionPushing([memberRefusal()]);+ let pushed = false;+ const push = provision.pushArtifact;+ provision.pushArtifact = async (...args) => { pushed = true; return push(...args); };+ provision.queryRecords = async (entity, opts) => {+ if (entity !== 'workflow') return entity === 'solution' ? [] : [{ publisherid: 'pub-1' }];+ calls.push([pushed ? 'readAfter' : 'readBefore', opts.select]);+ return pushed ? readAfter() : before(opts);+ };+ return { provision, calls };+}++test('the switched-off answer to a create the platform SAVED anyway is not the gate: the build halts and names the new rule row', async () => {+ const { sdk } = require('./helpers/mock-sdk.js').makeSimpleMockSdk();+ const { provision, calls } = provisionRefusedThenRead({ readAfter: async () => [{ workflowid: 'saved-row-1' }] });+ const warnings = [];+ const events = [];+ const err = await runBuild(threeRules(), {+ sdk, provisionSdk: provision, apply: true, phases: ['business-rules'], warn: (m) => warnings.push(m), emit: (e) => events.push(e),+ }).then(() => null, (e) => e);+ assert.ok(err, 'the build halts, as it did before the gate existed');+ assert.match(err.message, /business-rules failed/);+ assert.strictEqual(calls.filter((c) => c[0] === 'pushArtifact').length, 1, 'no other rule is sent');+ assert.strictEqual(calls.filter((c) => c[0] === 'readAfter').length, 1, 'one read after the refusal');+ assert.strictEqual(warnings.some((w) => /NOT created|platform limit/.test(w)), false, 'nothing is called a platform limit');+ assert.strictEqual(warnings.length, 1, `one warning naming the row; got ${JSON.stringify(warnings)}`);+ assert.match(warnings[0], /saved-row-1/);+ assert.match(warnings[0], /Either the platform saved this create and then failed to finish it, or something else added that rule meanwhile/);+ assert.doesNotMatch(warnings[0], /business rules ARE available/i, 'the new row is not attributed to this create: another writer can add it meanwhile');+ assert.strictEqual(events.some((e) => e.phase === 'business-rules' && e.status === 'skip'), false);+});++test('a read after the switched-off answer that fails or is unreadable proves nothing: the build halts', async () => {+ const reads = [async () => { throw new Error('HTTP 503 from workflows'); }, async () => [{ workflowid: '' }], async () => null];+ for (const readAfter of reads) {+ const { sdk } = require('./helpers/mock-sdk.js').makeSimpleMockSdk();+ const { provision } = provisionRefusedThenRead({ readAfter });+ const warnings = [];+ const err = await runBuild(ruleOnlySpec(), {+ sdk, provisionSdk: provision, apply: true, phases: ['business-rules'], warn: (m) => warnings.push(m),+ }).then(() => null, (e) => e);+ assert.ok(err, 'the build halts');+ assert.strictEqual(warnings.some((w) => /NOT created/.test(w)), false);+ assert.match(warnings.join('\n'), /failed|unreadable id set/);+ }+});++test('the switched-off answer with the rule\'s definitions unchanged skips: a row already in the snapshot is not counted as created', async () => {+ // The first workflow read (does the rule exist?) finds nothing; a row then appears before the push (another writer), so the+ // before-create snapshot holds it, and the read after the refusal finds the same row and nothing else.+ const { sdk } = require('./helpers/mock-sdk.js').makeSimpleMockSdk();+ let beforeReads = 0;+ const { provision, calls } = provisionRefusedThenRead({+ before: async () => { beforeReads += 1; return beforeReads === 1 ? [] : [{ workflowid: 'Concurrent-1' }]; },+ readAfter: async () => [{ workflowid: 'concurrent-1' }],+ });+ const warnings = [];+ const res = await runBuild(ruleOnlySpec(), {+ sdk, provisionSdk: provision, apply: true, phases: ['business-rules'], warn: (m) => warnings.push(m),+ });+ assert.strictEqual(res.ok, true);+ assert.strictEqual(res.skipped.businessRules.length, 1);+ assert.strictEqual(calls.filter((c) => c[0] === 'readAfter').length, 1);+ assert.strictEqual(warnings.filter((w) => /business rules were NOT created/.test(w)).length, 1);+});++test('only the answer the gate could accept is followed by a read: another refusal halts without one', async () => {+ const { sdk } = require('./helpers/mock-sdk.js').makeSimpleMockSdk();+ const { provision, calls } = provisionPushing([memberRefusal({ code: '0x80040265' })]);+ await assert.rejects(() => runBuild(ruleOnlySpec(), { sdk, provisionSdk: provision, apply: true, phases: ['business-rules'], warn: () => {} }));+ assert.strictEqual(calls.filter((c) => c[0] === 'queryRecords').length, 2, 'the existence read and the before-create snapshot, no read after the refusal');+});++// --- a refusal is the gate only when it is the definitive answer to the first send of the create ------------------------------------+//+// The first member create answers 503 from a gateway that may sit in front of a create that ran; the plugin's HTTP client sends it again; the second answer+// is the 400. That 400 says nothing of the first send, so "rules are switched off here" would hide a rule that may exist and say none was created.+// The history of the sends comes from the plugin's own HTTP client (lib/sdk-http-client.js), and is checked WITHOUT relying on anything else sending the create once.+const LATER_PHASES = ['business-rules', 'dashboards', 'app-shell'];+async function buildThroughAdapter(answerMember, spec = threeRules(), workflowRows = () => []) {+ const { createMakerSdk, createNodeWorkspaceStorage } = require(BUNDLE);+ const { createAzHttpClient } = require('../lib/sdk-http-client.js');+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'br-hist-'));+ dirs.push(dir);+ const memberPosts = [];+ const httpClient = createAzHttpClient('https://contoso.crm.dynamics.com', {+ getToken: () => 'TOK',+ sleep: async () => {},+ request: async ({ method, url }) => {+ if (method === 'POST' && /\/Microsoft\.Dynamics\.CRM\.CreateProcessWithWfomJson$/.test(String(url))) {+ memberPosts.push(String(url));+ return answerMember(memberPosts.length);+ }+ return { statusCode: method === 'GET' ? 200 : 204, headers: {}, body: JSON.stringify({ value: [] }) };+ },+ });+ const real = createMakerSdk({ workspaceStorage: createNodeWorkspaceStorage(dir), instanceUrl: 'https://contoso.crm.dynamics.com', httpClient });+ await real.initWorkspace();+ const { sdk } = require('./helpers/mock-sdk.js').makeSimpleMockSdk();+ // The mock SDK serves every other phase; the rows already there and the create, update and push of a rule are the ones under test.+ const initialQuery = sdk.queryRecords;+ const provision = { ...sdk, queryRecords: async (entity, opts) => (entity === 'workflow' ? workflowRows(memberPosts.length) : initialQuery(entity, opts)) };+ for (const method of ['createArtifact', 'updateElement', 'pushArtifact']) {+ const original = provision[method];+ provision[method] = (...args) => (args[0] === 'businessRule' ? real[method](...args) : original(...args));+ }+ const warnings = [];+ const events = [];+ const outcome = await runBuild({ ...spec, dashboards: [{ name: 'Later dashboard', tiles: [] }] }, {+ sdk, provisionSdk: provision, apply: true, phases: LATER_PHASES, warn: (m) => warnings.push(m), emit: (e) => events.push(e),+ }).then((res) => ({ res }), (err) => ({ err }));+ const phasesRun = [...new Set(events.filter((e) => e.status === 'ok').map((e) => e.phase))];+ return { ...outcome, memberPosts, warnings, events, phasesRun };+}+const REFUSED_ANSWER = { statusCode: 400, headers: {}, body: JSON.stringify({ error: { code: '0x80040216', message: 'An unexpected error occurred.' } }) };+const GATEWAY_ANSWER = { statusCode: 503, headers: {}, body: JSON.stringify({ error: { code: 'upstream', message: 'Gateway failed after dispatch' } }) };++test('REAL BUNDLE + plugin HTTP client: a definitive refusal of the first send skips the rules and the later phases run', async () => {+ const r = await buildThroughAdapter(() => REFUSED_ANSWER);+ assert.ok(r.res, `the build completes; got ${r.err && r.err.message}`);+ assert.strictEqual(r.memberPosts.length, 1);+ assert.strictEqual(r.res.skipped.businessRules.length, 3);+ assert.strictEqual(r.warnings.filter((w) => /business rules were NOT created/.test(w)).length, 1);+ assert.ok(r.phasesRun.includes('dashboards') && r.phasesRun.includes('app-shell'), `the phases after business-rules run; got ${JSON.stringify(r.phasesRun)}`);+});++test('REAL BUNDLE + plugin HTTP client: the switched-off answer to a create the platform saved anyway halts and names the row', async () => {+ const r = await buildThroughAdapter(() => REFUSED_ANSWER, threeRules(), (posts) => (posts > 0 ? [{ workflowid: 'saved-by-the-platform' }] : []));+ assert.ok(r.err, 'the build halts');+ assert.strictEqual(r.memberPosts.length, 1);+ assert.strictEqual(r.warnings.some((w) => /NOT created|platform limit/.test(w)), false);+ assert.match(r.warnings.join('\n'), /saved-by-the-platform/);+ assert.deepStrictEqual(r.phasesRun.filter((p) => p !== 'business-rules'), [], 'no later phase runs');+});++test('REAL BUNDLE + plugin HTTP client: a 503 sent again and then refused is NOT the gate — the build halts and nothing is called a limit', async () => {+ const r = await buildThroughAdapter((n) => (n === 1 ? GATEWAY_ANSWER : REFUSED_ANSWER));+ assert.ok(r.err, 'the build halts, as it did before the gate existed');+ assert.match(r.err.message, /business-rules failed/);+ assert.strictEqual(r.memberPosts.length, 2, 'the client sent it twice: the first send may have run');+ assert.strictEqual(r.warnings.some((w) => /NOT created|platform limit/.test(w)), false, 'no claim that nothing was created');+ assert.strictEqual(r.events.some((e) => e.phase === 'business-rules' && e.status === 'skip'), false);+ assert.deepStrictEqual(r.phasesRun.filter((p) => p !== 'business-rules'), [], 'no later phase runs');+});++test('REAL BUNDLE + plugin HTTP client: a send that got no answer, sent again and then refused, is NOT the gate either', async () => {+ const r = await buildThroughAdapter((n) => (n === 1 ? { error: 'socket hang up', code: 'ECONNRESET' } : REFUSED_ANSWER));+ assert.ok(r.err);+ assert.strictEqual(r.warnings.some((w) => /NOT created/.test(w)), false);+});++test('an unknown or partial outcome anywhere in the chain wins over a refusal inside it: thrown and by-value, and it still says it is unknown', async () => {+ const { sdk } = require('./helpers/mock-sdk.js').makeSimpleMockSdk();+ const wrappers = [+ ['an outcome flag', () => Object.assign(new Error('The create outcome is unknown; do not assume nothing was written.'), { code: 'create-outcome-unknown', transient: false, outcome: 'unknown', cause: memberRefusal() })],+ ['an outcome flag alone', () => Object.assign(new Error('not sure what the create did'), { outcome: 'unknown', cause: memberRefusal() })],+ ['a code naming an unknown outcome', () => Object.assign(new Error('the row MAY have been written'), { code: 'UPSERT_OUTCOME_UNKNOWN', cause: memberRefusal() })],+ ['an earlier gateway answer in the chain', () => Object.assign(new Error('gateway'), { code: 'CONNECTION_ERROR', statusCode: 503, cause: memberRefusal() })],+ ['a send that got no answer in the chain', () => Object.assign(new Error('Request failed'), { code: 'CONNECTION_ERROR', statusCode: 0, cause: memberRefusal() })],+ ];+ for (const [what, make] of wrappers) {+ for (const byValue of [false, true]) {+ const { provision } = provisionPushing([byValue+ ? { type: 'businessRule', id: 'br-new', saved: false, shipped: false, publish: { kind: 'notRequested' }, error: make() }+ : make()]);+ const warnings = [];+ const events = [];+ const err = await runBuild(threeRules(), {+ sdk, provisionSdk: provision, apply: true, phases: ['business-rules'], warn: (m) => warnings.push(m), emit: (e) => events.push(e),+ }).then(() => null, (e) => e);+ assert.ok(err, `${what}${byValue ? ' (by value)' : ''} must halt`);+ assert.strictEqual(warnings.length, 0, `${what}: no environment warning`);+ assert.strictEqual(events.some((e) => e.status === 'skip'), false, `${what}: no skip`);+ }+ }+ const { provision } = provisionPushing([wrappers[0][1]()]);+ const err = await runBuild(ruleOnlySpec(), { sdk, provisionSdk: provision, apply: true, phases: ['business-rules'], warn: () => {} }).then(() => null, (e) => e);+ assert.match(err.message, /outcome is unknown/, 'the halt keeps the words that say the outcome is unknown');+});++test('a plain wrapper around the confirmed refusal — nothing that says unknown — still skips', async () => {+ // requireSuccessfulPush's BuildHalt is the by-value case above; a plain Error around the SDK's error is the same kind of wrapper.+ const { sdk } = require('./helpers/mock-sdk.js').makeSimpleMockSdk();+ const { provision } = provisionPushing([Object.assign(new Error('push business rule Rule A failed'), { cause: memberRefusal() })]);+ const res = await runBuild(ruleOnlySpec(), { sdk, provisionSdk: provision, apply: true, phases: ['business-rules'], warn: () => {} });+ assert.strictEqual(res.skipped.businessRules.length, 1);+});++test('a refusal from a transport that reports no send history is not confirmed, so it halts', async () => {+ const { sdk } = require('./helpers/mock-sdk.js').makeSimpleMockSdk();+ const { provision } = provisionPushing([memberRefusal({ history: null })]);+ await assert.rejects(() => runBuild(ruleOnlySpec(), { sdk, provisionSdk: provision, apply: true, phases: ['business-rules'], warn: () => {} }));+});++test('a refusal whose earlier send was ambiguous halts even when it is the only send of its own call', async () => {+ // The SDK can call a request again itself: the history then comes from the client's ledger, not from this call's loop.+ const { sdk } = require('./helpers/mock-sdk.js').makeSimpleMockSdk();+ const { provision } = provisionPushing([memberRefusal({ history: { sends: 1, earlierAmbiguous: true } })]);+ await assert.rejects(() => runBuild(ruleOnlySpec(), { sdk, provisionSdk: provision, apply: true, phases: ['business-rules'], warn: () => {} }));+});++test('only the member itself is the gate: a failed read whose URL merely QUOTES the member is not', async () => {+ // A rule named like the member puts the member's name into the query of the read before its create. Judged by the request, that read is not the create.+ const { sdk } = require('./helpers/mock-sdk.js').makeSimpleMockSdk();+ const quoted = `https://contoso.crm.dynamics.com/api/data/v9.0/workflows?$filter=name%20eq%20'Microsoft.Dynamics.CRM.CreateProcessWithWfomJson'`;+ const lookalikes = [+ quoted,+ `${MEMBER_URL}2`,+ 'https://contoso.crm.dynamics.com/api/data/v9.0/workflows(00000000-0000-0000-0000-000000000000)/Xmicrosoft.Dynamics.CRM.CreateProcessWithWfomJson',+ 'https://contoso.crm.dynamics.com/api/data/v9.0/workflows(00000000-0000-0000-0000-000000000000)/Microsoft.Dynamics.CRM.UpdateProcessWithWfomJson?x=CreateProcessWithWfomJson',+ ];+ for (const url of lookalikes) {+ const { provision } = provisionPushing([memberRefusal({ url })]);+ const warnings = [];+ await assert.rejects(+ () => runBuild(ruleOnlySpec(), { sdk, provisionSdk: provision, apply: true, phases: ['business-rules'], warn: (m) => warnings.push(m) }),+ `${url} is not the member`);+ assert.strictEqual(warnings.length, 0);+ }+ // The same refusal raised by the read before the create (the one that really carries the quoted name) halts as well.+ const { provision } = provisionPushing(['ok']);+ const queryRecords = provision.queryRecords;+ let reads = 0;+ provision.queryRecords = async (entity, opts) => {+ if (entity === 'workflow') { reads += 1; if (reads === 2) throw memberRefusal({ url: quoted }); }+ return queryRecords(entity, opts);+ };+ const spec = ruleOnlySpec();+ spec.businessRules[0].name = 'Microsoft.Dynamics.CRM.CreateProcessWithWfomJson';+ const warnings = [];+ const err = await runBuild(spec, { sdk, provisionSdk: provision, apply: true, phases: ['business-rules'], warn: (m) => warnings.push(m) }).then(() => null, (e) => e);+ assert.ok(err, 'a failed read is not a refused create');+ assert.strictEqual(warnings.length, 0);+});diff --git a/plugins/model-apps/scripts/tests/check-auth.test.js b/plugins/model-apps/scripts/tests/check-auth.test.jsindex 7f322f2db..7131bec5d 100644--- a/plugins/model-apps/scripts/tests/check-auth.test.js+++ b/plugins/model-apps/scripts/tests/check-auth.test.js@@ -19,6 +19,7 @@ test('check-auth.js enumerates all blocker codes', () => {'whoami_403','whoami_401','whoami_error',+ 'no_customization_role',]) {assert.match(scriptSrc, new RegExp(`['"]${code}['"]`), `missing blocker code: ${code}`);}@@ -119,6 +120,8 @@ test('check-auth.js: 403 hint mentions az login --username when identities diffeconst { loadCli } = require('./helpers/cli-harness.js');const ENVURL = 'https://contoso.crm.dynamics.com';+// The one GET sent after a passing WhoAmI: the first read the build makes (its solution), as the capability probe.+const PROBE_REQUEST = 'GET solutions?$select=solutionid&$top=1';// runQuiet() shells out via execFileSync and treats a throw as "absent". These stubs therefore// model each CLI as either returning stdout or throwing, exactly as a missing binary would — and a@@ -241,7 +244,7 @@ function makeCancelableExecFile({ pacOrg = null, azUser = '[email protected]', a};}-async function run({ argv = [], exec = {}, whoAmI, whoAmIThrows, tokenFailure = null }) {+async function run({ argv = [], exec = {}, whoAmI, whoAmIThrows, tokenFailure = null, probe, probeThrows }) {const calls = [];// The token read is an `az` call too: with the Azure CLI missing or logged out it fails, as it would live.const azUnusable = exec.azVersion === null || exec.azUser === null || (exec.notOnPath || []).includes('az');@@ -264,7 +267,13 @@ async function run({ argv = [], exec = {}, whoAmI, whoAmIThrows, tokenFailure =},tokenFailureKind: () => tokenFailure,tokenFailureMessage: (url, fallback) => (tokenFailure === 'timeout' ? `token for ${url} timed out` : fallback),- dataverseRequest: async () => {+ dataverseRequest: async (url, method, requestPath) => {+ // WhoAmI is the identity test; any other request is the capability probe that follows a passing WhoAmI.+ if (requestPath !== 'WhoAmI') {+ calls.push(`${method} ${requestPath}`);+ if (probeThrows) throw new Error(probeThrows);+ return probe || { status: 200, data: { value: [] } };+ }calls.push('whoami');if (whoAmIThrows) throw new Error(whoAmIThrows);return whoAmI || { status: 200, data: { UserId: 'u-1', OrganizationId: 'o-1' } };@@ -304,7 +313,11 @@ async function runWithAsyncChildren({ argv = [], exec = {}, token, whoAmI } = {}},tokenFailureKind: () => null,tokenFailureMessage: (url, fallback) => fallback,- dataverseRequest: async () => {+ dataverseRequest: async (url, method, requestPath) => {+ if (requestPath !== 'WhoAmI') {+ calls.push(`${method} ${requestPath}`);+ return { status: 200, data: { value: [] } };+ }calls.push('whoami');return whoAmI || { status: 200, data: { UserId: 'u-1', OrganizationId: 'o-1' } };},@@ -428,6 +441,7 @@ test('pac org who starts before the az probes, and the WhoAmI token is warmed wh`token ${ENVURL}`,'whoami','done pac',+ PROBE_REQUEST,]);});@@ -629,6 +643,85 @@ test('a clean run reports ok with the WhoAmI identity ids', async () => {assert.match(r.message, /Ready \(az \+ pac both signed in/);});+// --- an identity that passes WhoAmI but holds no security role ---------------------------------------+//+// WhoAmI answers for any user the environment knows, role or not, so it said "ready" for an identity whose every customization+// read then fails:+// GET solutions?$select=solutionid&$top=1 -> HTTP 403+// {"error":{"code":"0x80042f09","message":"The user with id <id> has not been assigned any roles. They need a role with the prvReadCustomization privilege."}}+// (measured on an environment where the signed-in user had no role: `solutions`, `sitemaps`, `roles` and `publishers` all answered it).+// The probe is one customization read the build itself starts with. A role COUNT would be wrong: privileges also come through teams.+const NO_ROLE = { status: 403, data: { error: { code: '0x80042f09', message: 'The user with id 00000000-0000-0000-0000-000000000000 has not been assigned any roles. They need a role with the prvReadCustomization privilege.' } } };++test('an identity that passes WhoAmI but holds no security role is NOT ok, and the message says what to do', async () => {+ const r = await run({ argv: ['--env', ENVURL], exec: { pacOrg: 'Connected as [email protected]\n' }, probe: NO_ROLE });+ assert.equal(r.ok, false);+ assert.equal(r.blocker, 'no_customization_role');+ assert.match(r.message, /maker@contoso\.com/, 'names the identity');+ assert.match(r.message, /no security role/);+ assert.match(r.message, /System Customizer/, 'names a role that fixes it');+ assert.doesNotMatch(r.message, /az login/, 'the same identity in pac is no other identity to sign in as');+ assert.equal(r.azUser, '[email protected]');+ assert.equal(r.envUrl, ENVURL);+ assert.equal(r.whoAmI.ok, true, 'WhoAmI itself passed, and the result still says so');+});++test('with another identity in pac the role-less message offers it', async () => {+ const r = await run({ argv: ['--env', ENVURL], exec: { azUser: '[email protected]', pacOrg: 'Connected as [email protected]\n' }, probe: NO_ROLE });+ assert.equal(r.blocker, 'no_customization_role');+ assert.match(r.message, /dev@contoso\.com/);+ assert.match(r.message, /az login --username maker@contoso\.com/);+});++test('the role-less verdict reads the code in any case, and still says to ask for a role when pac is not signed in', async () => {+ const r = await run({+ argv: ['--env', ENVURL],+ probe: { status: 403, data: { error: { code: '0X80042F09', message: 'Der Benutzer hat keine Rolle.' } } },+ });+ assert.equal(r.ok, false, 'the code decides, not the words: the platform answers in the caller\'s language');+ assert.equal(r.blocker, 'no_customization_role');+ assert.match(r.message, /System Customizer/);+});++test('a role-holder is unchanged: one extra GET, the same ok result and no new warning', async () => {+ const r = await run({ argv: ['--env', ENVURL], exec: { pacOrg: 'Connected as [email protected]\n' } });+ assert.equal(r.ok, true);+ assert.equal(r.blocker, null);+ assert.deepEqual(r.warnings, []);+ assert.deepEqual(r.calls.filter((c) => c.startsWith('GET ')), [PROBE_REQUEST], 'exactly one GET is added, and it is the probe');+ assert.deepEqual(r.calls.filter((c) => c === 'whoami').length, 1);+ assert.match(r.message, /^Ready \(az \+ pac both signed in as maker@contoso\.com/);+});++test('any OTHER failure of the probe is a warning, never a false "no role"', async () => {+ const others = [+ ['another 403 code', { probe: { status: 403, data: { error: { code: '0x80040220', message: 'privilege missing' } } } }],+ ['a 403 with no body', { probe: { status: 403, data: {} } }],+ ['an HTTP 500', { probe: { status: 500, data: { error: { code: '0x80040216', message: 'An unexpected error occurred.' } } } }],+ ['an HTTP 429', { probe: { status: 429, data: {} } }],+ ['a transport failure', { probeThrows: 'getaddrinfo ENOTFOUND' }],+ ];+ for (const [what, extra] of others) {+ const r = await run({ argv: ['--env', ENVURL], exec: { pacOrg: 'Connected as [email protected]\n' }, ...extra });+ assert.equal(r.ok, true, `${what} must not block`);+ assert.equal(r.blocker, null, what);+ assert.equal(r.warnings.length, 1, `${what} is reported once as a warning; got ${JSON.stringify(r.warnings)}`);+ assert.match(r.warnings[0], /could not confirm/i, what);+ }+});++test('the probe is sent only after WhoAmI passed', async () => {+ for (const whoAmI of [{ status: 401, data: {} }, { status: 403, data: {} }, { status: 500, data: {} }]) {+ const r = await run({ argv: ['--env', ENVURL], whoAmI, probe: NO_ROLE });+ assert.equal(r.ok, false);+ assert.notEqual(r.blocker, 'no_customization_role', `WhoAmI ${whoAmI.status} keeps its own verdict`);+ assert.equal(r.calls.some((c) => c === PROBE_REQUEST), false, `no probe after a WhoAmI ${whoAmI.status}`);+ }+ const thrown = await run({ argv: ['--env', ENVURL], whoAmIThrows: 'getaddrinfo ENOTFOUND', probe: NO_ROLE });+ assert.equal(thrown.blocker, 'whoami_error');+ assert.equal(thrown.calls.some((c) => c === PROBE_REQUEST), false);+});+test('a mismatched-but-working identity is reported as ready WITH the caveat', async () => {// WhoAmI passed, so this is not a blocker — but entity creation can still 403 later, and the// message has to carry that forward or the user has no way to connect the two events.@@ -693,15 +786,19 @@ function runGated({ argv = ['--env', ENVURL], requirePac = false, tokenKind = nutokenFailureKind: () => tokenKind,tokenFailureMessage: (url, fallback) => (tokenKind === 'timeout' ? `token for ${url} timed out` : fallback),// `whoAmIRequest(events)` swaps in a different WhoAmI (the real dataverseRequest over a stub transport, say);- // by default WhoAmI is a gate the test opens by hand.- dataverseRequest: whoAmIRequest ? whoAmIRequest(events) : () => {- events.push('start whoami');- return gates.who.promise.then((value) => {- events.push('whoami answered');- if (value instanceof Error) throw value;- return value;- });- },+ // by default WhoAmI is a gate the test opens by hand. The capability probe that follows a passing WhoAmI is a role-holder's+ // 200 here, and leaves no event: these tests are about when WhoAmI starts and what it may refresh.+ dataverseRequest: (() => {+ const whoAmI = whoAmIRequest ? whoAmIRequest(events) : () => {+ events.push('start whoami');+ return gates.who.promise.then((value) => {+ events.push('whoami answered');+ if (value instanceof Error) throw value;+ return value;+ });+ };+ return (url, method, apiPath, ...rest) => (apiPath === 'WhoAmI' ? whoAmI(url, method, apiPath, ...rest) : Promise.resolve({ status: 200, data: { value: [] } }));+ })(),},},});diff --git a/plugins/model-apps/scripts/tests/collection-answers.test.js b/plugins/model-apps/scripts/tests/collection-answers.test.jsindex 6014a6ddc..e01a08017 100644--- a/plugins/model-apps/scripts/tests/collection-answers.test.js+++ b/plugins/model-apps/scripts/tests/collection-answers.test.js@@ -225,7 +225,7 @@ const recording = (response) => {};const TABLE = { LogicalName: 'new_widget', SchemaName: 'new_Widget', EntitySetName: 'new_widgets', IsCustomEntity: true, DisplayName: { UserLocalizedLabel: { Label: 'Widget' } } };-test('REAL BUNDLE: an SDK made through lib/maker-sdk.js fails findTables() on an answer that is no list — as an SdkError with its own code, not the SDK\u2019s ConnectionError — and the bundle\u2019s own factory reads it as no tables', async (t) => {+test('REAL BUNDLE: an SDK made through lib/maker-sdk.js fails findTables() on an answer that is no list — as an SdkError with its own code, not the SDK\u2019s ConnectionError — and the bundle\u2019s own factory refuses it too, without that code', async (t) => {const noValue = [answerOf(200, '{}'), answerOf(200, null), answerHtml, answerOf(200, 'Service Unavailable')];for (const response of [...noValue, answerOf(200, { value: 'x' })]) {const sdk = createMakerSdk({ workspaceStorage: withWorkspace(t), instanceUrl: ORIGIN, httpClient: recording(response) });@@ -237,10 +237,19 @@ test('REAL BUNDLE: an SDK made through lib/maker-sdk.js fails findTables() on anreturn true;}, JSON.stringify(response.body));}- // The premise, which is the hole: the bundle on its own reads each of those answers as an environment with no table at all.+ // The bundle on its own used to read each of those answers as an environment with no table at all — the hole the guard was made for.+ // The bundled SDK now refuses them itself, as a ConnectionError of the 200 it read ("paginated read returned a malformed page"). The+ // guard stays in front of it: it answers first, so every script still gets TABLES_UNREADABLE — the code the callers recognise+ // (unreadableAnswer) — and the words that say this is not an empty environment and that signing in again is the remedy.for (const response of noValue) {const unguarded = bundle.createMakerSdk({ workspaceStorage: withWorkspace(t), instanceUrl: ORIGIN, httpClient: recording(response) });- assert.deepStrictEqual(await unguarded.findTables('new_widget'), [], JSON.stringify(response.body));+ await assert.rejects(unguarded.findTables('new_widget'), (err) => {+ assert.ok(err instanceof ConnectionError, 'the bundle refuses it as a ConnectionError');+ assert.strictEqual(err.code, 'CONNECTION_ERROR');+ assert.strictEqual(err.statusCode, 200);+ assert.match(err.message, /malformed page/);+ return true;+ }, JSON.stringify(response.body));}});diff --git a/plugins/model-apps/scripts/tests/dashboard-creation-recovery-real-bundle.test.js b/plugins/model-apps/scripts/tests/dashboard-creation-recovery-real-bundle.test.jsindex 463791ec1..de53b9085 100644--- a/plugins/model-apps/scripts/tests/dashboard-creation-recovery-real-bundle.test.js+++ b/plugins/model-apps/scripts/tests/dashboard-creation-recovery-real-bundle.test.js@@ -712,7 +712,10 @@ const FIRST_BUILD_WRITES = {};const FIRST_BUILD_READS = 41;const UNCHANGED_REBUILD_WRITES = { 'PATCH sitemaps': 1, 'POST AddAppComponents': 1, 'POST PublishXml': 2 };-const UNCHANGED_REBUILD_READS = 92;+// The bundled SDK reads three more before an unchanged rebuild's app update re-adds the app's components (an unpublished update that+// adds components): the app row's token and, as it matches, the app's current layer and its components — then sends the action as+// before when every component is there. Writes are unchanged.+const UNCHANGED_REBUILD_READS = 95;const BAD_RECORDS = [['damaged', (file) => fs.writeFileSync(file, '{ "schemaVersion": 1, "dashboards": '), /could not be read/],diff --git a/plugins/model-apps/scripts/tests/fixtures/sdk-error-codes.json b/plugins/model-apps/scripts/tests/fixtures/sdk-error-codes.jsonnew file mode 100644index 000000000..517427d1e--- /dev/null+++ b/plugins/model-apps/scripts/tests/fixtures/sdk-error-codes.json@@ -0,0 +1,241 @@+{+ "ACTION_REQUIRES_CONDITION": "diagnostic",+ "ACTION_VALUE_TOO_LONG": "diagnostic",+ "AMBIGUOUS_ARTIFACT": "typed",+ "ANCESTOR_NOT_SERVED": "typed",+ "ANCESTOR_UNDETERMINED": "typed",+ "APP_COMPONENTS_NOT_PERSISTED": "typed",+ "APP_COMPONENTS_UNVERIFIED": "typed",+ "APP_DELETE_NOT_ATOMIC": "typed",+ "APP_DRAFT_HEADER_NOT_WRITABLE": "typed",+ "APP_ENTITY_COMPONENT_UNRESOLVED": "typed",+ "APP_ICON_UNRESOLVED": "typed",+ "APP_MAIN_FORM_PUBLISH_CONFLICT": "typed",+ "APP_MAIN_FORM_PUBLISH_WITHHELD": "typed",+ "APP_MAIN_FORM_REMOVAL_UNSUPPORTED": "typed",+ "APP_MAIN_FORM_SET_NOT_APPLIED": "typed",+ "APP_MAIN_FORM_SET_UNVERIFIED": "typed",+ "APP_NOT_FOUND": "typed",+ "APP_PART_COMPONENT_TYPE_UNRESOLVED": "typed",+ "APP_SITEMAP_SHARED": "typed",+ "APP_SITEMAP_UNRESOLVED": "typed",+ "APP_THEME_LOGO_INVALID": "typed",+ "APP_THEME_NAME_TAKEN": "typed",+ "APP_THEME_NOT_IN_SOLUTION": "typed",+ "APP_THEME_NOT_RESOLVED": "typed",+ "APP_THEME_NOT_SAVED": "typed",+ "APP_THEME_PUBLISH_BLOCKED": "typed",+ "APP_THEME_PUBLISH_FAILED": "typed",+ "APP_THEME_UNAVAILABLE": "typed",+ "APP_UPDATE_NO_ETAG": "typed",+ "APP_UPDATE_OUTCOME_UNKNOWN": "outcome-unknown",+ "ARTIFACT_ALREADY_EXISTS": "typed",+ "ARTIFACT_DELETE_NO_ETAG": "typed",+ "ARTIFACT_IN_USE": "typed",+ "ARTIFACT_LANGUAGE_MISMATCH": "page-pre-write",+ "ARTIFACT_NOT_FOUND": "page-pre-write",+ "ARTIFACT_PROJECTION_STALE": "page-pre-write",+ "ARTIFACT_UPDATE_NO_ETAG": "typed",+ "BPF_CREATE_NOT_ROLLED_BACK": "typed",+ "BPF_CREATE_NO_TOKEN": "typed",+ "BPF_CREATE_REMOVED_AFTER_CONFLICT": "typed",+ "BPF_CREATE_ROLLBACK_OUTCOME_UNKNOWN": "outcome-unknown-unresolved",+ "BPF_DEACTIVATE_OUTCOME_UNKNOWN": "outcome-unknown-unresolved",+ "BPF_IN_ENTITY_SCOPE": "diagnostic",+ "BPF_LEFT_DEACTIVATED": "typed",+ "BPF_REACTIVATE_OUTCOME_UNKNOWN": "outcome-unknown-unresolved",+ "BPF_STATE_UNREADABLE": "typed",+ "BPF_WRITE_NOT_ECHOED": "typed",+ "BUSINESS_RULE_API_UNAVAILABLE": "typed",+ "BUSINESS_RULE_LEFT_DEACTIVATED": "typed",+ "CLAUSE_VALUE_TOO_LONG": "diagnostic",+ "COLUMN_VISUALIZATION_BIND_FAILED": "typed",+ "COMMAND_CONTEXT_ENTITY_UNRESOLVED": "typed",+ "COMMAND_DUPLICATE_ROW": "typed",+ "COMMAND_IMMUTABLE_COLUMN_CHANGED": "typed",+ "COMMAND_PARENT_LOCATION_UNREADABLE": "typed",+ "COMMAND_ROW_NOT_IN_BAR": "typed",+ "COMMAND_TABLE_MISMATCH": "typed",+ "COMPARISON_NOT_ESTABLISHED": "diagnostic",+ "CONNECTION_ERROR": "connection",+ "CONNECTION_REFERENCE_COMPONENT_TYPE_UNRESOLVED": "typed",+ "CONNECTIVITY_CLOUD_UNSUPPORTED": "typed",+ "CONNECTIVITY_ENVIRONMENT_UNVERIFIED": "typed",+ "CONNECTIVITY_NOT_CONFIGURED": "typed",+ "CONNECTIVITY_RESPONSE_UNREADABLE": "typed",+ "CONNECTIVITY_ROUTE_DECOMMISSIONED": "typed",+ "CONNECTIVITY_UNAUTHORIZED": "typed",+ "CONNECTOR_NOT_TABULAR": "typed",+ "CONNECTOR_OPERATION_NOT_FOUND": "typed",+ "CONNECTOR_RUNTIME_UNSUPPORTED": "typed",+ "CONNECTOR_SCHEMA_TOO_LARGE": "typed",+ "CONNECTOR_SWAGGER_UNSUPPORTED": "typed",+ "CUSTOM_API_COMPONENT_TYPE_UNRESOLVED": "typed",+ "CUSTOM_API_DELETE_UNVERIFIABLE": "typed",+ "CUSTOM_API_LABELS_UNSUPPORTED": "typed",+ "CUSTOM_API_NOT_ATOMIC": "typed",+ "CUSTOM_API_OPTION_UNRECOGNIZED": "typed",+ "DATA_FIX_ACCESS_REFUSED": "typed",+ "DATA_FIX_COLUMNS_INVALID": "typed",+ "DATA_FIX_CONCURRENCY_UNSUPPORTED": "typed",+ "DATA_FIX_PLAN_INVALID": "typed",+ "DATA_FIX_PLAN_OTHER_ORG": "typed",+ "DATA_FIX_READ_FAILED": "typed",+ "DATA_FIX_REQUEST_NOT_SENT": "typed",+ "DATA_FIX_REQUEST_UNKNOWN_OUTCOME": "typed",+ "DATA_FIX_TABLE_NOT_FOUND": "typed",+ "DATA_FIX_THROTTLE_BUDGET_EXHAUSTED": "typed",+ "DATA_FIX_TOO_MANY_ROWS": "typed",+ "DATETIME_BEHAVIOR_MISSING": "typed",+ "DUPLICATE_PROJECTED_ID": "typed",+ "DUPLICATE_RULE_IDENTITY_MISMATCH": "typed",+ "DUPLICATE_RULE_PUBLISH_FAILED": "typed",+ "DUPLICATE_RULE_READ_INCOMPLETE": "typed",+ "DUPLICATE_RULE_UPDATE_NOT_ATOMIC": "typed",+ "EMPTY_ACTION_FIELD": "diagnostic",+ "EMPTY_ACTION_MESSAGE": "diagnostic",+ "EMPTY_ACTION_VALUE": "diagnostic",+ "EMPTY_CLAUSE_FIELD": "diagnostic",+ "EMPTY_CLAUSE_VALUE": "diagnostic",+ "EMPTY_RECOMMENDATION_MESSAGE": "diagnostic",+ "EMPTY_RECOMMENDATION_TITLE": "diagnostic",+ "ENRICH_DEFAULT_VIEWS_PUBLISH_FAILED": "wraps-failure",+ "ENTITY_ENVELOPE_ALSO_SHIPS_UNRELATED_UNPUBLISHED_CHANGES": "typed",+ "ENVIRONMENT_LANGUAGES_UNREADABLE": "typed",+ "ENVIRONMENT_VARIABLE_DELETE_NOT_ATOMIC": "typed",+ "ENVIRONMENT_VARIABLE_DELETE_UNGUARDED": "typed",+ "ENVIRONMENT_VARIABLE_SECRET_UNRECOGNIZED": "typed",+ "ENVIRONMENT_VARIABLE_TYPE_UNRECOGNIZED": "typed",+ "ENVIRONMENT_VARIABLE_VALUE_UNSETTLED": "typed",+ "FIELD_PERMISSION_UNRECOGNIZED": "typed",+ "FIELD_SECURITY_COLUMN_NOT_SECURED": "typed",+ "FIELD_SECURITY_PROFILE_PLATFORM_MANAGED": "typed",+ "FIELD_SECURITY_PROFILE_PUSH_NOT_ATOMIC": "typed",+ "FORM_GENPAGE_TARGET_NOT_FOUND": "typed",+ "FORM_GENPAGE_TARGET_UNVERIFIABLE": "typed",+ "FORM_TYPE_IMMUTABLE": "typed",+ "GENPAGE_COMPILER_INVALID": "page-pre-write",+ "GENPAGE_COMPILER_UNAVAILABLE": "page-pre-write",+ "GENPAGE_COMPILER_VERSION": "page-pre-write",+ "GENPAGE_COMPILE_DEPTH_EXCEEDED": "typed",+ "GENPAGE_COMPONENT_TYPE_UNRESOLVED": "typed",+ "GENPAGE_CONTENT_NOT_TEXT": "page-pre-write",+ "GENPAGE_CONTENT_UNREADABLE": "typed",+ "GENPAGE_CONTENT_WRITE_UNSUPPORTED": "page-pre-write",+ "GENPAGE_DATA_SOURCE_INCOMPLETE": "typed",+ "GENPAGE_FILES_REQUIRED": "typed",+ "GENPAGE_HISTORY_NOT_DELETED": "typed",+ "GENPAGE_PUBLISHED_READ_MOVED": "typed",+ "GENPAGE_PUBLISHED_READ_UNVERSIONED": "typed",+ "GENPAGE_RETAINED_ROW_MISSING": "page-pre-write",+ "GENPAGE_RETAIN_ON_CREATE": "page-pre-write",+ "GENPAGE_RUNTIME_TYPES_INVALID": "page-pre-write",+ "GENPAGE_TURN_CONFLICT": "page-pre-write",+ "GENPAGE_TURN_NOT_ATOMIC": "page-pre-write",+ "GENPAGE_WRITE_UNKNOWN": "page-pre-write",+ "IDENTITY_MISMATCH": "diagnostic",+ "INCOMPATIBLE_WORKSPACE": "typed",+ "INSPECTION_NOT_SUPPORTED": "typed",+ "INSPECTION_UNREADABLE": "typed",+ "INVALID_ARGUMENT": "typed",+ "INVALID_CLAUSE_NUMERIC_VALUE": "diagnostic",+ "INVALID_CLAUSE_OPTION_VALUE": "diagnostic",+ "INVALID_CLEAR_FOR_FIELD": "diagnostic",+ "INVALID_DAY_COUNT": "diagnostic",+ "INVALID_JSON_POINTER": "typed",+ "INVALID_PARENT_KIND": "diagnostic",+ "INVALID_VALUE_TYPE_FOR_FIELD": "diagnostic",+ "LANGUAGES_UNREADABLE": "diagnostic",+ "LOCAL_EDITS_WOULD_BE_LOST": "typed",+ "LOCATION_MISMATCH": "diagnostic",+ "MIXED_APP_SCOPE": "diagnostic",+ "NOT_IMPLEMENTED": "typed",+ "NOT_PROJECTED": "typed",+ "NO_ACTION": "diagnostic",+ "NO_CONDITION": "diagnostic",+ "PARENT_NOT_IN_BAR": "diagnostic",+ "PATH_NOT_FOUND": "typed",+ "PATH_TRAVERSAL": "typed",+ "PCF_COLUMN_UNAVAILABLE": "typed",+ "PCF_CONTROL_NOT_FOUND": "typed",+ "PCF_MANIFEST_UNAVAILABLE": "typed",+ "PREVIEW_APP_PIN_GUARD_NOT_EVALUATED": "diagnostic",+ "PREVIEW_BATCH_DEPENDENCY": "diagnostic",+ "PREVIEW_CREATE_ADOPTION_ELIGIBLE": "diagnostic",+ "PREVIEW_DELETE_OF_MANAGED": "diagnostic",+ "PREVIEW_LAYER_OVER_MANAGED": "diagnostic",+ "PREVIEW_PLAN_INCOMPLETE": "diagnostic",+ "PREVIEW_READ_FAILED": "diagnostic",+ "PREVIEW_REMOTE_CHANGES_UNAVAILABLE": "diagnostic",+ "PREVIEW_SIBLING_MOVED": "diagnostic",+ "PREVIEW_SOLUTION_MANAGED": "diagnostic",+ "PREVIEW_SOLUTION_NOT_FOUND": "diagnostic",+ "PREVIEW_WRITE_REFUSED": "diagnostic",+ "PRIMARY_COLUMN_REQUIRED_NOT_APPLIED": "typed",+ "PROMOTION_APP_NOT_IN_PACKAGE": "typed",+ "PROMOTION_ATTEMPT_IN_PROGRESS": "typed",+ "PROMOTION_CLEANUP_FAILED": "typed",+ "PROMOTION_CODEC_REQUIRED": "typed",+ "PROMOTION_COMPONENT_COLLISION": "typed",+ "PROMOTION_CONNECTION_CONNECTOR_MISMATCH": "typed",+ "PROMOTION_CONNECTION_NOT_IN_TARGET": "typed",+ "PROMOTION_CONNECTION_UNMAPPED": "typed",+ "PROMOTION_COVERAGE_GAP": "typed",+ "PROMOTION_DEPENDENCY_IDENTITY_UNRESOLVED": "typed",+ "PROMOTION_DEPENDENCY_MISSING": "typed",+ "PROMOTION_ENVIRONMENT_MISMATCH": "typed",+ "PROMOTION_HOLDING_PRESENT": "typed",+ "PROMOTION_IMPORT_FAILED": "typed",+ "PROMOTION_IMPORT_UNKNOWN": "typed",+ "PROMOTION_JOURNAL_FAILED": "typed",+ "PROMOTION_JOURNAL_REQUIRED": "typed",+ "PROMOTION_NON_ATOMIC_IMPORT_NOT_ACKNOWLEDGED": "typed",+ "PROMOTION_PACKAGE_MODE_MISMATCH": "typed",+ "PROMOTION_PACKAGE_UNREADABLE": "typed",+ "PROMOTION_PLAN_INVALID": "typed",+ "PROMOTION_PLAN_STALE": "typed",+ "PROMOTION_PUBLICATION_SCOPE_UNKNOWN": "typed",+ "PROMOTION_PUBLISHER_MISMATCH": "typed",+ "PROMOTION_PUBLISH_REQUIRED": "typed",+ "PROMOTION_READ_BUDGET_EXCEEDED": "typed",+ "PROMOTION_RECEIPT_UNVERIFIED": "typed",+ "PROMOTION_SAME_ENVIRONMENT": "typed",+ "PROMOTION_SECRET_VALUE": "typed",+ "PROMOTION_SETTING_UNAVAILABLE": "typed",+ "PROMOTION_SOURCE_PACKAGE_MISMATCH": "typed",+ "PROMOTION_STAGE_FAILED": "typed",+ "PROMOTION_STAGE_UNKNOWN": "typed",+ "PROMOTION_TARGET_MODE_MISMATCH": "typed",+ "PROMOTION_TENANT_MISMATCH": "typed",+ "PROMOTION_UPGRADE_NOT_SUPPORTED": "typed",+ "PROMOTION_VALUE_REQUIRED": "typed",+ "PROMOTION_VERIFICATION_FAILED": "typed",+ "PROMOTION_VERIFICATION_UNAVAILABLE": "diagnostic",+ "PROMOTION_VERSION_REFUSED": "typed",+ "PUSH_NOT_ATTEMPTED": "typed",+ "READ_FAILED": "diagnostic",+ "RECOMMENDATION_NO_APPLY_ACTION": "diagnostic",+ "ROW_SUMMARY_MODEL_NOT_DELETED": "typed",+ "ROW_SUMMARY_REMOVAL_UNCONFIRMED": "typed",+ "ROW_SUMMARY_TEMPLATE_NOT_FOUND": "typed",+ "SITEMAP_TARGET_NOT_FOUND": "typed",+ "SITEMAP_TARGET_UNVERIFIABLE": "typed",+ "SOLUTION_COMPONENT_UNCLASSIFIED": "typed",+ "SOLUTION_STAGING_FAILED": "typed",+ "SOLUTION_STAGING_UNREADABLE": "typed",+ "STALE_ARTIFACT": "typed",+ "SYSTEMFORM_KIND_MISMATCH": "typed",+ "TABLE_METADATA_NOT_VISIBLE": "typed",+ "TABLE_SEARCH_NOT_ALLOWED": "typed",+ "UNKNOWN_KIND": "diagnostic",+ "UNREACHABLE_ELSE": "diagnostic",+ "UNSUPPORTED_LOCATION": "diagnostic",+ "UPSERT_OUTCOME_UNKNOWN": "outcome-unknown",+ "VALIDATION_ERROR": "page-pre-write",+ "VERSION_CONFLICT": "typed",+ "WEB_RESOURCE_UNVERIFIED": "wraps-failure",+ "WORKFLOW_DELETE_UNSETTLED": "typed",+ "WORKFLOW_KIND_MISMATCH": "typed",+ "WORKSPACE_NOT_INITIALIZED": "typed",+ "WORKSPACE_ORG_MISMATCH": "typed"+}diff --git a/plugins/model-apps/scripts/tests/genpage-app-edit-real-bundle.test.js b/plugins/model-apps/scripts/tests/genpage-app-edit-real-bundle.test.jsindex 02f06519c..fd4c1fb47 100644--- a/plugins/model-apps/scripts/tests/genpage-app-edit-real-bundle.test.js+++ b/plugins/model-apps/scripts/tests/genpage-app-edit-real-bundle.test.js@@ -165,8 +165,10 @@ test('REAL BUNDLE: a pin the service refuses is a warning, as it was — the pagtry {const placed = await genpage.placeInApp(APP_ID, { pages: [{ pageId: OTHER, title: 'Other' }], dataSources: ['account'], finishIfUnpublished: true });assert.deepStrictEqual([placed.added, placed.provedPublished], [[OTHER], true]);- assert.strictEqual(placed.warnings.length, 1);+ assert.strictEqual(placed.warnings.length, 2, JSON.stringify(placed.warnings));assert.match(placed.warnings[0], /one or more components were not pinned \(.*HTTP 400.*The savedquery does not exist\./);+ assert.deepStrictEqual(placed.pinnedViews, [], 'a view the service refused is not reported as pinned');+ assert.match(placed.warnings[1], new RegExp(`^the default view ${APP_VIEW_ID} of the tables the pages read was not added to app ${APP_ID}`));assert.ok(namesPage(app.state.publishedXml, OTHER));assertMembership(world, { views: [] });} finally {@@ -557,3 +559,67 @@ for (const [label, sentAs] of SENT_AS) {}, { defaultViewPinned: false });});}++// The bundled SDK's guarded pin (lib/app-component-scope.js, THE SDK'S GUARDED PIN). On the strict fake of a whole environment, an app the build made — app and sitemap with tokens of their own, so the+// SDK's gate after the sitemap write finds the app token it holds — whose maker then took the table's forms and views out of it. The page backend pins the table's default view: the SDK then sends its+// pin as a change set (guard, action, echo), which the page's transport does not send; the bundle sends its plain action instead, limited to that view, as every earlier release did.+async function inBuiltApp(fn) {+ const { createLifecycleOrg } = require('./helpers/fake-lifecycle-org.js');+ const { createLifecycleHarness } = require('./helpers/lifecycle-harness.js');+ const org = createLifecycleOrg();+ const harness = createLifecycleHarness(org, tmp());+ const spec = {+ schemaVersion: 2,+ solution: { uniqueName: 'ContosoPin', displayName: 'Contoso Pin', publisherPrefix: 'contoso' },+ app: { name: 'Pin' },+ entities: [{ schemaName: 'contoso_project', displayName: 'Project', pluralName: 'Projects', primaryAttribute: { schemaName: 'contoso_name', displayName: 'Name' }, columns: [] }],+ pages: [{ key: 'overview', name: 'Overview', purpose: 'A page.', dataSources: ['contoso_project'], source: { kind: 'tsx', codeFile: 'KitchenPage.tsx' } }],+ appShell: { areas: [{ label: 'Work', groups: [{ label: 'Records', subAreas: [{ entity: 'contoso_project', title: 'Projects' }, { page: 'overview', title: 'Overview' }] }] }] },+ };+ const made = await harness.build(spec);+ assert.strictEqual(made.result.ok, true, JSON.stringify(made.result));+ const appId = made.result.created.app;+ const members = org.rowsOf('appmodulecomponents');+ const removedForms = [...members.values()].filter((row) => row.data.componenttype === 60).map((row) => row.data.objectid);+ for (const [id, row] of [...members]) if ([26, 60].includes(row.data.componenttype)) members.delete(id);+ return fn({ org, harness, appId, removedForms });+}+const inApp = (org, type) => org.find('appmodulecomponents', (row) => row.componenttype === type).map((row) => String(row.objectid).toLowerCase());++test('REAL BUNDLE: the default view a page edit pins is added when the SDK would send its pin as a guarded change set — only that view, by the plain action, the app published once, the forms the maker took out left out', async () => {+ await inBuiltApp(async ({ org, harness, appId, removedForms }) => {+ assert.ok(removedForms.length > 0, 'the app had a Main form the maker took out');+ const genpage = makeGenpageSdk(org.origin, { httpClient: harness.client });+ try {+ const [wanted] = (await genpage.defaultViews(['contoso_project'])).views.map((view) => view.viewId);+ const mark = org.mark();+ const placed = await genpage.placeInApp(appId, { pages: [], dataSources: ['contoso_project'] });+ assert.deepStrictEqual(org.unexpected, []);+ assert.deepStrictEqual(inApp(org, 26), [wanted], 'the view is in the app');+ assert.deepStrictEqual(inApp(org, 60), [], 'no Main form the maker took out came back');+ assert.deepStrictEqual(org.writeCounts(mark), { 'PATCH sitemaps': 1, 'POST AddAppComponents': 1, 'POST PublishXml': 1 }, 'the sitemap, the one limited action and one publish — as before 2.20.6: no app-row write, no change set');+ const posted = org.writes(mark).filter((write) => /AddAppComponents/.test(write.path));+ assert.deepStrictEqual(posted.map((write) => [write.batched === true, write.body && write.body.Components]), [[false, [{ '@odata.type': 'Microsoft.Dynamics.CRM.savedquery', savedqueryid: wanted }]]]);+ assert.deepStrictEqual([placed.pinnedViews, placed.warnings, placed.appEdited], [[wanted], [], true]);+ } finally {+ await genpage.dispose();+ }+ });+});++test('REAL BUNDLE: the same state reaches the SDK\'s guarded pin — through a transport no page edit limits, the bundle sends guard, action and echo in one change set', async () => {+ await inBuiltApp(async ({ org, harness, appId }) => {+ // A lent SDK keeps its lender's transport, so the edit through it is not limited (lib/genpage-sdk.js `deps.sdk`).+ const sdk = createMakerSdk({ workspaceStorage: createNodeWorkspaceStorage(tmp()), instanceUrl: org.origin, httpClient: harness.client });+ await sdk.initWorkspace();+ const genpage = makeGenpageSdk(org.origin, { sdk });+ try {+ const mark = org.mark();+ await genpage.placeInApp(appId, { pages: [], dataSources: ['contoso_project'] });+ const batched = org.writes(mark).filter((write) => write.batched).map((write) => `${write.method} ${write.path.split('?')[0].replace(/\(.*\)/, '()')}`);+ assert.deepStrictEqual(batched, ['PATCH /appmodules()', 'POST /AddAppComponents', 'PATCH /appmodules()'], 'the guarded change set the page edit above does not send');+ } finally {+ await genpage.dispose();+ }+ });+});\ No newline at end of filediff --git a/plugins/model-apps/scripts/tests/genpage-dispatch-contract.test.js b/plugins/model-apps/scripts/tests/genpage-dispatch-contract.test.jsindex d402fb4de..0c3d28a91 100644--- a/plugins/model-apps/scripts/tests/genpage-dispatch-contract.test.js+++ b/plugins/model-apps/scripts/tests/genpage-dispatch-contract.test.js@@ -1151,24 +1151,26 @@ test('every genpage-plan-provenance.js command the genpage flows document uses oassert.doesNotMatch(editFlow, /--require-assumptions|--require-observed-lookups|--lookup-metadata/, 'neighbour: an edit plan keeps its own comparison');});-// Iteration that compiles to nothing (references/rules.md, Critical Rule 24 and Common Errors > 5). The SDK compiles a page to ES5 without-// iterator downleveling, so a spread, a for...of loop or an array destructure of a Map, a Set or an iterator reads length and indices: the-// values disappear with a clean compile (scripts/tests/iteration-emit.test.js runs that emit). Nothing executes these instructions, so as-// with the Griffel rule the one rule text is stated in the same words in every document that writes or edits a page (whitespace aside), and-// the WRONG/CORRECT examples live in rules.md alone.+// Iteration that another page compiler can lose (references/rules.md, Critical Rule 24 and Common Errors > 5). The SDK compiles a page to ES5+// with iterator support, but a tool that compiles the page again without it (an older maker portal, pac) reads a Map, a Set or an iterator+// by length and indices: the values disappear with a clean compile (scripts/tests/iteration-emit.test.js runs both emits). Nothing executes+// these instructions, so as with the Griffel rule the one rule text is stated in the same words in every document that writes or edits a+// page (whitespace aside), and the WRONG/CORRECT examples live in rules.md alone.const ITERATION_RULE = [- 'The page compiler targets ES5 without iterator downleveling or full type checking.',- 'Spreading, looping over, or array-destructuring a Map, Set or iterator reads length and indices instead of the iterator:',- 'values can disappear, defaults can replace them, or rest destructuring can throw.',- 'This includes `[...new Set(xs)]`, `[...m.values()]`, `[...seen.values()]`, `for (const [k, v] of m)`, `new Set([...prev, id])`,',- '`[...selected]` and `[...text.matchAll(re)]`.',- 'Convert with `Array.from(...)` before spreading, looping or destructuring; copy a Set with `new Set(prev)` then `.add(id)`.',+ 'Pages this plugin uploads are compiled with iterator support (ES5 with `downlevelIteration`), so a spread, a `for...of` loop or an array',+ 'destructure of a Map, Set, iterator, generator or string reads it as modern JavaScript does.',+ 'A tool that compiles the page again without that support — an older maker portal, or `pac` — reads length and indices instead:',+ 'values disappear, defaults replace them, and rest destructuring or a string spread throws, all with a clean compile.',+ 'Keep the page correct under every compiler: convert with `Array.from(...)` before spreading, looping or destructuring, for example',+ '`[...new Set(xs)]`, `[...m.values()]`, `[...seen.values()]`, `for (const [k, v] of m)`, `new Set([...prev, id])`, `[...selected]` and',+ '`[...text.matchAll(re)]`; copy a Set with `new Set(prev)` then `.add(id)`.','Ordinary array spreads and loops remain valid. `Object.keys`, `Object.values` and `Object.entries` return arrays.',- 'Spreads of `arguments` and ordinary indexed array-likes work; rest destructuring of an array-like without `slice` does not.',- 'String spread throws, and an ES5 string loop visits UTF-16 code units rather than Unicode code points.',- 'See **Common Errors > 5. Iteration that compiles to nothing** in `references/rules.md` for the pairs.',+ 'Rest destructuring of a non-iterable array-like without `slice` throws under every compiler.',+ 'A destructuring default must not write to the array being destructured: `const [a = (values[1] = 3), b] = values` leaves `b` at its old',+ 'value here, unlike modern JavaScript.',+ 'See **Common Errors > 5. Iteration that another page compiler can lose** in `references/rules.md` for the pairs.',].join(' ');-const ITERATION_SECTION = '**Common Errors > 5. Iteration that compiles to nothing**';+const ITERATION_SECTION = '**Common Errors > 5. Iteration that another page compiler can lose**';test('every instruction that writes or edits a page states the iteration rule in the same words, where it reviews the page', () => {const docs = griffelDocs();@@ -1176,7 +1178,7 @@ test('every instruction that writes or edits a page states the iteration rule inassert.ok(squash(text).includes(ITERATION_RULE), `${name} must state the iteration rule in the shared words`);}// rules.md: the section opens with it, after Common Errors 1-4, which keep their numbers.- const section = docs.rules.split('\n### 5. Iteration that compiles to nothing\n');+ const section = docs.rules.split('\n### 5. Iteration that another page compiler can lose\n');assert.equal(section.length, 2, 'rules.md has one canonical section');assert.ok(squash(section[1]).trimStart().startsWith(ITERATION_RULE), 'the section opens with the rule');const errors = docs.rules.slice(docs.rules.indexOf('\n## Common Errors\n'));@@ -1187,7 +1189,7 @@ test('every instruction that writes or edits a page states the iteration rule inassert.deepEqual([...critical.matchAll(/^(\d+)\. \*\*/gm)].map((match) => Number(match[1])), Array.from({ length: 24 }, (_, i) => i + 1));assert.match(critical, /\n22\. \*\*Consistent errors\*\*[^\n]*\n23\. \*\*Lookup identities\*\*[^\n]*\n24\. \*\*Convert iterables to arrays\*\*[^\n]*\n\n---\n/);// The page-builder has no shell: its Step 2.7 gives the rule and a self-review, and no command.- const builderStep = docs['page-builder'].split('## Step 2.7 — Iteration that compiles to nothing')[1].split('## Step 3')[0];+ const builderStep = docs['page-builder'].split('## Step 2.7 — Iteration that another page compiler can lose')[1].split('## Step 3')[0];assert.ok(squash(builderStep).includes(ITERATION_RULE), 'the page-builder states it in its own step');assert.ok(docs['page-builder'].indexOf('## Step 2.6') < docs['page-builder'].indexOf('## Step 2.7'), 'after the Griffel step');assert.doesNotMatch(builderStep, /node\s+"\$\{PLUGIN_ROOT\}/, 'no command for a worker to run');@@ -1201,6 +1203,8 @@ test('every instruction that writes or edits a page states the iteration rule inconst editRule = squash(edit).indexOf(ITERATION_RULE);assert.ok(editRule > 0 && editRule < squash(edit).indexOf('## Edit Phase 6: Deploy Updated Page'), 'an edited page is reviewed before it is uploaded');assert.match(squash(edit), /Do not silently expand an unrelated edit: convert an existing form only when the requested change needs it or the user asks for it, and state any resulting behavior change in the summary\./);+ assert.match(squash(edit), /`Array\.from` reads the whole iterable at once: where a loop stops early or a destructure reads only the first values of a generator or another iterator, the conversion reads the rest too/, 'converting an existing form is not said to be neutral');+ assert.doesNotMatch(squash(edit), /changes nothing here/);// /app-builder: Phase 1.5 step 5, before promote-intent-pages.js commits the pages.const appBuilder = docs['app-builder'];const appRule = squash(appBuilder).indexOf(ITERATION_RULE);diff --git a/plugins/model-apps/scripts/tests/genpage-page-nesting.test.js b/plugins/model-apps/scripts/tests/genpage-page-nesting.test.jsindex 2692902ab..a696a5f09 100644--- a/plugins/model-apps/scripts/tests/genpage-page-nesting.test.js+++ b/plugins/model-apps/scripts/tests/genpage-page-nesting.test.js@@ -185,6 +185,50 @@ test('the gates keep today\'s answers for every page that is not one the parserassert.deepStrictEqual(pageStructure(`${GENERIC_SIGNATURE}${DEEP_BUT_FINE}`), { problems: [], code: null });});+// The bundled SDK now refuses a source too deep for the compiler itself (GENPAGE_COMPILE_DEPTH_EXCEEDED), over every stage of its compile — the parse, the emit, the+// checker and its own walks — while the factory's guard covers only the compiler's entry points. Whichever layer fires, the maker sees ONE refusal: the plugin's code and words,+// `outcome: 'nothing'`, never run again. This drives the real bundle with the vendored compiler UNguarded, so it is the SDK's own refusal that reaches the backend.+test('the SDK\'s own compile-depth refusal reaches the maker as PAGE_NESTING_TOO_DEEP, wrote nothing, and is never sent again — on create and on update', async () => {+ const { loadVendoredTypeScript } = require('../lib/typescript-compiler.js');+ const { retryPolicyFor, RETRY } = require('../lib/retry-policy.js');+ const server = makeServer();+ const folder = makeTempDir('nest-sdk-');+ const sdk = createMakerSdk({ workspaceStorage: createNodeWorkspaceStorage(folder), instanceUrl: INSTANCE, httpClient: server.http(), typescript: () => loadVendoredTypeScript() });+ await sdk.initWorkspace();+ const raw = await sdk.createArtifact('genPage', { name: 'Raw', source: TOO_DEEP, dataSources: ['account'], newTurn: { prompt: 'p' } });+ await assert.rejects(sdk.pushArtifact('genPage', raw.id), (e) => e instanceof SdkError && e.code === 'GENPAGE_COMPILE_DEPTH_EXCEEDED', 'the bundle raises its own code when no guard is over its compiler');+ assert.strictEqual(writeOutcome(new SdkError('GENPAGE_COMPILE_DEPTH_EXCEEDED', 'x')), 'nothing', 'the SDK compiles before any write');+ assert.ok(PRE_WRITE_REFUSALS.has('GENPAGE_COMPILE_DEPTH_EXCEEDED'));++ const genpage = makeGenpageSdk(INSTANCE, { sdk });+ try {+ await assert.rejects(+ genpage.create({ name: 'Overview', source: TOO_DEEP, dataSources: 'account', prompt: 'p', agentMessage: 'a' }),+ (e) => {+ assert.strictEqual(e.code, PAGE_NESTING_TOO_DEEP, 'the code makers and the docs know');+ assert.strictEqual(e.outcome, 'nothing', 'not an unknown outcome settled by reads');+ assert.strictEqual(e.transient, false);+ assert.strictEqual(retryPolicyFor(e), RETRY.NEVER, 'the build never runs it again');+ assert.strictEqual(retryPolicyFor(new SdkError('GENPAGE_COMPILE_DEPTH_EXCEEDED', 'x')), RETRY.NEVER, 'nor the SDK\'s code on its own');+ assert.match(e.message, /^generative page "Overview" was not created \(nothing was written\): the elements of the page nest too deeply to compile .* split the page into components/);+ assert.ok(!/sent twice|Maximum call stack/.test(e.message), e.message);+ return true;+ },+ );+ assert.deepStrictEqual(changeWrites(server), [], 'not one request was written');+ const { pageId } = await genpage.create({ name: 'Overview', source: DEEP_BUT_FINE, dataSources: 'account', prompt: 'p', agentMessage: 'ok' });+ const before = server.writes().length;+ await assert.rejects(+ genpage.update(pageId, { source: TOO_DEEP, prompt: 'p2', agentMessage: 'a2' }),+ (e) => e.code === PAGE_NESTING_TOO_DEEP && e.outcome === 'nothing' && e.pageId === pageId && !/Maximum call stack|could not be compiled because/.test(e.message)+ && /^the update of generative page "Overview" \(.+\) failed and wrote nothing: the elements of the page nest too deeply to compile/.test(e.message),+ );+ assert.strictEqual(server.writes().length, before, 'the refused update wrote nothing');+ } finally {+ await genpage.dispose();+ }+});+test('a push through the factory\'s own SDK, with no page backend over it, is refused with the same code and nothing is written; the page\'s name is the backend\'s to add', async () => {const server = makeServer();const folder = makeTempDir('nest-direct-');diff --git a/plugins/model-apps/scripts/tests/genpage-sdk-app.test.js b/plugins/model-apps/scripts/tests/genpage-sdk-app.test.jsindex b971854be..48c25477e 100644--- a/plugins/model-apps/scripts/tests/genpage-sdk-app.test.js+++ b/plugins/model-apps/scripts/tests/genpage-sdk-app.test.js@@ -336,12 +336,16 @@ test('placeInApp: the sitemap title language is the SDK\'s construction-time opt// ── placeInApp: pinning the default views ───────────────────────────────────────────────────────────────────────-const viewRecords = ({ held = [], views = { account: V_ACCOUNT, contact: V_CONTACT } } = {}) => ({+// The app's views: those it `held` before, and — as the service would answer once the push landed — those its pushed copy names (`lands: false`: a push whose pin did not land).+const viewRecords = ({ held = [], views = { account: V_ACCOUNT, contact: V_CONTACT }, lands = true } = {}) => ({savedquery: (o) => {const table = /returnedtypecode eq '([^']+)'/.exec(o.filter)[1];return views[table] ? [{ savedqueryid: views[table].toUpperCase() }] : [];},- appmodulecomponent: () => held.map((objectid) => ({ objectid: `{${objectid}}`, componenttype: 26 })),+ appmodulecomponent: (o, sdk) => {+ const pushed = lands && sdk && sdk.count('pushArtifact') > 0 ? (((sdk.apps.get(APP) || {}).components || {}).views || []) : [];+ return [...new Set([...held, ...pushed])].map((objectid) => ({ objectid: `{${objectid}}`, componenttype: 26 }));+ },});test('pinning: the default public view of each data source joins the app\'s components, and the app is pushed and published', async () => {@@ -395,10 +399,22 @@ test('pinning: an app that already carries components.views is extended in placeassert.deepStrictEqual(noViews.of('addElement').map((c) => c.args), [['app', APP, '/components', { views: [V_ACCOUNT] }]]);});-test('pinning: a layer that cannot be read leaves every view to pin — AddAppComponents is additive, so the worst case is a push that changes nothing', async () => {+test('pinning: a layer that cannot be read leaves every view to pin — AddAppComponents is additive, so the worst case is a push that changes nothing — and none of them is reported pinned, since none is seen to be', async () => {const sdk = new FakeSdk({ records: viewRecords({ held: [V_ACCOUNT] }), onGet: async () => ({ status: 500, body: null }) }).seedApp(appArtifact());const out = await backend(sdk).placeInApp(APP, { pages: [], dataSources: ['account'] });- assert.deepStrictEqual(out.pinnedViews, [V_ACCOUNT]);+ assert.deepStrictEqual(sdk.of('addElement').map((c) => c.args), [['app', APP, '', { components: { views: [V_ACCOUNT] } }]], 'the view is asked for');+ assert.deepStrictEqual(out.pinnedViews, []);+ assert.strictEqual(out.warnings.length, 1);+ assert.match(out.warnings[0], new RegExp(`^the default view ${V_ACCOUNT} of the tables the pages read could not be confirmed in app ${APP}: its components could not be read back`));+});++test('pinning: a view the push did not add is not reported pinned — the app is read back after the push, and what is not there is said in a warning', async () => {+ const sdk = placing(appArtifact(), viewRecords({ lands: false }));+ const out = await backend(sdk).placeInApp(APP, { pages: [], dataSources: ['account', 'contact'] });+ assert.strictEqual(sdk.count('pushArtifact'), 1);+ assert.strictEqual(sdk.count('publishArtifact'), 1, 'the app is published all the same: the pin is the push\'s own partial result');+ assert.deepStrictEqual(out.pinnedViews, []);+ assert.deepStrictEqual(out.warnings, [`the default views ${V_ACCOUNT}, ${V_CONTACT} of the tables the pages read were not added to app ${APP} — the maker's "/" picker may not list their tables; run the same command again to add them`]);});test('pinning: a table name is escaped into the OData filter as a literal', async () => {diff --git a/plugins/model-apps/scripts/tests/genpage-sdk-real-bundle.test.js b/plugins/model-apps/scripts/tests/genpage-sdk-real-bundle.test.jsindex e46d26c4b..2bad2c329 100644--- a/plugins/model-apps/scripts/tests/genpage-sdk-real-bundle.test.js+++ b/plugins/model-apps/scripts/tests/genpage-sdk-real-bundle.test.js@@ -739,6 +739,13 @@ test('REAL BUNDLE: an update whose first send lands immediately before its resenassert.strictEqual(server.messagesOf(pageId).length, 4);assert.strictEqual(out.publish.kind, 'verified');assert.match(out.warnings.join('\n'), /had been written — so it was not sent again/);+ // The bundled SDK names a push's versioning checkpoint after the turn it records (`uxagentproject_<turn id>`), so the resend of the+ // same edit addresses the same checkpoint; the bundles before model-apps 2.20.6 minted a new one per send.+ const checkpoints = server.batches.map((body) => [...new Set(String(body).match(/MSCRM\.VersioningChangeset: \S+/g) || [])]);+ assert.strictEqual(checkpoints[1].length, 1, 'one checkpoint per change set');+ assert.deepStrictEqual(checkpoints[2], checkpoints[1], 'the resend of the same turn names the same checkpoint');+ assert.notDeepStrictEqual(checkpoints[1], checkpoints[0], 'another turn, another checkpoint');+ assert.match(checkpoints[1][0], /^MSCRM\.VersioningChangeset: uxagentproject_[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/, 'lower case, no braces');});});diff --git a/plugins/model-apps/scripts/tests/genpage-sdk.test.js b/plugins/model-apps/scripts/tests/genpage-sdk.test.jsindex 1d8d428ee..bfb403a1d 100644--- a/plugins/model-apps/scripts/tests/genpage-sdk.test.js+++ b/plugins/model-apps/scripts/tests/genpage-sdk.test.js@@ -87,7 +87,7 @@ test('writeOutcome: what a failed SDK send says it did — nothing, or unknown// raises it, which is before any request is sent — so a change to it is a decision, and this is where it is made.assert.deepStrictEqual([...PRE_WRITE_REFUSALS].sort(), ['ARTIFACT_LANGUAGE_MISMATCH', 'ARTIFACT_NOT_FOUND', 'ARTIFACT_PROJECTION_STALE',- 'GENPAGE_COMPILER_INVALID', 'GENPAGE_COMPILER_UNAVAILABLE', 'GENPAGE_COMPILER_VERSION', 'GENPAGE_CONTENT_NOT_TEXT', 'GENPAGE_CONTENT_WRITE_UNSUPPORTED',+ 'GENPAGE_COMPILER_INVALID', 'GENPAGE_COMPILER_UNAVAILABLE', 'GENPAGE_COMPILER_VERSION', 'GENPAGE_COMPILE_DEPTH_EXCEEDED', 'GENPAGE_CONTENT_NOT_TEXT', 'GENPAGE_CONTENT_WRITE_UNSUPPORTED','GENPAGE_RETAINED_ROW_MISSING', 'GENPAGE_RETAIN_ON_CREATE', 'GENPAGE_RUNTIME_TYPES_INVALID', 'GENPAGE_TURN_CONFLICT', 'GENPAGE_TURN_NOT_ATOMIC', 'GENPAGE_WRITE_UNKNOWN','PAGE_NESTING_TOO_DEEP', 'VALIDATION_ERROR',]);diff --git a/plugins/model-apps/scripts/tests/golden/lifecycle-trail.build.txt b/plugins/model-apps/scripts/tests/golden/lifecycle-trail.build.txtnew file mode 100644index 000000000..9030d1a1c--- /dev/null+++ b/plugins/model-apps/scripts/tests/golden/lifecycle-trail.build.txt@@ -0,0 +1,391 @@+# 419 requests, 11 publishes+## up to publish 1: importexportxml(webresources(webresource=#id))+ 2x GET /EntityDefinitions(<id>)/Attributes?$select=MetadataId,LogicalName -> 200+ 3x GET /EntityDefinitions(<id>)?$select=LogicalName,EntitySetName,PrimaryIdAttribute,PrimaryNameAttribute -> 200+ 1x GET /EntityDefinitions(LogicalName='appmodule')?$select=EntitySetName -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_project')/Attributes/Microsoft.Dynamics.CRM.MultiSelectPicklistAttributeMetadata?$select=LogicalName&$expand=OptionSet($select=Options) -> 404+ 1x GET /EntityDefinitions(LogicalName='contoso_project')/Attributes/Microsoft.Dynamics.CRM.PicklistAttributeMetadata?$select=LogicalName&$expand=OptionSet($select=Options) -> 404+ 1x GET /EntityDefinitions(LogicalName='contoso_project')/Attributes/Microsoft.Dynamics.CRM.StateAttributeMetadata?$select=LogicalName&$expand=OptionSet($select=Options) -> 404+ 1x GET /EntityDefinitions(LogicalName='contoso_project')/Attributes/Microsoft.Dynamics.CRM.StatusAttributeMetadata?$select=LogicalName&$expand=OptionSet($select=Options) -> 404+ 2x GET /EntityDefinitions(LogicalName='contoso_project')/OneToManyRelationships?$select=SchemaName,ReferencingEntity,ReferencingAttribute -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_project')?$select=EntitySetName -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_project')?$select=LogicalName,EntitySetName&$expand=Keys($select=SchemaName,KeyAttributes) -> 404+ 1x GET /EntityDefinitions(LogicalName='contoso_tag')?$select=LogicalName,EntitySetName -> 404+ 1x GET /EntityDefinitions(LogicalName='contoso_task') -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_task')/ManyToManyRelationships?$select=SchemaName,Entity1LogicalName,Entity2LogicalName,IntersectEntityName,Entity1IntersectAttribute,Entity2IntersectAttribute -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_task')?$select=EntitySetName -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_task')?$select=LogicalName,EntitySetName -> 404+ 1x GET /EntityDefinitions(LogicalName='publisher')?$select=EntitySetName -> 200+ 1x GET /EntityDefinitions(LogicalName='solution')?$select=EntitySetName -> 200+ 1x GET /EntityDefinitions(LogicalName='webresource')?$select=EntitySetName -> 200+ 1x GET /GlobalOptionSetDefinitions(Name='contoso_stage')?$select=MetadataId -> 404+ 1x GET /appmodules?$select=appmoduleid&$filter=uniquename eq 'contoso_kitchensink'&$top=1 -> 200+ 1x GET /contoso_projects?$select=contoso_name,contoso_projectid&$filter=contoso_name eq 'Apollo'&$top=5000 -> 200+ 1x GET /contoso_tasks?$select=contoso_title,contoso_taskid&$filter=contoso_title eq 'Kickoff'&$top=5000 -> 200+ 1x GET /publishers?$select=publisherid&$filter=customizationprefix eq 'contoso'&$top=1 -> 200+ 2x GET /solutions?$select=solutionid&$filter=uniquename eq 'ContosoKitchen'&$top=1 -> 200+ 1x GET /webresourceset?$select=webresourceid,content&$filter=name eq 'contoso_project.js'&$top=1 -> 200+ 1x POST /$batch -> 200+ > POST /EntityDefinitions(LogicalName='contoso_project')/Attributes #17143fc8+ > POST /EntityDefinitions(LogicalName='contoso_project')/Attributes #78d7bbae+ > POST /EntityDefinitions(LogicalName='contoso_project')/Attributes #3b86689e+ > POST /EntityDefinitions(LogicalName='contoso_project')/Attributes #3b86689e+ > POST /EntityDefinitions(LogicalName='contoso_project')/Attributes #7d59d525+ > POST /EntityDefinitions(LogicalName='contoso_project')/Attributes #3fa06a81+ > POST /EntityDefinitions(LogicalName='contoso_project')/Attributes #4940b353+ > POST /EntityDefinitions(LogicalName='contoso_project')/Attributes #0207ffd9+ > POST /EntityDefinitions(LogicalName='contoso_project')/Attributes #85166fac+ > POST /EntityDefinitions(LogicalName='contoso_project')/Attributes #83dcbd6c+ > POST /EntityDefinitions(LogicalName='contoso_project')/Attributes #83dcbd6c+ > POST /EntityDefinitions(LogicalName='contoso_project')/Attributes #85806883+ 1x POST /$batch -> 200+ > POST /EntityDefinitions(LogicalName='contoso_task')/Attributes #0207ffd9+ > POST /EntityDefinitions(LogicalName='contoso_task')/Attributes #7d59d525+ 1x POST /CreateCustomerRelationships #e32dd0e5 -> 200+ 3x POST /EntityDefinitions #1b412e8a -> 204+ 1x POST /EntityDefinitions(LogicalName='contoso_project')/Attributes #53686b0d -> 204+ 1x POST /EntityDefinitions(LogicalName='contoso_project')/Attributes #99efb92e -> 204+ 1x POST /EntityDefinitions(LogicalName='contoso_project')/Attributes #fab2e725 -> 204+ 1x POST /EntityDefinitions(LogicalName='contoso_project')/Keys #e84db148 -> 204+ 1x POST /GlobalOptionSetDefinitions #4898eb8f -> 204+ 1x POST /InsertStatusValue #0bad973f -> 200+ 1x POST /PublishXml #1b71745d -> 204+ 1x POST /RelationshipDefinitions #2770187f -> 204+ 2x POST /RelationshipDefinitions #6f73d760 -> 204+ 1x POST /contoso_projects/Microsoft.Dynamics.CRM.CreateMultiple #e95a897a -> 200+ 1x POST /contoso_tasks/Microsoft.Dynamics.CRM.CreateMultiple #e75eb5e5 -> 200+ 1x POST /publishers #4c52dd4a -> 204+ 1x POST /solutions #1a52c2ed -> 204+ 1x POST /webresourceset #7d3c3d0e -> 204+ 1x PUT /EntityDefinitions(<id>) #2b71ae7d -> 204+## up to publish 2: importexportxml(webresources(webresource=#id))+ 1x GET /webresourceset(<id>)?$select=content -> 200+ 1x GET /webresourceset?$select=webresourceid,content&$filter=name eq 'contoso_projecticon.svg'&$top=1 -> 200+ 1x POST /AddSolutionComponent #c1ba6652 -> 200+ 1x POST /PublishXml #1b71745d -> 204+ 1x POST /webresourceset #7d3c3d0e -> 204+## up to publish 3: importexportxml(entities(entity=contoso_project))+ 1x GET /EntityDefinitions(LogicalName='contoso_project') -> 200+ 1x GET /webresourceset(<id>)?$select=content -> 200+ 1x POST /AddSolutionComponent #c1ba6652 -> 200+ 1x POST /PublishXml #1b71745d -> 204+ 1x PUT /EntityDefinitions(<id>) #d6b4b26e -> 204+## up to publish 4: importexportxml(webresources(webresource=#id))+ 1x GET /EntityDefinitions(LogicalName='appaction')?$select=EntitySetName -> 200+ 1x GET /EntityDefinitions(LogicalName='contact')?$select=MetadataId,EntitySetName -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_project')/Attributes/Microsoft.Dynamics.CRM.MultiSelectPicklistAttributeMetadata?$select=LogicalName&$expand=OptionSet($select=Options) -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_project')/Attributes/Microsoft.Dynamics.CRM.PicklistAttributeMetadata?$select=LogicalName&$expand=OptionSet($select=Options) -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_project')/Attributes/Microsoft.Dynamics.CRM.StateAttributeMetadata?$select=LogicalName&$expand=OptionSet($select=Options) -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_project')/Attributes/Microsoft.Dynamics.CRM.StatusAttributeMetadata?$select=LogicalName&$expand=OptionSet($select=Options) -> 200+ 2x GET /EntityDefinitions(LogicalName='contoso_project')/Attributes?$select=LogicalName,AttributeType,DisplayName&$filter=LogicalName eq 'contoso_name' or LogicalName eq 'contoso_email' or LogicalName eq 'contoso_notes' or LogicalName eq 'contoso_priority' or LogicalName eq 'contoso_stage' or LogicalName eq 'contoso_labels' or LogicalName eq 'contoso_billable' or LogicalName eq 'contoso_budget' or LogicalName eq 'contoso_due' or LogicalName eq 'contoso_headcount' or LogicalName eq 'contoso_rate' or LogicalName eq 'contoso_score' or LogicalName eq 'contoso_ref' or LogicalName eq 'contoso_contract' or LogicalName eq 'contoso_logo' or LogicalName eq 'contoso_parentprojectid' -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_project')?$select=MetadataId -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_project')?$select=ObjectTypeCode -> 200+ 2x GET /EntityDefinitions(LogicalName='contoso_task')/Attributes?$select=LogicalName,AttributeType,DisplayName&$filter=LogicalName eq 'contoso_title' or LogicalName eq 'contoso_hours' or LogicalName eq 'contoso_done' or LogicalName eq 'contoso_projectid' -> 200+ 2x GET /EntityDefinitions(LogicalName='contoso_task')?$select=ObjectTypeCode -> 200+ 3x GET /EntityDefinitions(LogicalName='savedquery')?$select=EntitySetName -> 200+ 1x GET /EntityDefinitions(LogicalName='savedqueryvisualization')?$select=EntitySetName -> 200+ 4x GET /EntityDefinitions(LogicalName='systemform')?$select=EntitySetName -> 200+ 1x GET /appactions?$select=appactionid,buttonlabeltext&$filter=contextvalue eq 'contoso_project'&$top=1 -> 200+ 4x GET /savedqueries(<id>)/Microsoft.Dynamics.CRM.RetrieveUnpublished()?$select=savedqueryid,name,description,fetchxml,layoutxml,querytype,returnedtypecode,isdefault -> 200+ 4x GET /savedqueries(<id>)?$select=savedqueryid -> 200+ 1x GET /savedqueries?$select=savedqueryid&$filter=returnedtypecode eq 'contoso_project' and name eq 'Open Projects'&$top=2 -> 200+ 1x GET /savedqueries?$select=savedqueryid&$filter=returnedtypecode eq 'contoso_task' and name eq 'My Open Tasks'&$top=2 -> 200+ 1x GET /savedqueries?$select=savedqueryid&$filter=returnedtypecode eq 'contoso_task' and name eq 'Open Tasks'&$top=2 -> 200+ 1x GET /savedqueries?$select=savedqueryid,name,canbedeleted,fetchxml,createdon&$filter=returnedtypecode eq 'contoso_project' and querytype eq 0 -> 200+ 1x GET /savedqueries?$select=savedqueryid,name,canbedeleted,fetchxml,createdon&$filter=returnedtypecode eq 'contoso_task' and querytype eq 0 -> 200+ 1x GET /savedqueryvisualizations?$select=savedqueryvisualizationid&$filter=primaryentitytypecode eq 'contoso_project' and name eq 'Projects by Priority'&$top=2 -> 200+ 4x GET /systemforms(<id>)/Microsoft.Dynamics.CRM.RetrieveUnpublished()?$select=formid,formxml,name,type,objecttypecode,formpresentation,formactivationstate,uniquename,description,versionnumber -> 200+ 4x GET /systemforms(<id>)/Microsoft.Dynamics.CRM.RetrieveUnpublished()?$select=formid,formxml,type -> 200+ 2x GET /systemforms(<id>)/Microsoft.Dynamics.CRM.RetrieveUnpublished()?$select=formid,type -> 200+ 3x GET /systemforms(<id>)?$select=formid -> 200+ 1x GET /systemforms?$select=formid&$filter=objecttypecode eq 'contoso_project' and name eq 'Project Card' and type eq 6&$top=2 -> 200+ 1x GET /systemforms?$select=formid&$filter=objecttypecode eq 'contoso_project' and name eq 'Project' and type eq 2&$top=2 -> 200+ 1x GET /systemforms?$select=formid&$filter=objecttypecode eq 'contoso_task' and name eq 'Task Quick Create' and type eq 7&$top=2 -> 200+ 1x GET /systemforms?$select=formid&$filter=objecttypecode eq 'contoso_task' and name eq 'Task' and type eq 2&$top=2 -> 200+ 1x GET /systemforms?$select=formid,name&$filter=name eq 'Kitchen Overview' and type eq 0&$top=10 -> 200+ 1x GET /systemforms?$select=formid,name&$filter=objecttypecode eq 'contoso_task' and type eq 2 and formactivationstate eq 1&$top=250 -> 200+ 1x GET /webresourceset?$select=webresourceid&$filter=name eq 'contoso_kitchensink_icon'&$top=1 -> 200+ 4x PATCH /savedqueries(<id>)?$select=savedqueryid #97e1522c -> 200+ 2x PATCH /systemforms(<id>) #9bb0a025 -> 204+ 1x PATCH /systemforms(<id>) #e39def73 -> 204+ 1x PATCH /systemforms(<id>)?$select=formid #bb920f89 -> 200+ 1x PATCH /systemforms(<id>)?$select=formid #e0abe8e4 -> 200+ 9x POST /AddSolutionComponent #c1ba6652 -> 200+ 1x POST /PublishXml #1b71745d -> 204+ 1x POST /appactions?$select=appactionid #02a1c789 -> 201+ 1x POST /appactions?$select=appactionid #37081196 -> 201+ 1x POST /appactions?$select=appactionid #e34f0019 -> 201+ 1x POST /appactions?$select=appactionid #eaa4807c -> 201+ 3x POST /savedqueries?$select=savedqueryid #3afc734a -> 201+ 1x POST /savedqueryvisualizations?$select=savedqueryvisualizationid #360d4c1c -> 201+ 3x POST /systemforms?$select=formid #05f7c2f8 -> 201+ 1x POST /systemforms?$select=formid #9d0094e8 -> 201+ 1x POST /systemforms?$select=formid #d59ac10f -> 201+ 1x POST /webresourceset #7d3c3d0e -> 204+## up to publish 5: importexportxml(entities(entity=contoso_project entity=contoso_tag entity=contoso_task))+ 1x GET /appmodules?$select=appmoduleid&$filter=uniquename eq 'contoso_kitchensink'&$top=1 -> 200+ 1x GET /webresourceset(<id>)?$select=content -> 200+ 1x POST /AddSolutionComponent #c1ba6652 -> 200+ 1x POST /PublishXml #1b71745d -> 204+## up to publish 6: importexportxml(appmodules(appmodule=#id))+ 1x GET /EntityDefinitions(LogicalName='contoso_project')?$select=MetadataId,EntitySetName -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_tag')?$select=MetadataId,EntitySetName -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_task')?$select=MetadataId,EntitySetName -> 200+ 1x GET /appmodulecomponents?$select=objectid,componenttype&$filter=_appmoduleidunique_value eq <id> and componenttype eq 1 -> 200+ 1x GET /appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()?$select=appmoduleid,appmoduleidunique,componentstate&$filter=appmoduleid eq <id> -> 200+ 1x GET /appsettings/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()?$select=appsettingid,value&$filter=_parentappmoduleid_value eq <id> and _settingdefinitionid_value eq <id> -> 200+ 1x GET /roles?$select=roleid,_parentrootroleid_value&$filter=_roletemplateid_value eq <id> -> 200+ 1x GET /savedqueries?$select=savedqueryid&$filter=returnedtypecode eq 'contoso_project' and querytype eq 0 and statecode eq 0 -> 200+ 1x GET /savedqueries?$select=savedqueryid&$filter=returnedtypecode eq 'contoso_tag' and querytype eq 0 and statecode eq 0 -> 200+ 1x GET /savedqueries?$select=savedqueryid&$filter=returnedtypecode eq 'contoso_task' and querytype eq 0 and statecode eq 0 -> 200+ 1x GET /savedqueryvisualizations?$select=savedqueryvisualizationid&$filter=primaryentitytypecode eq 'contoso_project' -> 200+ 1x GET /savedqueryvisualizations?$select=savedqueryvisualizationid&$filter=primaryentitytypecode eq 'contoso_tag' -> 200+ 1x GET /savedqueryvisualizations?$select=savedqueryvisualizationid&$filter=primaryentitytypecode eq 'contoso_task' -> 200+ 1x GET /settingdefinitions?$select=settingdefinitionid,uniquename,displayname&$filter=uniquename eq 'HeaderAndNavigationRefresh' -> 200+ 1x GET /systemforms?$select=formid&$filter=objecttypecode eq 'contoso_project' and type eq 2 and formactivationstate eq 1 -> 200+ 1x GET /systemforms?$select=formid&$filter=objecttypecode eq 'contoso_tag' and type eq 2 and formactivationstate eq 1 -> 200+ 1x GET /systemforms?$select=formid&$filter=objecttypecode eq 'contoso_task' and type eq 2 and formactivationstate eq 1 -> 200+ 1x POST /AddAppComponents #e1de4e0e -> 204+ 1x POST /PublishXml #1b71745d -> 204+ 1x POST /appmodules #b3f86741 -> 204+ 1x POST /appmodules(<id>)/appmoduleroles_association/$ref #f07e5c5f -> 204+ 1x POST /appsettings #1c3b649b -> 204+ 1x POST /sitemaps?$select=sitemapid #c4c362c9 -> 201+## up to publish 7: importexportxml(appmodules(appmodule=#id))+ 1x GET /EntityDefinitions(LogicalName='sitemap')?$select=EntitySetName -> 200+ 2x GET /appmodulecomponents?$select=objectid,componenttype&$filter=_appmoduleidunique_value eq <id> and componenttype eq 1 -> 200+ 1x GET /appmodules(<id>)?$select=appmoduleid -> 200+ 2x GET /appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()?$select=appmoduleid,appmoduleidunique,componentstate&$filter=appmoduleid eq <id> -> 200+ 1x GET /sitemaps?$select=sitemapid&$filter=sitemapnameunique eq 'contoso_kitchensink'&$top=1 -> 200+ 1x POST /AddAppComponents #390f6b73 -> 204+ 2x POST /AddSolutionComponent #c1ba6652 -> 200+ 1x POST /PublishXml #1b71745d -> 204+## up to publish 8: importexportxml(uxagentprojects(uxagentproject=#id))+ 1x GET /EntityDefinitions(LogicalName='appmodulecomponent')?$select=EntitySetName -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_project')/Attributes/Microsoft.Dynamics.CRM.BooleanAttributeMetadata?$select=LogicalName&$expand=OptionSet($select=TrueOption,FalseOption) -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_project')/Attributes/Microsoft.Dynamics.CRM.LookupAttributeMetadata?$select=LogicalName,Targets -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_project')/Attributes/Microsoft.Dynamics.CRM.MultiSelectPicklistAttributeMetadata?$select=LogicalName&$expand=OptionSet($select=Options) -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_project')/Attributes/Microsoft.Dynamics.CRM.PicklistAttributeMetadata?$select=LogicalName&$expand=OptionSet($select=Options) -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_project')/Attributes/Microsoft.Dynamics.CRM.StateAttributeMetadata?$select=LogicalName&$expand=OptionSet($select=Options) -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_project')/Attributes/Microsoft.Dynamics.CRM.StatusAttributeMetadata?$select=LogicalName&$expand=OptionSet($select=Options) -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_project')/Attributes/Microsoft.Dynamics.CRM.StringAttributeMetadata?$select=LogicalName,MaxLength -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_project')/ManyToManyRelationships?$select=SchemaName,Entity1LogicalName,Entity2LogicalName -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_project')/ManyToOneRelationships?$select=SchemaName,ReferencedEntity,ReferencedAttribute -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_project')/OneToManyRelationships?$select=SchemaName,ReferencingEntity,ReferencingAttribute -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_project')?$select=LogicalName,SchemaName,DisplayName,Description,EntitySetName,IsCustomEntity,PrimaryNameAttribute,PrimaryIdAttribute,PrimaryImageAttribute&$expand=Attributes($select=LogicalName,DisplayName,Description,AttributeType,AttributeTypeName,IsCustomAttribute,IsValidForUpdate,IsValidForRead,AttributeOf) -> 200+ 1x GET /EntityDefinitions(LogicalName='uxagentproject')?$select=ObjectTypeCode -> 200+ 1x GET /appmodulecomponents?$select=objectid,componenttype&$filter=_appmoduleidunique_value eq <id> and componenttype eq 62&$top=1 -> 200+ 1x GET /appmodules?$select=appmoduleid,appmoduleidunique&$filter=uniquename eq 'contoso_kitchensink'&$top=1 -> 200+ 1x GET /sitemaps?$select=sitemapxml&$filter=sitemapid eq <id>&$top=1 -> 200+ 5x GET /uxagentprojectfiles(<id>)/filecontent/$value -> 200+ 3x GET /uxagentprojectfiles?$select=uxagentprojectfileid,filename,filetype&$filter=_uxagentprojectid_value eq <id> -> 200+ 2x GET /uxagentprojects(<id>)?$select=uxagentprojectid,name -> 200+ 1x GET /uxagentprojects?$select=uxagentprojectid,name -> 200+ 1x GET /webresourceset?$select=webresourceid,content&$filter=name eq 'contoso_kitchensink_pagemanifest'&$top=1 -> 200+ 1x POST /$batch -> 200+ > POST /uxagentprojects #0bca3f5e+ > POST /uxagentprojectfiles #f3dc5825+ > PATCH /uxagentprojectfiles(<id>)/filecontent #473287f8+ > POST /uxagentprojectfiles #f3dc5825+ > PATCH /uxagentprojectfiles(<id>)/filecontent #473287f8+ > POST /uxagentprojectfiles #f3dc5825+ > PATCH /uxagentprojectfiles(<id>)/filecontent #473287f8+ > POST /uxagentprojectfiles #f3dc5825+ > PATCH /uxagentprojectfiles(<id>)/filecontent #473287f8+ > PATCH /uxagentprojects(<id>) #8e40ff9d+ > POST /agentconversationmessages #43dbd5f4+ > POST /agentconversationmessages #43dbd5f4+ 1x POST /PublishXml #1b71745d -> 204+## up to publish 9: importexportxml(webresources(webresource=#id))+ 8x GET /uxagentprojectfiles(<id>)/filecontent/$value -> 200+ 3x GET /uxagentprojectfiles?$select=uxagentprojectfileid,filename,filetype&$filter=_uxagentprojectid_value eq <id> -> 200+ 3x GET /uxagentprojects(<id>)?$select=uxagentprojectid,name -> 200+ 1x POST /PublishXml #1b71745d -> 204+ 1x POST /webresourceset #7d3c3d0e -> 204+## up to publish 10: importexportxml(appmodules(appmodule=#id))+ 1x GET /EntityDefinitions(LogicalName='solutioncomponent')?$select=EntitySetName -> 200+ 1x GET /EntityDefinitions(LogicalName='uxagentproject')?$select=EntitySetName -> 200+ 1x GET /EntityDefinitions(LogicalName='uxagentprojectfile')?$select=EntitySetName -> 200+ 5x GET /appmodulecomponents?$select=objectid&$filter=_appmoduleidunique_value eq <id> and componenttype eq 62 -> 200+ 1x GET /appmodulecomponents?$select=objectid,componenttype&$filter=_appmoduleidunique_value eq <id> -> 200+ 1x GET /appmodulecomponents?$select=objectid,componenttype&$filter=_appmoduleidunique_value eq <id> and componenttype eq 1 -> 200+ 3x GET /appmodules(<id>)?$select=appmoduleid -> 200+ 7x GET /appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()?$select=appmoduleid,appmoduleidunique,componentstate&$filter=appmoduleid eq <id> -> 200+ 3x GET /appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()?$select=appmoduleid,name,uniquename,description,aiappdescription&$filter=appmoduleid eq <id>&$top=1 -> 200+ 1x GET /savedqueries?$select=savedqueryid&$filter=returnedtypecode eq 'contoso_project' and querytype eq 0 and statecode eq 0 -> 200+ 1x GET /savedqueries?$select=savedqueryid&$filter=returnedtypecode eq 'contoso_tag' and querytype eq 0 and statecode eq 0 -> 200+ 1x GET /savedqueries?$select=savedqueryid&$filter=returnedtypecode eq 'contoso_task' and querytype eq 0 and statecode eq 0 -> 200+ 1x GET /savedqueryvisualizations?$select=savedqueryvisualizationid&$filter=primaryentitytypecode eq 'contoso_project' -> 200+ 1x GET /savedqueryvisualizations?$select=savedqueryvisualizationid&$filter=primaryentitytypecode eq 'contoso_tag' -> 200+ 1x GET /savedqueryvisualizations?$select=savedqueryvisualizationid&$filter=primaryentitytypecode eq 'contoso_task' -> 200+ 2x GET /sitemaps(<id>)?$select=sitemapid -> 200+ 2x GET /sitemaps/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()?$select=sitemapid,sitemapname,sitemapnameunique,sitemapxml&$filter=sitemapid eq <id>&$top=1 -> 200+ 1x GET /solutioncomponents?$select=objectid,componenttype,rootcomponentbehavior&$filter=_solutionid_value eq <id> and (componenttype eq 26 or componenttype eq 59 or componenttype eq 60 or componenttype eq 61 or componenttype eq 62 or componenttype eq 80 or componenttype eq 20 or componenttype eq 29 or componenttype eq 1) -> 200+ 1x GET /solutions?$select=solutionid&$filter=uniquename eq 'ContosoKitchen'&$top=1 -> 200+ 1x GET /systemforms?$select=formid&$filter=objecttypecode eq 'contoso_project' and type eq 2 and formactivationstate eq 1 -> 200+ 1x GET /systemforms?$select=formid&$filter=objecttypecode eq 'contoso_tag' and type eq 2 and formactivationstate eq 1 -> 200+ 1x GET /systemforms?$select=formid&$filter=objecttypecode eq 'contoso_task' and type eq 2 and formactivationstate eq 1 -> 200+ 3x GET /uxagentprojectfiles(<id>)/filecontent/$value -> 200+ 1x GET /uxagentprojectfiles?$select=uxagentprojectfileid,filename,filetype&$filter=_uxagentprojectid_value eq <id> -> 200+ 2x GET /uxagentprojectfiles?$select=uxagentprojectfileid,versionnumber,_uxagentprojectid_value&$filter=_uxagentprojectid_value eq <id> -> 200+ 1x GET /uxagentprojects(<id>)?$select=uxagentprojectid,name -> 200+ 1x GET /uxagentprojects/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()?$select=uxagentprojectid&$filter=uxagentprojectid eq <id> -> 200+ 2x GET /uxagentprojects?$select=uxagentprojectid,versionnumber&$filter=uxagentprojectid eq <id> -> 200+ 1x GET /webresourceset(<id>)?$select=content -> 200+ 1x PATCH /sitemaps(<id>)?$select=sitemapid #a48e6542 -> 200+ 1x POST /AddAppComponents #55bd8832 -> 204+ 2x POST /AddSolutionComponent #c1ba6652 -> 200+ 1x POST /PublishXml #1b71745d -> 204+## up to publish 11: importexportxml(appmodules(appmodule=#id) entities(entity=contoso_project entity=contoso_task))+ 1x GET /EntityDefinitions(LogicalName='appmodule')?$select=LogicalName,Privileges -> 200+ 1x GET /EntityDefinitions(LogicalName='appmodulecomponent')?$select=EntitySetName -> 200+ 1x GET /EntityDefinitions(LogicalName='businessunit')?$select=EntitySetName -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_project')?$select=LogicalName,Privileges -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_tag')?$select=LogicalName,Privileges -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_task')?$select=LogicalName,Privileges -> 200+ 1x GET /EntityDefinitions(LogicalName='role')?$select=EntitySetName -> 200+ 1x GET /EntityDefinitions(LogicalName='savedquery')?$select=EntitySetName -> 200+ 4x GET /appmodulecomponents?$select=objectid&$filter=_appmoduleidunique_value eq <id> and componenttype eq 62 -> 200+ 1x GET /appmodulecomponents?$select=objectid,componenttype&$filter=_appmoduleidunique_value eq <id> and componenttype eq 26 -> 200+ 2x GET /appmodules(<id>)?$select=appmoduleid -> 200+ 5x GET /appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()?$select=appmoduleid,appmoduleidunique,componentstate&$filter=appmoduleid eq <id> -> 200+ 2x GET /appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()?$select=appmoduleid,name,uniquename,description,aiappdescription&$filter=appmoduleid eq <id>&$top=1 -> 200+ 1x GET /appsettings/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()?$select=appsettingid,value&$filter=_parentappmoduleid_value eq <id> and _settingdefinitionid_value eq <id> -> 200+ 2x GET /businessunits?$select=businessunitid&$filter=_parentbusinessunitid_value eq null&$top=1 -> 200+ 1x GET /roles?$select=roleid,description,ismanaged&$filter=name eq 'Kitchen Planner' and _businessunitid_value eq <id> -> 200+ 1x GET /roles?$select=roleid,name,ismanaged&$filter=name eq 'Basic User' and _businessunitid_value eq <id>&$top=5 -> 200+ 7x GET /savedqueries(<id>)/Microsoft.Dynamics.CRM.RetrieveUnpublished()?$select=savedqueryid,name,description,fetchxml,layoutxml,querytype,returnedtypecode,isdefault -> 200+ 7x GET /savedqueries(<id>)?$select=savedqueryid -> 200+ 1x GET /savedqueries?$select=savedqueryid&$filter=returnedtypecode eq 'contoso_project' and querytype eq 0 and isdefault eq true&$top=1 -> 200+ 1x GET /savedqueryvisualizations(<id>)/Microsoft.Dynamics.CRM.RetrieveUnpublished()?$select=savedqueryvisualizationid,name,description,primaryentitytypecode,datadescription,presentationdescription,charttype,type,isdefault -> 200+ 1x GET /savedqueryvisualizations(<id>)?$select=savedqueryvisualizationid -> 200+ 1x GET /settingdefinitions?$select=settingdefinitionid,uniquename,displayname&$filter=uniquename eq 'HeaderAndNavigationRefresh' -> 200+ 2x GET /sitemaps(<id>)?$select=sitemapid -> 200+ 2x GET /sitemaps/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()?$select=sitemapid,sitemapname,sitemapnameunique,sitemapxml&$filter=sitemapid eq <id>&$top=1 -> 200+ 4x GET /systemforms(<id>)/Microsoft.Dynamics.CRM.RetrieveUnpublished()?$select=formid,formxml,name,type,objecttypecode,formpresentation,formactivationstate,uniquename,description,versionnumber -> 200+ 2x GET /systemforms(<id>)/Microsoft.Dynamics.CRM.RetrieveUnpublished()?$select=formid,formxml,type -> 200+ 1x GET /systemforms(<id>)?$select=formid -> 200+ 1x PATCH /appsettings(<id>) #7a0f420e -> 204+ 1x PATCH /systemforms(<id>) #e39def73 -> 204+ 1x POST /AddSolutionComponent #c1ba6652 -> 200+ 1x POST /PublishXml #1b71745d -> 204+ 1x POST /SaveSettingValue #9bbb6c67 -> 204+ 1x POST /appmodules(<id>)/appmoduleroles_association/$ref #f07e5c5f -> 204+ 1x POST /roles #d13e24c0 -> 204+ 1x POST /roles(<id>)/Microsoft.Dynamics.CRM.AddPrivilegesRole #497ea01a -> 204+ 1x POST /roles(<id>)/Microsoft.Dynamics.CRM.ReplacePrivilegesRole #20224ada -> 204+## after the last publish+ 1x GET /EntityDefinitions(LogicalName='contact')?$select=MetadataId -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_project')/Attributes/Microsoft.Dynamics.CRM.MultiSelectPicklistAttributeMetadata?$select=LogicalName&$expand=OptionSet($select=Options) -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_project')/Attributes/Microsoft.Dynamics.CRM.PicklistAttributeMetadata?$select=LogicalName&$expand=OptionSet($select=Options) -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_project')/Attributes/Microsoft.Dynamics.CRM.StateAttributeMetadata?$select=LogicalName&$expand=OptionSet($select=Options) -> 200+ 2x GET /EntityDefinitions(LogicalName='contoso_project')/Attributes/Microsoft.Dynamics.CRM.StatusAttributeMetadata?$select=LogicalName&$expand=OptionSet($select=Options) -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_project')/Attributes?$select=LogicalName,SchemaName,DisplayName,AttributeType,IsCustomAttribute -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_project')/Keys?$select=LogicalName,SchemaName,KeyAttributes -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_project')/ManyToManyRelationships?$select=SchemaName,Entity1LogicalName,Entity2LogicalName,IntersectEntityName,Entity1IntersectAttribute,Entity2IntersectAttribute -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_project')/ManyToOneRelationships?$select=SchemaName,ReferencedEntity,ReferencingAttribute -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_project')?$select=MetadataId -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_tag')/Attributes?$select=LogicalName,SchemaName,DisplayName,AttributeType,IsCustomAttribute -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_tag')?$select=MetadataId -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_task')/Attributes?$select=LogicalName,SchemaName,DisplayName,AttributeType,IsCustomAttribute -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_task')/ManyToManyRelationships?$select=SchemaName,Entity1LogicalName,Entity2LogicalName,IntersectEntityName,Entity1IntersectAttribute,Entity2IntersectAttribute -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_task')/ManyToOneRelationships?$select=SchemaName,ReferencedEntity,ReferencingAttribute -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_task')?$select=MetadataId -> 200+ 1x GET /EntityDefinitions(LogicalName='entity')?$select=MetadataId -> 404+ 1x GET /EntityDefinitions(LogicalName='roleprivileges')?$select=EntitySetName -> 200+ 1x GET /EntityDefinitions?$select=LogicalName,SchemaName,EntitySetName,DisplayName,IsCustomEntity -> 200+ 1x GET /WhoAmI -> 200+ 1x GET /appactions?$select=appactionid,buttonlabeltext&$filter=contextvalue eq 'contoso_project'&$top=1 -> 200+ 1x GET /appmodulecomponents?$select=objectid,componenttype&$filter=_appmoduleidunique_value eq <id> and componenttype eq 1 -> 200+ 1x GET /appmodulecomponents?$select=objectid,componenttype&$filter=_appmoduleidunique_value eq <id> and componenttype eq 62&$top=1 -> 200+ 1x GET /appmodules(<id>)/appmoduleroles_association?$select=roleid -> 200+ 1x GET /appmodules?$select=appmoduleid&$filter=uniquename eq 'contoso_kitchensink'&$top=1 -> 200+ 2x GET /appmodules?$select=appmoduleid,appmoduleidunique&$filter=uniquename eq 'contoso_kitchensink'&$top=1 -> 200+ 1x GET /businessunits?$select=businessunitid&$filter=_parentbusinessunitid_value eq null&$top=1 -> 200+ 2x GET /roleprivilegescollection?$select=privilegeid,privilegedepthmask&$filter=roleid eq <id> -> 200+ 1x GET /roles?$select=roleid,description,ismanaged&$filter=name eq 'Kitchen Planner' and _businessunitid_value eq <id>&$top=5 -> 200+ 1x GET /roles?$select=roleid,name&$filter=name eq 'Basic User' and _businessunitid_value eq <id>&$top=5 -> 200+ 1x GET /savedqueries?$select=returnedtypecode&$filter=savedqueryid eq <id>&$top=1 -> 200+ 1x GET /savedqueries?$select=savedqueryid,layoutxml,fetchxml&$filter=returnedtypecode eq 'contoso_project' and name eq 'Open Projects'&$top=1 -> 200+ 1x GET /savedqueries?$select=savedqueryid,layoutxml,fetchxml&$filter=returnedtypecode eq 'contoso_task' and name eq 'My Open Tasks'&$top=1 -> 200+ 1x GET /savedqueries?$select=savedqueryid,layoutxml,fetchxml&$filter=returnedtypecode eq 'contoso_task' and name eq 'Open Tasks'&$top=1 -> 200+ 1x GET /savedqueryvisualizations?$select=primaryentitytypecode&$filter=savedqueryvisualizationid eq <id>&$top=1 -> 200+ 1x GET /savedqueryvisualizations?$select=savedqueryvisualizationid&$filter=primaryentitytypecode eq 'contoso_project' and name eq 'Projects by Priority'&$top=1 -> 200+ 1x GET /sitemaps?$select=sitemapxml&$filter=sitemapid eq <id>&$top=1 -> 200+ 1x GET /systemforms(<id>)/Microsoft.Dynamics.CRM.RetrieveUnpublished()?$select=formid,name,description,formxml,type,objecttypecode,istabletenabled,iscustomizable,componentstate,versionnumber -> 200+ 2x GET /systemforms(<id>)/Microsoft.Dynamics.CRM.RetrieveUnpublished()?$select=formxml -> 200+ 1x GET /systemforms/Microsoft.Dynamics.CRM.RetrieveFilteredForms(EntityLogicalName=@e,FormType=@t,User=@u)?@e='contoso_task'&@t=2&@u={'@odata.id':'systemusers(<id>)'} -> 200+ 2x GET /systemforms?$select=formid&$filter=objecttypecode eq 'contoso_project' and name eq 'Project Card' and type eq 6&$top=2 -> 200+ 2x GET /systemforms?$select=formid&$filter=objecttypecode eq 'contoso_project' and name eq 'Project' and type eq 2&$top=2 -> 200+ 2x GET /systemforms?$select=formid&$filter=objecttypecode eq 'contoso_task' and name eq 'Task Quick Create' and type eq 7&$top=2 -> 200+ 2x GET /systemforms?$select=formid&$filter=objecttypecode eq 'contoso_task' and name eq 'Task' and type eq 2&$top=2 -> 200+ 2x GET /systemforms?$select=formid,formxml&$filter=formid eq <id>&$top=1 -> 200+ 4x GET /systemforms?$select=formid,isdefault,formxml&$filter=formid eq <id>&$top=1 -> 200+ 1x GET /systemforms?$select=formid,name&$filter=objecttypecode eq 'contoso_task' and type eq 2&$top=250 -> 200+ 1x GET /systemforms?$select=formid,name&$filter=type eq 0 and name eq 'Kitchen Overview' -> 200+ 1x GET /uxagentprojects?$select=uxagentprojectid,name -> 200+ 1x GET /webresourceset?$select=content&$filter=name eq 'contoso_kitchensink_pagemanifest'&$top=1 -> 200+ 1x GET /webresourceset?$select=webresourceid,content&$filter=name eq 'contoso_project.js'&$top=1 -> 200+ 1x GET /webresourceset?$select=webresourceid,content&$filter=name eq 'contoso_projecticon.svg'&$top=1 -> 200+# shapes+#0207ffd9 {@odata.type:string,AttributeType:string,AttributeTypeName:{Value:string},DisplayName:{@odata.type:string,LocalizedLabels:[1x{@odata.type:string,Label:string,LanguageCode:number}]},Format:string,MaxValue:number,MinValue:number,RequiredLevel:{CanBeChanged:boolean,ManagedPropertyLogicalName:string,Value:string},SchemaName:string}+#02a1c789 {[email protected]:string,appactionid:string,buttonlabeltext:string,context:number,contextvalue:string,location:number,name:string,sequence:number,type:number,uniquename:string}+#05f7c2f8 {formid:string,formxml:string,name:string,objecttypecode:string,type:number}+#0bad973f {AttributeLogicalName:string,EntityLogicalName:string,Label:{@odata.type:string,LocalizedLabels:[1x{@odata.type:string,Label:string,LanguageCode:number}]},StateCode:number,Value:number}+#0bca3f5e {name:string,uxagentprojectid:string}+#17143fc8 {@odata.type:string,AttributeType:string,AttributeTypeName:{Value:string},DisplayName:{@odata.type:string,LocalizedLabels:[1x{@odata.type:string,Label:string,LanguageCode:number}]},FormatName:{Value:string},MaxLength:number,RequiredLevel:{CanBeChanged:boolean,ManagedPropertyLogicalName:string,Value:string},SchemaName:string}+#1a52c2ed {description:string,friendlyname:string,[email protected]:string,uniquename:string,version:string}+#1b412e8a {@odata.type:string,Attributes:[1x{@odata.type:string,AttributeType:string,AttributeTypeName:{Value:string},DisplayName:{@odata.type:string,LocalizedLabels:[1x{@odata.type:string,Label:string,LanguageCode:number}]},FormatName:{Value:string},IsPrimaryName:boolean,MaxLength:number,RequiredLevel:{CanBeChanged:boolean,ManagedPropertyLogicalName:string,Value:string},SchemaName:string}],Description:{@odata.type:string,LocalizedLabels:[1x{@odata.type:string,Label:string,LanguageCode:number}]},DisplayCollectionName:{@odata.type:string,LocalizedLabels:[1x{@odata.type:string,Label:string,LanguageCode:number}]},DisplayName:{@odata.type:string,LocalizedLabels:[1x{@odata.type:string,Label:string,LanguageCode:number}]},HasActivities:boolean,HasNotes:boolean,IsActivity:boolean,OwnershipType:string,SchemaName:string}+#1b71745d {ParameterXml:string}+#1c3b649b {[email protected]:string,[email protected]:string,value:string}+#20224ada {Privileges:[5x{Depth:string,PrivilegeId:string}]}+#2770187f {@odata.type:string,Entity1LogicalName:string,Entity2LogicalName:string,IntersectEntityName:string,SchemaName:string}+#2b71ae7d {@odata.type:string,ChangeTrackingEnabled:boolean,CollectionSchemaName:string,Description:{LocalizedLabels:[1x{HasChanged:null,IsManaged:boolean,Label:string,LanguageCode:number,MetadataId:string}],UserLocalizedLabel:{HasChanged:null,IsManaged:boolean,Label:string,LanguageCode:number,MetadataId:string}},DisplayCollectionName:{LocalizedLabels:[1x{HasChanged:null,IsManaged:boolean,Label:string,LanguageCode:number,MetadataId:string}],UserLocalizedLabel:{HasChanged:null,IsManaged:boolean,Label:string,LanguageCode:number,MetadataId:string}},DisplayName:{LocalizedLabels:[1x{HasChanged:null,IsManaged:boolean,Label:string,LanguageCode:number,MetadataId:string}],UserLocalizedLabel:{HasChanged:null,IsManaged:boolean,Label:string,LanguageCode:number,MetadataId:string}},EntitySetName:string,HasActivities:boolean,HasNotes:boolean,IconLargeName:null,IconMediumName:null,IconSmallName:null,IconVectorName:null,IsActivity:boolean,IsCustomEntity:boolean,IsIntersect:boolean,IsManaged:boolean,IsQuickCreateEnabled:boolean,LogicalCollectionName:string,LogicalName:string,MetadataId:string,ObjectTypeCode:number,OwnershipType:string,PrimaryIdAttribute:string,PrimaryImageAttribute:null,PrimaryNameAttribute:string,Privileges:[8x{CanBeBasic:boolean,CanBeDeep:boolean,CanBeEntityReference:boolean,CanBeGlobal:boolean,CanBeLocal:boolean,CanBeParentEntityReference:boolean,Name:string,PrivilegeId:string,PrivilegeType:string}],SchemaName:string,TableType:string}+#360d4c1c {charttype:number,datadescription:string,description:string,isdefault:boolean,name:string,presentationdescription:string,primaryentitytypecode:string,savedqueryvisualizationid:string}+#37081196 {[email protected]:string,[email protected]:string,appactionid:string,buttonlabeltext:string,context:number,contextvalue:string,location:number,name:string,onclickeventjavascriptfunctionname:string,onclickeventjavascriptparameters:string,onclickeventtype:number,sequence:number,type:number,uniquename:string}+#390f6b73 {AppId:string,Components:[1x{@odata.id:string}]}+#3afc734a {description:string,fetchxml:string,isdefault:boolean,layoutxml:string,name:string,querytype:number,returnedtypecode:string,savedqueryid:string}+#3b86689e {@odata.type:string,AttributeType:string,AttributeTypeName:{Value:string},DisplayName:{@odata.type:string,LocalizedLabels:[1x{@odata.type:string,Label:string,LanguageCode:number}]},OptionSet:{@odata.type:string,IsGlobal:boolean,OptionSetType:string,Options:[3x{Label:{@odata.type:string,LocalizedLabels:[1x{@odata.type:string,Label:string,LanguageCode:number}]},Value:number}]},RequiredLevel:{CanBeChanged:boolean,ManagedPropertyLogicalName:string,Value:string},SchemaName:string}+#3fa06a81 {@odata.type:string,AttributeType:string,AttributeTypeName:{Value:string},DisplayName:{@odata.type:string,LocalizedLabels:[1x{@odata.type:string,Label:string,LanguageCode:number}]},MaxValue:number,MinValue:number,Precision:number,PrecisionSource:number,RequiredLevel:{CanBeChanged:boolean,ManagedPropertyLogicalName:string,Value:string},SchemaName:string}+#43dbd5f4 {[email protected]:string,agentconversationmessageid:string,message:string,messagecontext:string,messagesender:number}+#473287f8 string+#4898eb8f {@odata.type:string,DisplayName:{@odata.type:string,LocalizedLabels:[1x{@odata.type:string,Label:string,LanguageCode:number}]},IsGlobal:boolean,Name:string,OptionSetType:string,Options:[3x{Label:{@odata.type:string,LocalizedLabels:[1x{@odata.type:string,Label:string,LanguageCode:number}]},Value:number}]}+#4940b353 {@odata.type:string,AttributeType:string,AttributeTypeName:{Value:string},DateTimeBehavior:{Value:string},DisplayName:{@odata.type:string,LocalizedLabels:[1x{@odata.type:string,Label:string,LanguageCode:number}]},Format:string,RequiredLevel:{CanBeChanged:boolean,ManagedPropertyLogicalName:string,Value:string},SchemaName:string}+#497ea01a {Privileges:[1x{Depth:string,PrivilegeId:string}]}+#4c52dd4a {customizationoptionvalueprefix:number,customizationprefix:string,friendlyname:string,uniquename:string}+#53686b0d {@odata.type:string,AttributeType:string,AttributeTypeName:{Value:string},DisplayName:{@odata.type:string,LocalizedLabels:[1x{@odata.type:string,Label:string,LanguageCode:number}]},MaxSizeInKB:number,RequiredLevel:{CanBeChanged:boolean,ManagedPropertyLogicalName:string,Value:string},SchemaName:string}+#55bd8832 {AppId:string,Components:[3x{@odata.id:string}|6x{@odata.type:string,formid:string}|9x{@odata.type:string,savedqueryid:string}|1x{@odata.type:string,savedqueryvisualizationid:string}]}+#6f73d760 {@odata.type:string,Lookup:{@odata.type:string,AttributeType:string,AttributeTypeName:{Value:string},DisplayName:{@odata.type:string,LocalizedLabels:[1x{@odata.type:string,Label:string,LanguageCode:number}]},RequiredLevel:{CanBeChanged:boolean,ManagedPropertyLogicalName:string,Value:string},SchemaName:string},ReferencedEntity:string,ReferencingEntity:string,SchemaName:string}+#78d7bbae {@odata.type:string,AttributeType:string,AttributeTypeName:{Value:string},DisplayName:{@odata.type:string,LocalizedLabels:[1x{@odata.type:string,Label:string,LanguageCode:number}]},Format:string,MaxLength:number,RequiredLevel:{CanBeChanged:boolean,ManagedPropertyLogicalName:string,Value:string},SchemaName:string}+#7a0f420e {value:string}+#7d3c3d0e {content:string,displayname:string,name:string,webresourcetype:number}+#7d59d525 {@odata.type:string,AttributeType:string,AttributeTypeName:{Value:string},DefaultValue:boolean,DisplayName:{@odata.type:string,LocalizedLabels:[1x{@odata.type:string,Label:string,LanguageCode:number}]},OptionSet:{@odata.type:string,FalseOption:{Label:{@odata.type:string,LocalizedLabels:[1x{@odata.type:string,Label:string,LanguageCode:number}]},Value:number},TrueOption:{Label:{@odata.type:string,LocalizedLabels:[1x{@odata.type:string,Label:string,LanguageCode:number}]},Value:number}},RequiredLevel:{CanBeChanged:boolean,ManagedPropertyLogicalName:string,Value:string},SchemaName:string}+#83dcbd6c {@odata.type:string,AttributeType:string,AttributeTypeName:{Value:string},DisplayName:{@odata.type:string,LocalizedLabels:[1x{@odata.type:string,Label:string,LanguageCode:number}]},MaxValue:number,MinValue:number,Precision:number,RequiredLevel:{CanBeChanged:boolean,ManagedPropertyLogicalName:string,Value:string},SchemaName:string}+#85166fac {@odata.type:string,AttributeType:string,AttributeTypeName:{Value:string},DisplayName:{@odata.type:string,LocalizedLabels:[1x{@odata.type:string,Label:string,LanguageCode:number}]},RequiredLevel:{CanBeChanged:boolean,ManagedPropertyLogicalName:string,Value:string},SchemaName:string}+#85806883 {@odata.type:string,AttributeType:string,AttributeTypeName:{Value:string},AutoNumberFormat:string,DisplayName:{@odata.type:string,LocalizedLabels:[1x{@odata.type:string,Label:string,LanguageCode:number}]},FormatName:{Value:string},MaxLength:number,RequiredLevel:{CanBeChanged:boolean,ManagedPropertyLogicalName:string,Value:string},SchemaName:string}+#8e40ff9d {name:string}+#97e1522c {description:string,fetchxml:string,layoutxml:string,name:string,returnedtypecode:string}+#99efb92e {@odata.type:string,AttributeType:string,AttributeTypeName:{Value:string},DisplayName:{@odata.type:string,LocalizedLabels:[1x{@odata.type:string,Label:string,LanguageCode:number}]},[email protected]:string,RequiredLevel:{CanBeChanged:boolean,ManagedPropertyLogicalName:string,Value:string},SchemaName:string}+#9bb0a025 {isdefault:boolean}+#9bbb6c67 {AppUniqueName:string,SettingName:string,SolutionUniqueName:string,Value:string}+#9d0094e8 {description:string,formid:string,formxml:string,istabletenabled:boolean,name:string,type:string}+#a48e6542 {sitemapname:string,sitemapxml:string}+#b3f86741 {appmoduleid:string,clienttype:number,description:string,formfactor:number,name:string,navigationtype:number,uniquename:string,webresourceid:string}+#bb920f89 {description:string,formxml:string,name:string,objecttypecode:string,type:number}+#c1ba6652 {AddRequiredComponents:boolean,ComponentId:string,ComponentType:number,SolutionUniqueName:string}+#c4c362c9 {sitemapid:string,sitemapname:string,sitemapnameunique:string,sitemapxml:string}+#d13e24c0 {[email protected]:string,description:string,name:string}+#d59ac10f {description:string,formid:string,formxml:string,name:string,objecttypecode:string,type:number}+#d6b4b26e {@odata.type:string,ChangeTrackingEnabled:boolean,CollectionSchemaName:string,Description:{LocalizedLabels:[1x{HasChanged:null,IsManaged:boolean,Label:string,LanguageCode:number,MetadataId:string}],UserLocalizedLabel:{HasChanged:null,IsManaged:boolean,Label:string,LanguageCode:number,MetadataId:string}},DisplayCollectionName:{LocalizedLabels:[1x{HasChanged:null,IsManaged:boolean,Label:string,LanguageCode:number,MetadataId:string}],UserLocalizedLabel:{HasChanged:null,IsManaged:boolean,Label:string,LanguageCode:number,MetadataId:string}},DisplayName:{LocalizedLabels:[1x{HasChanged:null,IsManaged:boolean,Label:string,LanguageCode:number,MetadataId:string}],UserLocalizedLabel:{HasChanged:null,IsManaged:boolean,Label:string,LanguageCode:number,MetadataId:string}},EntitySetName:string,HasActivities:boolean,HasNotes:boolean,IconLargeName:null,IconMediumName:null,IconSmallName:null,IconVectorName:string,IsActivity:boolean,IsCustomEntity:boolean,IsIntersect:boolean,IsManaged:boolean,IsQuickCreateEnabled:boolean,LogicalCollectionName:string,LogicalName:string,MetadataId:string,ObjectTypeCode:number,OwnershipType:string,PrimaryIdAttribute:string,PrimaryImageAttribute:string,PrimaryNameAttribute:string,Privileges:[8x{CanBeBasic:boolean,CanBeDeep:boolean,CanBeEntityReference:boolean,CanBeGlobal:boolean,CanBeLocal:boolean,CanBeParentEntityReference:boolean,Name:string,PrivilegeId:string,PrivilegeType:string}],SchemaName:string,TableType:string}+#e0abe8e4 {formxml:string,name:string,objecttypecode:string,type:number}+#e1de4e0e {AppId:string,Components:[3x{@odata.id:string}|6x{@odata.type:string,formid:string}|9x{@odata.type:string,savedqueryid:string}|1x{@odata.type:string,savedqueryvisualizationid:string}|1x{@odata.type:string,sitemapid:string}]}+#e32dd0e5 {Lookup:{@odata.type:string,DisplayName:{@odata.type:string,LocalizedLabels:[1x{@odata.type:string,Label:string,LanguageCode:number}]},RequiredLevel:{CanBeChanged:boolean,ManagedPropertyLogicalName:string,Value:string},SchemaName:string,Targets:[2xstring]},OneToManyRelationships:[2x{@odata.type:string,ReferencedEntity:string,ReferencingEntity:string,SchemaName:string}]}+#e34f0019 {[email protected]:string,[email protected]:string,appactionid:string,context:number,contextvalue:string,grouptitle:string,isgrouptitlehidden:boolean,location:number,name:string,type:number,uniquename:string}+#e39def73 {formxml:string}+#e75eb5e5 {Targets:[1x{@odata.type:string,[email protected]:string,contoso_hours:number,contoso_title:string}]}+#e84db148 {@odata.type:string,DisplayName:{@odata.type:string,LocalizedLabels:[1x{@odata.type:string,Label:string,LanguageCode:number}]},KeyAttributes:[1xstring],SchemaName:string}+#e95a897a {Targets:[1x{@odata.type:string,contoso_billable:boolean,contoso_headcount:number,contoso_name:string,contoso_priority:number,contoso_stage:number,statecode:number,statuscode:number}]}+#eaa4807c {[email protected]:string,[email protected]:string,[email protected]:string,appactionid:string,buttonlabeltext:string,context:number,contextvalue:string,location:number,name:string,onclickeventjavascriptfunctionname:string,onclickeventjavascriptparameters:string,onclickeventtype:number,sequence:number,type:number,uniquename:string}+#f07e5c5f {@odata.id:string}+#f3dc5825 {filename:string,filetype:number,uxagentprojectfileid:string,[email protected]:string}+#fab2e725 {@odata.type:string,AttributeType:string,AttributeTypeName:{Value:string},DisplayName:{@odata.type:string,LocalizedLabels:[1x{@odata.type:string,Label:string,LanguageCode:number}]},IsPrimaryImage:boolean,MaxSizeInKB:number,RequiredLevel:{CanBeChanged:boolean,ManagedPropertyLogicalName:string,Value:string},SchemaName:string}diff --git a/plugins/model-apps/scripts/tests/golden/lifecycle-trail.download.txt b/plugins/model-apps/scripts/tests/golden/lifecycle-trail.download.txtnew file mode 100644index 000000000..e2681284b--- /dev/null+++ b/plugins/model-apps/scripts/tests/golden/lifecycle-trail.download.txt@@ -0,0 +1,127 @@+# 136 requests, 0 publishes+## after the last publish+ 4x GET /EntityDefinitions(<id>)?$select=LogicalName,IsCustomEntity -> 200+ 1x GET /EntityDefinitions(LogicalName='appaction')?$select=EntitySetName -> 200+ 1x GET /EntityDefinitions(LogicalName='appmodule')?$select=EntitySetName -> 200+ 1x GET /EntityDefinitions(LogicalName='appmodulecomponent')?$select=EntitySetName -> 200+ 1x GET /EntityDefinitions(LogicalName='appsetting')?$select=EntitySetName -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_project')/Attributes/Microsoft.Dynamics.CRM.BooleanAttributeMetadata?$select=LogicalName&$expand=OptionSet($select=TrueOption,FalseOption) -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_project')/Attributes/Microsoft.Dynamics.CRM.DateTimeAttributeMetadata?$select=LogicalName,Format -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_project')/Attributes/Microsoft.Dynamics.CRM.DecimalAttributeMetadata?$select=LogicalName,MinValue,MaxValue,Precision -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_project')/Attributes/Microsoft.Dynamics.CRM.DoubleAttributeMetadata?$select=LogicalName,MinValue,MaxValue,Precision -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_project')/Attributes/Microsoft.Dynamics.CRM.FileAttributeMetadata?$select=LogicalName,MaxSizeInKB -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_project')/Attributes/Microsoft.Dynamics.CRM.ImageAttributeMetadata?$select=LogicalName,MaxSizeInKB,IsPrimaryImage -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_project')/Attributes/Microsoft.Dynamics.CRM.IntegerAttributeMetadata?$select=LogicalName,MinValue,MaxValue,Format -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_project')/Attributes/Microsoft.Dynamics.CRM.LookupAttributeMetadata?$select=LogicalName,SchemaName,DisplayName,Targets -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_project')/Attributes/Microsoft.Dynamics.CRM.LookupAttributeMetadata?$select=LogicalName,Targets -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_project')/Attributes/Microsoft.Dynamics.CRM.MemoAttributeMetadata?$select=LogicalName,MaxLength -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_project')/Attributes/Microsoft.Dynamics.CRM.MoneyAttributeMetadata?$select=LogicalName,IsBaseCurrency,MinValue,MaxValue,Precision,PrecisionSource -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_project')/Attributes/Microsoft.Dynamics.CRM.MultiSelectPicklistAttributeMetadata?$select=LogicalName&$expand=OptionSet($select=Name,DisplayName,IsGlobal,Options) -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_project')/Attributes/Microsoft.Dynamics.CRM.MultiSelectPicklistAttributeMetadata?$select=LogicalName&$expand=OptionSet($select=Options) -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_project')/Attributes/Microsoft.Dynamics.CRM.PicklistAttributeMetadata?$select=LogicalName&$expand=OptionSet($select=Name,DisplayName,IsGlobal,Options) -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_project')/Attributes/Microsoft.Dynamics.CRM.PicklistAttributeMetadata?$select=LogicalName&$expand=OptionSet($select=Options) -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_project')/Attributes/Microsoft.Dynamics.CRM.StateAttributeMetadata?$select=LogicalName&$expand=OptionSet($select=Options) -> 200+ 2x GET /EntityDefinitions(LogicalName='contoso_project')/Attributes/Microsoft.Dynamics.CRM.StatusAttributeMetadata?$select=LogicalName&$expand=OptionSet($select=Options) -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_project')/Attributes/Microsoft.Dynamics.CRM.StringAttributeMetadata?$select=LogicalName,MaxLength -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_project')/Attributes/Microsoft.Dynamics.CRM.StringAttributeMetadata?$select=LogicalName,MaxLength,FormatName,AutoNumberFormat -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_project')/Attributes?$select=LogicalName,Description,DisplayName,IsLogical,AttributeOf,AttributeTypeName -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_project')/ManyToManyRelationships?$select=SchemaName,Entity1LogicalName,Entity2LogicalName -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_project')/ManyToManyRelationships?$select=SchemaName,Entity1LogicalName,Entity2LogicalName,IsCustomRelationship -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_project')/ManyToOneRelationships?$select=SchemaName,ReferencedEntity,ReferencedAttribute -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_project')/ManyToOneRelationships?$select=SchemaName,ReferencedEntity,ReferencingEntity,ReferencingAttribute,IsCustomRelationship -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_project')/OneToManyRelationships?$select=SchemaName,ReferencingEntity,ReferencingAttribute -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_project')?$select=LogicalName,Description,DisplayName,DisplayCollectionName,IconVectorName&$expand=Keys($select=SchemaName,DisplayName,KeyAttributes,IsManaged) -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_project')?$select=LogicalName,SchemaName,DisplayName,Description,EntitySetName,IsCustomEntity,PrimaryNameAttribute,PrimaryIdAttribute,PrimaryImageAttribute&$expand=Attributes($select=LogicalName,DisplayName,Description,AttributeType,AttributeTypeName,IsCustomAttribute,IsValidForUpdate,IsValidForRead,AttributeOf) -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_tag')/Attributes/Microsoft.Dynamics.CRM.BooleanAttributeMetadata?$select=LogicalName&$expand=OptionSet($select=TrueOption,FalseOption) -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_tag')/Attributes/Microsoft.Dynamics.CRM.LookupAttributeMetadata?$select=LogicalName,Targets -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_tag')/Attributes/Microsoft.Dynamics.CRM.MoneyAttributeMetadata?$select=LogicalName,IsBaseCurrency,MinValue,MaxValue,Precision,PrecisionSource -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_tag')/Attributes/Microsoft.Dynamics.CRM.MultiSelectPicklistAttributeMetadata?$select=LogicalName&$expand=OptionSet($select=Name,DisplayName,IsGlobal,Options) -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_tag')/Attributes/Microsoft.Dynamics.CRM.MultiSelectPicklistAttributeMetadata?$select=LogicalName&$expand=OptionSet($select=Options) -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_tag')/Attributes/Microsoft.Dynamics.CRM.PicklistAttributeMetadata?$select=LogicalName&$expand=OptionSet($select=Name,DisplayName,IsGlobal,Options) -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_tag')/Attributes/Microsoft.Dynamics.CRM.PicklistAttributeMetadata?$select=LogicalName&$expand=OptionSet($select=Options) -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_tag')/Attributes/Microsoft.Dynamics.CRM.StateAttributeMetadata?$select=LogicalName&$expand=OptionSet($select=Options) -> 200+ 2x GET /EntityDefinitions(LogicalName='contoso_tag')/Attributes/Microsoft.Dynamics.CRM.StatusAttributeMetadata?$select=LogicalName&$expand=OptionSet($select=Options) -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_tag')/Attributes/Microsoft.Dynamics.CRM.StringAttributeMetadata?$select=LogicalName,MaxLength -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_tag')/Attributes/Microsoft.Dynamics.CRM.StringAttributeMetadata?$select=LogicalName,MaxLength,FormatName,AutoNumberFormat -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_tag')/Attributes?$select=LogicalName,Description,DisplayName,IsLogical,AttributeOf,AttributeTypeName -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_tag')/ManyToManyRelationships?$select=SchemaName,Entity1LogicalName,Entity2LogicalName -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_tag')/ManyToManyRelationships?$select=SchemaName,Entity1LogicalName,Entity2LogicalName,IsCustomRelationship -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_tag')/ManyToOneRelationships?$select=SchemaName,ReferencedEntity,ReferencedAttribute -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_tag')/ManyToOneRelationships?$select=SchemaName,ReferencedEntity,ReferencingEntity,ReferencingAttribute,IsCustomRelationship -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_tag')/OneToManyRelationships?$select=SchemaName,ReferencingEntity,ReferencingAttribute -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_tag')?$select=LogicalName,Description,DisplayName,DisplayCollectionName,IconVectorName&$expand=Keys($select=SchemaName,DisplayName,KeyAttributes,IsManaged) -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_tag')?$select=LogicalName,SchemaName,DisplayName,Description,EntitySetName,IsCustomEntity,PrimaryNameAttribute,PrimaryIdAttribute,PrimaryImageAttribute&$expand=Attributes($select=LogicalName,DisplayName,Description,AttributeType,AttributeTypeName,IsCustomAttribute,IsValidForUpdate,IsValidForRead,AttributeOf) -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_task')/Attributes/Microsoft.Dynamics.CRM.BooleanAttributeMetadata?$select=LogicalName&$expand=OptionSet($select=TrueOption,FalseOption) -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_task')/Attributes/Microsoft.Dynamics.CRM.DateTimeAttributeMetadata?$select=LogicalName,Format -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_task')/Attributes/Microsoft.Dynamics.CRM.IntegerAttributeMetadata?$select=LogicalName,MinValue,MaxValue,Format -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_task')/Attributes/Microsoft.Dynamics.CRM.LookupAttributeMetadata?$select=LogicalName,SchemaName,DisplayName,Targets -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_task')/Attributes/Microsoft.Dynamics.CRM.LookupAttributeMetadata?$select=LogicalName,Targets -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_task')/Attributes/Microsoft.Dynamics.CRM.MoneyAttributeMetadata?$select=LogicalName,IsBaseCurrency,MinValue,MaxValue,Precision,PrecisionSource -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_task')/Attributes/Microsoft.Dynamics.CRM.MultiSelectPicklistAttributeMetadata?$select=LogicalName&$expand=OptionSet($select=Name,DisplayName,IsGlobal,Options) -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_task')/Attributes/Microsoft.Dynamics.CRM.MultiSelectPicklistAttributeMetadata?$select=LogicalName&$expand=OptionSet($select=Options) -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_task')/Attributes/Microsoft.Dynamics.CRM.PicklistAttributeMetadata?$select=LogicalName&$expand=OptionSet($select=Name,DisplayName,IsGlobal,Options) -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_task')/Attributes/Microsoft.Dynamics.CRM.PicklistAttributeMetadata?$select=LogicalName&$expand=OptionSet($select=Options) -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_task')/Attributes/Microsoft.Dynamics.CRM.StateAttributeMetadata?$select=LogicalName&$expand=OptionSet($select=Options) -> 200+ 2x GET /EntityDefinitions(LogicalName='contoso_task')/Attributes/Microsoft.Dynamics.CRM.StatusAttributeMetadata?$select=LogicalName&$expand=OptionSet($select=Options) -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_task')/Attributes/Microsoft.Dynamics.CRM.StringAttributeMetadata?$select=LogicalName,MaxLength -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_task')/Attributes/Microsoft.Dynamics.CRM.StringAttributeMetadata?$select=LogicalName,MaxLength,FormatName,AutoNumberFormat -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_task')/Attributes?$select=LogicalName,Description,DisplayName,IsLogical,AttributeOf,AttributeTypeName -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_task')/ManyToManyRelationships?$select=SchemaName,Entity1LogicalName,Entity2LogicalName -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_task')/ManyToManyRelationships?$select=SchemaName,Entity1LogicalName,Entity2LogicalName,IsCustomRelationship -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_task')/ManyToOneRelationships?$select=SchemaName,ReferencedEntity,ReferencedAttribute -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_task')/ManyToOneRelationships?$select=SchemaName,ReferencedEntity,ReferencingEntity,ReferencingAttribute,IsCustomRelationship -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_task')/OneToManyRelationships?$select=SchemaName,ReferencingEntity,ReferencingAttribute -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_task')?$select=LogicalName,Description,DisplayName,DisplayCollectionName,IconVectorName&$expand=Keys($select=SchemaName,DisplayName,KeyAttributes,IsManaged) -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_task')?$select=LogicalName,SchemaName,DisplayName,Description,EntitySetName,IsCustomEntity,PrimaryNameAttribute,PrimaryIdAttribute,PrimaryImageAttribute&$expand=Attributes($select=LogicalName,DisplayName,Description,AttributeType,AttributeTypeName,IsCustomAttribute,IsValidForUpdate,IsValidForRead,AttributeOf) -> 200+ 1x GET /EntityDefinitions(LogicalName='savedquery')?$select=EntitySetName -> 200+ 1x GET /EntityDefinitions(LogicalName='savedqueryvisualization')?$select=EntitySetName -> 200+ 1x GET /EntityDefinitions(LogicalName='settingdefinition')?$select=EntitySetName -> 200+ 1x GET /EntityDefinitions(LogicalName='solution')?$select=EntitySetName -> 200+ 1x GET /EntityDefinitions(LogicalName='solutioncomponent')?$select=EntitySetName -> 200+ 1x GET /EntityDefinitions(LogicalName='systemform')?$select=EntitySetName -> 200+ 1x GET /EntityDefinitions(LogicalName='webresource')?$select=EntitySetName -> 200+ 1x GET /GlobalOptionSetDefinitions?$select=Name,Description,IsManaged,MetadataId -> 200+ 1x GET /agentconversationmessages?$select=agentconversationmessageid,message,messagesender,createdon&$filter=_regardingobjectid_value eq <id>&$orderby=createdon asc,versionnumber asc -> 200+ 1x GET /appactions?$select=appactionid,name,buttonlabeltext,contextvalue,type,statecode,_appmoduleid_value&$filter=ismanaged eq false and (contextvalue eq 'contact' or contextvalue eq 'contoso_project' or contextvalue eq 'contoso_tag' or contextvalue eq 'contoso_task') -> 200+ 2x GET /appmodulecomponents?$select=objectid&$filter=_appmoduleidunique_value eq <id> and componenttype eq 62 -> 200+ 1x GET /appmodulecomponents?$select=objectid,componenttype&$filter=_appmoduleidunique_value eq <id> and componenttype eq 1 -> 200+ 1x GET /appmodulecomponents?$select=objectid,componenttype&$filter=_appmoduleidunique_value eq <id> and componenttype eq 26 -> 200+ 1x GET /appmodulecomponents?$select=objectid,componenttype&$filter=_appmoduleidunique_value eq <id> and componenttype eq 59 -> 200+ 1x GET /appmodulecomponents?$select=objectid,componenttype&$filter=_appmoduleidunique_value eq <id> and componenttype eq 60 -> 200+ 1x GET /appmodulecomponents?$select=objectid,componenttype&$filter=_appmoduleidunique_value eq <id> and componenttype eq 62&$top=1 -> 200+ 1x GET /appmodules(<id>)?$select=appmoduleid -> 200+ 3x GET /appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()?$select=appmoduleid,appmoduleidunique,componentstate&$filter=appmoduleid eq <id> -> 200+ 1x GET /appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()?$select=appmoduleid,name,uniquename,description,aiappdescription&$filter=appmoduleid eq <id>&$top=1 -> 200+ 1x GET /appmodules?$select=appmoduleid&$filter=uniquename eq 'contoso_kitchensink'&$top=1 -> 200+ 1x GET /appmodules?$select=uniquename&$filter=appmoduleid eq <id>&$top=1 -> 200+ 1x GET /appsettings?$select=value,_settingdefinitionid_value&$filter=_parentappmoduleid_value eq <id> and (_settingdefinitionid_value eq <id> or _settingdefinitionid_value eq <id>)&$top=10 -> 200+ 1x GET /organizations?$select=languagecode&$top=1 -> 200+ 1x GET /savedqueries?$select=savedqueryid,name,returnedtypecode,description&$filter=savedqueryid eq <id> or savedqueryid eq <id> or savedqueryid eq <id> or savedqueryid eq <id> or savedqueryid eq <id> or savedqueryid eq <id> or savedqueryid eq <id> or savedqueryid eq <id> or savedqueryid eq <id> -> 200+ 1x GET /savedqueries?$select=savedqueryid,returnedtypecode&$filter=savedqueryid eq <id> or savedqueryid eq <id> or savedqueryid eq <id> or savedqueryid eq <id> or savedqueryid eq <id> or savedqueryid eq <id> or savedqueryid eq <id> or savedqueryid eq <id> or savedqueryid eq <id> -> 200+ 1x GET /savedqueryvisualizations?$select=savedqueryvisualizationid,name,primaryentitytypecode,description&$filter=savedqueryvisualizationid eq <id> -> 200+ 1x GET /savedqueryvisualizations?$select=savedqueryvisualizationid,primaryentitytypecode&$filter=savedqueryvisualizationid eq <id> -> 200+ 1x GET /settingdefinitions?$select=settingdefinitionid,uniquename&$filter=uniquename eq 'NewLookAlwaysOn' or uniquename eq 'HeaderAndNavigationRefresh'&$top=10 -> 200+ 1x GET /sitemaps(<id>)?$select=sitemapid -> 200+ 1x GET /sitemaps/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()?$select=sitemapid,sitemapname,sitemapnameunique,sitemapxml&$filter=sitemapid eq <id>&$top=1 -> 200+ 1x GET /sitemaps/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()?$select=sitemapxml,componentstate&$filter=sitemapid eq <id> -> 200+ 1x GET /solutioncomponents?$select=_solutionid_value&$filter=objectid eq <id> -> 200+ 1x GET /solutioncomponents?$select=objectid&$filter=_solutionid_value eq <id> and componenttype eq 9 -> 200+ 1x GET /solutioncomponents?$select=objectid,componenttype&$filter=_solutionid_value eq <id> and componenttype eq 29 -> 200+ 1x GET /solutions?$select=solutionid&$filter=uniquename eq 'ContosoKitchen'&$top=1 -> 200+ 1x GET /solutions?$select=solutionid,uniquename,friendlyname,ismanaged,description&$filter=solutionid eq <id> -> 200+ 1x GET /solutions?$select=solutionid,uniquename,friendlyname,version,ismanaged&$expand=publisherid($select=publisherid,uniquename,customizationprefix,customizationoptionvalueprefix)&$filter=uniquename eq 'ContosoKitchen' -> 200+ 1x GET /systemforms(<id>)/Microsoft.Dynamics.CRM.RetrieveUnpublished()?$select=formid,name,description,formxml,type,objecttypecode,istabletenabled,iscustomizable,componentstate,versionnumber -> 200+ 1x GET /systemforms?$select=formid,name,formactivationstate&$filter=objecttypecode eq 'contoso_project' and type eq 2 -> 200+ 1x GET /systemforms?$select=formid,name,formactivationstate&$filter=objecttypecode eq 'contoso_tag' and type eq 2 -> 200+ 1x GET /systemforms?$select=formid,name,formactivationstate&$filter=objecttypecode eq 'contoso_task' and type eq 2 -> 200+ 1x GET /systemforms?$select=formid,name,objecttypecode,description,formxml&$filter=formid eq <id> or formid eq <id> or formid eq <id> or formid eq <id> or formid eq <id> or formid eq <id> -> 200+ 1x GET /systemforms?$select=formid,name,type,objecttypecode&$filter=formid eq <id> or formid eq <id> or formid eq <id> or formid eq <id> or formid eq <id> or formid eq <id> -> 200+ 1x GET /systemforms?$select=formid,objecttypecode&$filter=formid eq <id> or formid eq <id> or formid eq <id> or formid eq <id> or formid eq <id> or formid eq <id> -> 200+ 1x GET /systemforms?$select=name,description&$filter=formid eq <id>&$top=1 -> 200+ 4x GET /uxagentprojectfiles(<id>)/filecontent/$value -> 200+ 1x GET /uxagentprojectfiles?$select=uxagentprojectfileid,filename,filetype&$filter=_uxagentprojectid_value eq <id> -> 200+ 1x GET /uxagentprojects(<id>)?$select=uxagentprojectid,name -> 200+ 1x GET /uxagentprojects?$select=uxagentprojectid,name -> 200+ 1x GET /webresourceset?$select=content&$filter=name eq 'contoso_kitchensink_pagemanifest'&$top=1 -> 200+ 1x GET /webresourceset?$select=name,displayname,webresourcetype,content,ismanaged&$filter=name eq 'contoso_projecticon.svg'&$top=1 -> 200+# shapesdiff --git a/plugins/model-apps/scripts/tests/golden/lifecycle-trail.edit.txt b/plugins/model-apps/scripts/tests/golden/lifecycle-trail.edit.txtnew file mode 100644index 000000000..365cd4383--- /dev/null+++ b/plugins/model-apps/scripts/tests/golden/lifecycle-trail.edit.txt@@ -0,0 +1,280 @@+# 406 requests, 5 publishes+## up to publish 1: importexportxml(entities(entity=contoso_project))+ 1x GET /EntityDefinitions(LogicalName='appmodule')?$select=EntitySetName -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_project') -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_project')/Attributes/Microsoft.Dynamics.CRM.MultiSelectPicklistAttributeMetadata?$select=LogicalName&$expand=OptionSet($select=Options) -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_project')/Attributes/Microsoft.Dynamics.CRM.PicklistAttributeMetadata?$select=LogicalName&$expand=OptionSet($select=Options) -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_project')/Attributes/Microsoft.Dynamics.CRM.StateAttributeMetadata?$select=LogicalName&$expand=OptionSet($select=Options) -> 200+ 2x GET /EntityDefinitions(LogicalName='contoso_project')/Attributes/Microsoft.Dynamics.CRM.StatusAttributeMetadata?$select=LogicalName&$expand=OptionSet($select=Options) -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_project')/Attributes?$select=LogicalName,RequiredLevel -> 200+ 2x GET /EntityDefinitions(LogicalName='contoso_project')/OneToManyRelationships?$select=SchemaName,ReferencingEntity,ReferencingAttribute -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_project')?$select=EntitySetName -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_project')?$select=LogicalName,EntitySetName&$expand=Keys($select=SchemaName,KeyAttributes) -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_tag')/Attributes?$select=LogicalName,RequiredLevel -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_tag')?$select=LogicalName,EntitySetName -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_task') -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_task')/Attributes?$select=LogicalName,RequiredLevel -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_task')/ManyToManyRelationships?$select=SchemaName,Entity1LogicalName,Entity2LogicalName,IntersectEntityName,Entity1IntersectAttribute,Entity2IntersectAttribute -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_task')?$select=EntitySetName -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_task')?$select=LogicalName,EntitySetName -> 200+ 1x GET /EntityDefinitions(LogicalName='solution')?$select=EntitySetName -> 200+ 1x GET /EntityDefinitions(LogicalName='webresource')?$select=EntitySetName -> 200+ 1x GET /GlobalOptionSetDefinitions(Name='contoso_stage')?$select=MetadataId -> 200+ 2x GET /appmodulecomponents?$select=objectid&$filter=_appmoduleidunique_value eq <id> and componenttype eq 62 -> 200+ 1x GET /appmodules(<id>)?$select=appmoduleid -> 200+ 2x GET /appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()?$select=appmoduleid,appmoduleidunique,componentstate&$filter=appmoduleid eq <id> -> 200+ 1x GET /appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()?$select=appmoduleid,name,uniquename,description,aiappdescription&$filter=appmoduleid eq <id>&$top=1 -> 200+ 2x GET /appmodules?$select=appmoduleid&$filter=uniquename eq 'contoso_kitchensink'&$top=1 -> 200+ 1x GET /contoso_projects?$select=contoso_name,contoso_projectid&$filter=contoso_name eq 'Apollo'&$top=5000 -> 200+ 1x GET /contoso_tasks?$select=contoso_title,contoso_taskid&$filter=contoso_title eq 'Kickoff'&$top=5000 -> 200+ 1x GET /sitemaps(<id>)?$select=sitemapid -> 200+ 1x GET /sitemaps/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()?$select=sitemapid,sitemapname,sitemapnameunique,sitemapxml&$filter=sitemapid eq <id>&$top=1 -> 200+ 2x GET /solutions?$select=solutionid&$filter=uniquename eq 'ContosoKitchen'&$top=1 -> 200+ 1x GET /webresourceset?$select=webresourceid,content&$filter=name eq 'contoso_project.js'&$top=1 -> 200+ 1x GET /webresourceset?$select=webresourceid,content&$filter=name eq 'contoso_projecticon.svg'&$top=1 -> 200+ 1x POST /EntityDefinitions(LogicalName='contoso_tag')/Attributes #17143fc8 -> 204+ 1x POST /EntityDefinitions(LogicalName='contoso_task')/Attributes #4940b353 -> 204+ 1x POST /PublishXml #1b71745d -> 204+ 1x PUT /EntityDefinitions(<id>) #2b71ae7d -> 204+ 1x PUT /EntityDefinitions(<id>) #d6b4b26e -> 204+## up to publish 2: importexportxml(entities(entity=contoso_project entity=contoso_tag entity=contoso_task))+ 1x GET /EntityDefinitions(LogicalName='appaction')?$select=EntitySetName -> 200+ 1x GET /EntityDefinitions(LogicalName='appmodulecomponent')?$select=EntitySetName -> 200+ 1x GET /EntityDefinitions(LogicalName='contact')?$select=MetadataId,EntitySetName -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_project')?$select=MetadataId,EntitySetName -> 200+ 2x GET /EntityDefinitions(LogicalName='contoso_task')/Attributes?$select=LogicalName,AttributeType,DisplayName&$filter=LogicalName eq 'contoso_start' -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_task')?$select=MetadataId,EntitySetName -> 200+ 3x GET /EntityDefinitions(LogicalName='savedquery')?$select=EntitySetName -> 200+ 1x GET /EntityDefinitions(LogicalName='savedqueryvisualization')?$select=EntitySetName -> 200+ 1x GET /EntityDefinitions(LogicalName='solutioncomponent')?$select=EntitySetName -> 200+ 4x GET /EntityDefinitions(LogicalName='systemform')?$select=EntitySetName -> 200+ 1x GET /appactions?$select=appactionid,buttonlabeltext&$filter=contextvalue eq 'contoso_project'&$top=1 -> 200+ 1x GET /appmodulecomponents?$select=objectid,componenttype&$filter=_appmoduleidunique_value eq <id> and componenttype eq 59 -> 200+ 1x GET /appmodulecomponents?$select=objectid,componenttype&$filter=_appmoduleidunique_value eq <id> and componenttype eq 60 -> 200+ 1x GET /appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()?$select=appmoduleid,appmoduleidunique,componentstate&$filter=appmoduleid eq <id> -> 200+ 1x GET /appmodules?$select=appmoduleid&$filter=uniquename eq 'contoso_kitchensink'&$top=1 -> 200+ 9x GET /savedqueries(<id>)/Microsoft.Dynamics.CRM.RetrieveUnpublished()?$select=savedqueryid,name,description,fetchxml,layoutxml,querytype,returnedtypecode,isdefault -> 200+ 9x GET /savedqueries(<id>)?$select=savedqueryid -> 200+ 1x GET /savedqueries?$select=savedqueryid&$filter=returnedtypecode eq 'contoso_project' and name eq 'Open Projects'&$top=2 -> 200+ 1x GET /savedqueries?$select=savedqueryid&$filter=returnedtypecode eq 'contoso_task' and name eq 'My Open Tasks'&$top=2 -> 200+ 1x GET /savedqueries?$select=savedqueryid&$filter=returnedtypecode eq 'contoso_task' and name eq 'Open Tasks'&$top=2 -> 200+ 1x GET /savedqueries?$select=savedqueryid,name,canbedeleted,fetchxml,createdon&$filter=returnedtypecode eq 'contoso_project' and querytype eq 0 -> 200+ 1x GET /savedqueries?$select=savedqueryid,name,canbedeleted,fetchxml,createdon&$filter=returnedtypecode eq 'contoso_tag' and querytype eq 0 -> 200+ 1x GET /savedqueries?$select=savedqueryid,name,canbedeleted,fetchxml,createdon&$filter=returnedtypecode eq 'contoso_task' and querytype eq 0 -> 200+ 1x GET /savedqueryvisualizations(<id>)/Microsoft.Dynamics.CRM.RetrieveUnpublished()?$select=savedqueryvisualizationid,name,description,primaryentitytypecode,datadescription,presentationdescription,charttype,type,isdefault -> 200+ 1x GET /savedqueryvisualizations(<id>)?$select=savedqueryvisualizationid -> 200+ 1x GET /savedqueryvisualizations/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()?$select=savedqueryvisualizationid,primaryentitytypecode&$filter=savedqueryvisualizationid eq <id> -> 200+ 1x GET /savedqueryvisualizations?$select=savedqueryvisualizationid&$filter=primaryentitytypecode eq 'contoso_project' and name eq 'Projects by Priority'&$top=2 -> 200+ 1x GET /solutioncomponents?$select=objectid&$filter=_solutionid_value eq <id> and componenttype eq 60 and (objectid eq <id>)&$top=50 -> 200+ 1x GET /solutioncomponents?$select=objectid,componenttype,rootcomponentbehavior&$filter=_solutionid_value eq <id> and (componenttype eq 26 or componenttype eq 59 or componenttype eq 60 or componenttype eq 61 or componenttype eq 62 or componenttype eq 80 or componenttype eq 20 or componenttype eq 29 or componenttype eq 1) -> 200+ 2x GET /solutions?$select=solutionid&$filter=uniquename eq 'ContosoKitchen'&$top=1 -> 200+ 8x GET /systemforms(<id>)/Microsoft.Dynamics.CRM.RetrieveUnpublished()?$select=formid,formxml,name,type,objecttypecode,formpresentation,formactivationstate,uniquename,description,versionnumber -> 200+ 2x GET /systemforms(<id>)/Microsoft.Dynamics.CRM.RetrieveUnpublished()?$select=formid,formxml,type -> 200+ 2x GET /systemforms(<id>)/Microsoft.Dynamics.CRM.RetrieveUnpublished()?$select=formid,type -> 200+ 2x GET /systemforms(<id>)?$select=formid -> 200+ 1x GET /systemforms/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()?$select=formid,objecttypecode&$filter=formid eq <id> or formid eq <id> or formid eq <id> or formid eq <id> or formid eq <id> or formid eq <id> -> 200+ 1x GET /systemforms?$select=formid&$filter=objecttypecode eq 'contoso_project' and name eq 'Project Card' and type eq 6&$top=2 -> 200+ 1x GET /systemforms?$select=formid&$filter=objecttypecode eq 'contoso_project' and name eq 'Project' and type eq 2&$top=2 -> 200+ 1x GET /systemforms?$select=formid&$filter=objecttypecode eq 'contoso_task' and name eq 'Task Quick Create' and type eq 7&$top=2 -> 200+ 1x GET /systemforms?$select=formid&$filter=objecttypecode eq 'contoso_task' and name eq 'Task' and type eq 2&$top=2 -> 200+ 1x GET /systemforms?$select=formid,name&$filter=name eq 'Kitchen Overview' and type eq 0&$top=10 -> 200+ 1x GET /systemforms?$select=formid,name&$filter=objecttypecode eq 'contoso_task' and type eq 2 and formactivationstate eq 1&$top=250 -> 200+ 1x GET /webresourceset?$select=webresourceid&$filter=name eq 'contoso_kitchensink_icon'&$top=1 -> 200+ 8x PATCH /savedqueries(<id>)?$select=savedqueryid #97e1522c -> 200+ 2x PATCH /systemforms(<id>) #9bb0a025 -> 204+ 2x PATCH /systemforms(<id>)?$select=formid #e0abe8e4 -> 200+ 1x POST /PublishXml #1b71745d -> 204+## up to publish 3: importexportxml(uxagentprojects(uxagentproject=#id))+ 1x GET /EntityDefinitions(LogicalName='contoso_project')/Attributes/Microsoft.Dynamics.CRM.BooleanAttributeMetadata?$select=LogicalName&$expand=OptionSet($select=TrueOption,FalseOption) -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_project')/Attributes/Microsoft.Dynamics.CRM.LookupAttributeMetadata?$select=LogicalName,Targets -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_project')/Attributes/Microsoft.Dynamics.CRM.MultiSelectPicklistAttributeMetadata?$select=LogicalName&$expand=OptionSet($select=Options) -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_project')/Attributes/Microsoft.Dynamics.CRM.PicklistAttributeMetadata?$select=LogicalName&$expand=OptionSet($select=Options) -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_project')/Attributes/Microsoft.Dynamics.CRM.StateAttributeMetadata?$select=LogicalName&$expand=OptionSet($select=Options) -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_project')/Attributes/Microsoft.Dynamics.CRM.StatusAttributeMetadata?$select=LogicalName&$expand=OptionSet($select=Options) -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_project')/Attributes/Microsoft.Dynamics.CRM.StringAttributeMetadata?$select=LogicalName,MaxLength -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_project')/ManyToManyRelationships?$select=SchemaName,Entity1LogicalName,Entity2LogicalName -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_project')/ManyToOneRelationships?$select=SchemaName,ReferencedEntity,ReferencedAttribute -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_project')/OneToManyRelationships?$select=SchemaName,ReferencingEntity,ReferencingAttribute -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_project')?$select=LogicalName,SchemaName,DisplayName,Description,EntitySetName,IsCustomEntity,PrimaryNameAttribute,PrimaryIdAttribute,PrimaryImageAttribute&$expand=Attributes($select=LogicalName,DisplayName,Description,AttributeType,AttributeTypeName,IsCustomAttribute,IsValidForUpdate,IsValidForRead,AttributeOf) -> 200+ 1x GET /EntityDefinitions(LogicalName='sitemap')?$select=EntitySetName -> 200+ 1x GET /EntityDefinitions(LogicalName='uxagentproject')?$select=EntitySetName -> 200+ 1x GET /EntityDefinitions(LogicalName='uxagentproject')?$select=ObjectTypeCode -> 200+ 1x GET /EntityDefinitions(LogicalName='uxagentprojectfile')?$select=EntitySetName -> 200+ 1x GET /agentconversationmessages?$select=agentconversationmessageid,message,messagesender,_regardingobjectid_value&$filter=agentconversationmessageid eq <id> or agentconversationmessageid eq <id> -> 200+ 1x GET /agentconversationmessages?$select=agentconversationmessageid,message,messagesender,createdon&$filter=_regardingobjectid_value eq <id>&$orderby=createdon asc,versionnumber asc -> 200+ 2x GET /appmodulecomponents?$select=objectid&$filter=_appmoduleidunique_value eq <id> and componenttype eq 62 -> 200+ 1x GET /appmodulecomponents?$select=objectid,componenttype&$filter=_appmoduleidunique_value eq <id> and componenttype eq 1 -> 200+ 3x GET /appmodulecomponents?$select=objectid,componenttype&$filter=_appmoduleidunique_value eq <id> and componenttype eq 62&$top=1 -> 200+ 1x GET /appmodules(<id>)?$select=appmoduleid -> 200+ 3x GET /appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()?$select=appmoduleid,appmoduleidunique,componentstate&$filter=appmoduleid eq <id> -> 200+ 2x GET /appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()?$select=appmoduleid,appmoduleidunique,uniquename,componentstate -> 200+ 1x GET /appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()?$select=appmoduleid,name,uniquename,description,aiappdescription&$filter=appmoduleid eq <id>&$top=1 -> 200+ 1x GET /appmodules?$select=appmoduleid,appmoduleidunique&$filter=uniquename eq 'contoso_kitchensink'&$top=1 -> 200+ 2x GET /appmodules?$select=appmoduleid,appmoduleidunique&$filter=uniquename eq 'fabrikam_widgets'&$top=1 -> 200+ 2x GET /appmodules?$select=appmoduleid,appmoduleidunique,uniquename -> 200+ 1x GET /sitemaps(<id>)?$select=sitemapid -> 200+ 1x GET /sitemaps/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()?$select=sitemapid,sitemapname,sitemapnameunique,sitemapxml&$filter=sitemapid eq <id>&$top=1 -> 200+ 2x GET /sitemaps/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()?$select=sitemapid,sitemapxml,componentstate,sitemapnameunique -> 200+ 1x GET /sitemaps?$select=sitemapid&$filter=sitemapnameunique eq 'contoso_kitchensink'&$top=1 -> 200+ 3x GET /sitemaps?$select=sitemapxml&$filter=sitemapid eq <id>&$top=1 -> 200+ 7x GET /uxagentprojectfiles(<id>)/filecontent/$value -> 200+ 5x GET /uxagentprojectfiles?$select=uxagentprojectfileid,filename,filetype&$filter=_uxagentprojectid_value eq <id> -> 200+ 1x GET /uxagentprojectfiles?$select=uxagentprojectfileid,versionnumber,_uxagentprojectid_value&$filter=_uxagentprojectid_value eq <id> -> 200+ 4x GET /uxagentprojects(<id>)?$select=uxagentprojectid,name -> 200+ 1x GET /uxagentprojects?$select=uxagentprojectid,name -> 200+ 1x GET /uxagentprojects?$select=uxagentprojectid,versionnumber&$filter=uxagentprojectid eq <id> -> 200+ 1x GET /webresourceset?$select=webresourceid,content&$filter=name eq 'contoso_kitchensink_pagemanifest'&$top=1 -> 200+ 1x POST /$batch -> 200+ > PATCH /uxagentprojectfiles(<id>)/filecontent #473287f8+ > PATCH /uxagentprojectfiles(<id>)/filecontent #473287f8+ > PATCH /uxagentprojects(<id>) #8e40ff9d+ > POST /agentconversationmessages #43dbd5f4+ > POST /agentconversationmessages #43dbd5f4+ 1x POST /PublishXml #1b71745d -> 204+## up to publish 4: importexportxml(appmodules(appmodule=#id))+ 1x GET /EntityDefinitions(LogicalName='contoso_project')?$select=MetadataId,EntitySetName -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_tag')?$select=MetadataId,EntitySetName -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_task')?$select=MetadataId,EntitySetName -> 200+ 7x GET /appmodulecomponents?$select=objectid&$filter=_appmoduleidunique_value eq <id> and componenttype eq 62 -> 200+ 1x GET /appmodulecomponents?$select=objectid,componenttype&$filter=_appmoduleidunique_value eq <id> -> 200+ 1x GET /appmodulecomponents?$select=objectid,componenttype&$filter=_appmoduleidunique_value eq <id> and componenttype eq 1 -> 200+ 1x GET /appmodulecomponents?$select=objectid,componenttype&$filter=_appmoduleidunique_value eq <id> and componenttype eq 62&$top=1 -> 200+ 4x GET /appmodules(<id>)?$select=appmoduleid -> 200+ 9x GET /appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()?$select=appmoduleid,appmoduleidunique,componentstate&$filter=appmoduleid eq <id> -> 200+ 1x GET /appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()?$select=appmoduleid,appmoduleidunique,uniquename,componentstate -> 200+ 4x GET /appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()?$select=appmoduleid,name,uniquename,description,aiappdescription&$filter=appmoduleid eq <id>&$top=1 -> 200+ 1x GET /appmodules?$select=appmoduleid,appmoduleidunique&$filter=uniquename eq 'fabrikam_widgets'&$top=1 -> 200+ 1x GET /appmodules?$select=appmoduleid,appmoduleidunique,uniquename -> 200+ 1x GET /savedqueries?$select=savedqueryid&$filter=returnedtypecode eq 'contoso_project' and querytype eq 0 and statecode eq 0 -> 200+ 1x GET /savedqueries?$select=savedqueryid&$filter=returnedtypecode eq 'contoso_tag' and querytype eq 0 and statecode eq 0 -> 200+ 1x GET /savedqueries?$select=savedqueryid&$filter=returnedtypecode eq 'contoso_task' and querytype eq 0 and statecode eq 0 -> 200+ 1x GET /savedqueryvisualizations?$select=savedqueryvisualizationid&$filter=primaryentitytypecode eq 'contoso_project' -> 200+ 1x GET /savedqueryvisualizations?$select=savedqueryvisualizationid&$filter=primaryentitytypecode eq 'contoso_tag' -> 200+ 1x GET /savedqueryvisualizations?$select=savedqueryvisualizationid&$filter=primaryentitytypecode eq 'contoso_task' -> 200+ 3x GET /sitemaps(<id>)?$select=sitemapid -> 200+ 3x GET /sitemaps/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()?$select=sitemapid,sitemapname,sitemapnameunique,sitemapxml&$filter=sitemapid eq <id>&$top=1 -> 200+ 1x GET /sitemaps/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()?$select=sitemapid,sitemapxml,componentstate,sitemapnameunique -> 200+ 1x GET /sitemaps?$select=sitemapxml&$filter=sitemapid eq <id>&$top=1 -> 200+ 1x GET /solutioncomponents?$select=objectid,componenttype,rootcomponentbehavior&$filter=_solutionid_value eq <id> and (componenttype eq 10200) -> 200+ 1x GET /solutions?$select=solutionid&$filter=uniquename eq 'ContosoKitchen'&$top=1 -> 200+ 1x GET /systemforms?$select=formid&$filter=objecttypecode eq 'contoso_project' and type eq 2 and formactivationstate eq 1 -> 200+ 1x GET /systemforms?$select=formid&$filter=objecttypecode eq 'contoso_tag' and type eq 2 and formactivationstate eq 1 -> 200+ 1x GET /systemforms?$select=formid&$filter=objecttypecode eq 'contoso_task' and type eq 2 and formactivationstate eq 1 -> 200+ 11x GET /uxagentprojectfiles(<id>)/filecontent/$value -> 200+ 4x GET /uxagentprojectfiles?$select=uxagentprojectfileid,filename,filetype&$filter=_uxagentprojectid_value eq <id> -> 200+ 2x GET /uxagentprojectfiles?$select=uxagentprojectfileid,versionnumber,_uxagentprojectid_value&$filter=_uxagentprojectid_value eq <id> -> 200+ 4x GET /uxagentprojects(<id>)?$select=uxagentprojectid,name -> 200+ 1x GET /uxagentprojects/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()?$select=uxagentprojectid&$filter=uxagentprojectid eq <id> -> 200+ 2x GET /uxagentprojects?$select=uxagentprojectid,versionnumber&$filter=uxagentprojectid eq <id> -> 200+ 1x PATCH /appmodules(<id>)?$select=appmoduleid #5c895103 -> 200+ 1x PATCH /sitemaps(<id>)?$select=sitemapid #a48e6542 -> 200+ 1x POST /AddAppComponents #55bd8832 -> 204+ 1x POST /PublishXml #1b71745d -> 204+## up to publish 5: importexportxml(appmodules(appmodule=#id) entities(entity=contoso_project entity=contoso_tag entity=contoso_task))+ 1x GET /EntityDefinitions(LogicalName='appmodule')?$select=LogicalName,Privileges -> 200+ 1x GET /EntityDefinitions(LogicalName='appmodulecomponent')?$select=EntitySetName -> 200+ 1x GET /EntityDefinitions(LogicalName='businessunit')?$select=EntitySetName -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_project')?$select=LogicalName,Privileges -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_tag')?$select=LogicalName,Privileges -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_task')?$select=LogicalName,Privileges -> 200+ 1x GET /EntityDefinitions(LogicalName='role')?$select=EntitySetName -> 200+ 1x GET /EntityDefinitions(LogicalName='savedquery')?$select=EntitySetName -> 200+ 4x GET /appmodulecomponents?$select=objectid&$filter=_appmoduleidunique_value eq <id> and componenttype eq 62 -> 200+ 1x GET /appmodulecomponents?$select=objectid,componenttype&$filter=_appmoduleidunique_value eq <id> and componenttype eq 26 -> 200+ 2x GET /appmodules(<id>)?$select=appmoduleid -> 200+ 5x GET /appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()?$select=appmoduleid,appmoduleidunique,componentstate&$filter=appmoduleid eq <id> -> 200+ 2x GET /appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()?$select=appmoduleid,name,uniquename,description,aiappdescription&$filter=appmoduleid eq <id>&$top=1 -> 200+ 1x GET /appsettings/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()?$select=appsettingid,value&$filter=_parentappmoduleid_value eq <id> and _settingdefinitionid_value eq <id> -> 200+ 2x GET /businessunits?$select=businessunitid&$filter=_parentbusinessunitid_value eq null&$top=1 -> 200+ 1x GET /roles?$select=roleid,description,ismanaged&$filter=name eq 'Kitchen Planner' and _businessunitid_value eq <id> -> 200+ 1x GET /roles?$select=roleid,name,ismanaged&$filter=name eq 'Basic User' and _businessunitid_value eq <id>&$top=5 -> 200+ 9x GET /savedqueries(<id>)/Microsoft.Dynamics.CRM.RetrieveUnpublished()?$select=savedqueryid,name,description,fetchxml,layoutxml,querytype,returnedtypecode,isdefault -> 200+ 9x GET /savedqueries(<id>)?$select=savedqueryid -> 200+ 1x GET /savedqueries?$select=savedqueryid&$filter=returnedtypecode eq 'contoso_project' and querytype eq 0 and isdefault eq true&$top=1 -> 200+ 1x GET /savedqueryvisualizations(<id>)/Microsoft.Dynamics.CRM.RetrieveUnpublished()?$select=savedqueryvisualizationid,name,description,primaryentitytypecode,datadescription,presentationdescription,charttype,type,isdefault -> 200+ 1x GET /savedqueryvisualizations(<id>)?$select=savedqueryvisualizationid -> 200+ 1x GET /settingdefinitions?$select=settingdefinitionid,uniquename,displayname&$filter=uniquename eq 'HeaderAndNavigationRefresh' -> 200+ 2x GET /sitemaps(<id>)?$select=sitemapid -> 200+ 2x GET /sitemaps/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()?$select=sitemapid,sitemapname,sitemapnameunique,sitemapxml&$filter=sitemapid eq <id>&$top=1 -> 200+ 4x GET /systemforms(<id>)/Microsoft.Dynamics.CRM.RetrieveUnpublished()?$select=formid,formxml,name,type,objecttypecode,formpresentation,formactivationstate,uniquename,description,versionnumber -> 200+ 2x GET /systemforms(<id>)/Microsoft.Dynamics.CRM.RetrieveUnpublished()?$select=formid,formxml,type -> 200+ 1x GET /systemforms(<id>)?$select=formid -> 200+ 1x PATCH /systemforms(<id>) #e39def73 -> 204+ 1x POST /PublishXml #1b71745d -> 204+ 1x POST /SaveSettingValue #9bbb6c67 -> 204+ 1x POST /appmodules(<id>)/appmoduleroles_association/$ref #f07e5c5f -> 400+ 1x POST /roles(<id>)/Microsoft.Dynamics.CRM.AddPrivilegesRole #497ea01a -> 204+ 1x POST /roles(<id>)/Microsoft.Dynamics.CRM.ReplacePrivilegesRole #20224ada -> 204+## after the last publish+ 1x GET /EntityDefinitions(LogicalName='contact')?$select=MetadataId -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_project')/Attributes/Microsoft.Dynamics.CRM.MultiSelectPicklistAttributeMetadata?$select=LogicalName&$expand=OptionSet($select=Options) -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_project')/Attributes/Microsoft.Dynamics.CRM.PicklistAttributeMetadata?$select=LogicalName&$expand=OptionSet($select=Options) -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_project')/Attributes/Microsoft.Dynamics.CRM.StateAttributeMetadata?$select=LogicalName&$expand=OptionSet($select=Options) -> 200+ 2x GET /EntityDefinitions(LogicalName='contoso_project')/Attributes/Microsoft.Dynamics.CRM.StatusAttributeMetadata?$select=LogicalName&$expand=OptionSet($select=Options) -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_project')/Attributes?$select=LogicalName,SchemaName,DisplayName,AttributeType,IsCustomAttribute -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_project')/Keys?$select=LogicalName,SchemaName,KeyAttributes -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_project')/ManyToManyRelationships?$select=SchemaName,Entity1LogicalName,Entity2LogicalName,IntersectEntityName,Entity1IntersectAttribute,Entity2IntersectAttribute -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_project')/ManyToOneRelationships?$select=SchemaName,ReferencedEntity,ReferencingAttribute -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_project')?$select=MetadataId -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_tag')/Attributes?$select=LogicalName,SchemaName,DisplayName,AttributeType,IsCustomAttribute -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_tag')?$select=MetadataId -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_task')/Attributes?$select=LogicalName,SchemaName,DisplayName,AttributeType,IsCustomAttribute -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_task')/ManyToManyRelationships?$select=SchemaName,Entity1LogicalName,Entity2LogicalName,IntersectEntityName,Entity1IntersectAttribute,Entity2IntersectAttribute -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_task')/ManyToOneRelationships?$select=SchemaName,ReferencedEntity,ReferencingAttribute -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_task')?$select=MetadataId -> 200+ 1x GET /EntityDefinitions(LogicalName='entity')?$select=MetadataId -> 404+ 1x GET /EntityDefinitions(LogicalName='roleprivileges')?$select=EntitySetName -> 200+ 1x GET /EntityDefinitions?$select=LogicalName,SchemaName,EntitySetName,DisplayName,IsCustomEntity -> 200+ 1x GET /WhoAmI -> 200+ 1x GET /appactions?$select=appactionid,buttonlabeltext&$filter=contextvalue eq 'contoso_project'&$top=1 -> 200+ 1x GET /appmodulecomponents?$select=objectid,componenttype&$filter=_appmoduleidunique_value eq <id> and componenttype eq 1 -> 200+ 1x GET /appmodulecomponents?$select=objectid,componenttype&$filter=_appmoduleidunique_value eq <id> and componenttype eq 62&$top=1 -> 200+ 1x GET /appmodules(<id>)/appmoduleroles_association?$select=roleid -> 200+ 1x GET /appmodules?$select=appmoduleid&$filter=uniquename eq 'contoso_kitchensink'&$top=1 -> 200+ 2x GET /appmodules?$select=appmoduleid,appmoduleidunique&$filter=uniquename eq 'contoso_kitchensink'&$top=1 -> 200+ 1x GET /businessunits?$select=businessunitid&$filter=_parentbusinessunitid_value eq null&$top=1 -> 200+ 2x GET /roleprivilegescollection?$select=privilegeid,privilegedepthmask&$filter=roleid eq <id> -> 200+ 1x GET /roles?$select=roleid,description,ismanaged&$filter=name eq 'Kitchen Planner' and _businessunitid_value eq <id>&$top=5 -> 200+ 1x GET /roles?$select=roleid,name&$filter=name eq 'Basic User' and _businessunitid_value eq <id>&$top=5 -> 200+ 1x GET /savedqueries?$select=returnedtypecode&$filter=savedqueryid eq <id>&$top=1 -> 200+ 1x GET /savedqueries?$select=savedqueryid,layoutxml,fetchxml&$filter=returnedtypecode eq 'contoso_project' and name eq 'Open Projects'&$top=1 -> 200+ 1x GET /savedqueries?$select=savedqueryid,layoutxml,fetchxml&$filter=returnedtypecode eq 'contoso_task' and name eq 'My Open Tasks'&$top=1 -> 200+ 1x GET /savedqueries?$select=savedqueryid,layoutxml,fetchxml&$filter=returnedtypecode eq 'contoso_task' and name eq 'Open Tasks'&$top=1 -> 200+ 1x GET /savedqueryvisualizations?$select=primaryentitytypecode&$filter=savedqueryvisualizationid eq <id>&$top=1 -> 200+ 1x GET /savedqueryvisualizations?$select=savedqueryvisualizationid&$filter=primaryentitytypecode eq 'contoso_project' and name eq 'Projects by Priority'&$top=1 -> 200+ 1x GET /sitemaps?$select=sitemapxml&$filter=sitemapid eq <id>&$top=1 -> 200+ 1x GET /systemforms(<id>)/Microsoft.Dynamics.CRM.RetrieveUnpublished()?$select=formid,name,description,formxml,type,objecttypecode,istabletenabled,iscustomizable,componentstate,versionnumber -> 200+ 2x GET /systemforms(<id>)/Microsoft.Dynamics.CRM.RetrieveUnpublished()?$select=formxml -> 200+ 1x GET /systemforms/Microsoft.Dynamics.CRM.RetrieveFilteredForms(EntityLogicalName=@e,FormType=@t,User=@u)?@e='contoso_task'&@t=2&@u={'@odata.id':'systemusers(<id>)'} -> 200+ 2x GET /systemforms?$select=formid&$filter=objecttypecode eq 'contoso_project' and name eq 'Project Card' and type eq 6&$top=2 -> 200+ 2x GET /systemforms?$select=formid&$filter=objecttypecode eq 'contoso_project' and name eq 'Project' and type eq 2&$top=2 -> 200+ 2x GET /systemforms?$select=formid&$filter=objecttypecode eq 'contoso_task' and name eq 'Task Quick Create' and type eq 7&$top=2 -> 200+ 2x GET /systemforms?$select=formid&$filter=objecttypecode eq 'contoso_task' and name eq 'Task' and type eq 2&$top=2 -> 200+ 2x GET /systemforms?$select=formid,formxml&$filter=formid eq <id>&$top=1 -> 200+ 4x GET /systemforms?$select=formid,isdefault,formxml&$filter=formid eq <id>&$top=1 -> 200+ 1x GET /systemforms?$select=formid,name&$filter=objecttypecode eq 'contoso_task' and type eq 2&$top=250 -> 200+ 1x GET /systemforms?$select=formid,name&$filter=type eq 0 and name eq 'Kitchen Overview' -> 200+ 1x GET /uxagentprojects?$select=uxagentprojectid,name -> 200+ 1x GET /webresourceset?$select=content&$filter=name eq 'contoso_kitchensink_pagemanifest'&$top=1 -> 200+ 1x GET /webresourceset?$select=webresourceid,content&$filter=name eq 'contoso_project.js'&$top=1 -> 200+ 1x GET /webresourceset?$select=webresourceid,content&$filter=name eq 'contoso_projecticon.svg'&$top=1 -> 200+# shapes+#17143fc8 {@odata.type:string,AttributeType:string,AttributeTypeName:{Value:string},DisplayName:{@odata.type:string,LocalizedLabels:[1x{@odata.type:string,Label:string,LanguageCode:number}]},FormatName:{Value:string},MaxLength:number,RequiredLevel:{CanBeChanged:boolean,ManagedPropertyLogicalName:string,Value:string},SchemaName:string}+#1b71745d {ParameterXml:string}+#20224ada {Privileges:[5x{Depth:string,PrivilegeId:string}]}+#2b71ae7d {@odata.type:string,ChangeTrackingEnabled:boolean,CollectionSchemaName:string,Description:{LocalizedLabels:[1x{HasChanged:null,IsManaged:boolean,Label:string,LanguageCode:number,MetadataId:string}],UserLocalizedLabel:{HasChanged:null,IsManaged:boolean,Label:string,LanguageCode:number,MetadataId:string}},DisplayCollectionName:{LocalizedLabels:[1x{HasChanged:null,IsManaged:boolean,Label:string,LanguageCode:number,MetadataId:string}],UserLocalizedLabel:{HasChanged:null,IsManaged:boolean,Label:string,LanguageCode:number,MetadataId:string}},DisplayName:{LocalizedLabels:[1x{HasChanged:null,IsManaged:boolean,Label:string,LanguageCode:number,MetadataId:string}],UserLocalizedLabel:{HasChanged:null,IsManaged:boolean,Label:string,LanguageCode:number,MetadataId:string}},EntitySetName:string,HasActivities:boolean,HasNotes:boolean,IconLargeName:null,IconMediumName:null,IconSmallName:null,IconVectorName:null,IsActivity:boolean,IsCustomEntity:boolean,IsIntersect:boolean,IsManaged:boolean,IsQuickCreateEnabled:boolean,LogicalCollectionName:string,LogicalName:string,MetadataId:string,ObjectTypeCode:number,OwnershipType:string,PrimaryIdAttribute:string,PrimaryImageAttribute:null,PrimaryNameAttribute:string,Privileges:[8x{CanBeBasic:boolean,CanBeDeep:boolean,CanBeEntityReference:boolean,CanBeGlobal:boolean,CanBeLocal:boolean,CanBeParentEntityReference:boolean,Name:string,PrivilegeId:string,PrivilegeType:string}],SchemaName:string,TableType:string}+#43dbd5f4 {[email protected]:string,agentconversationmessageid:string,message:string,messagecontext:string,messagesender:number}+#473287f8 string+#4940b353 {@odata.type:string,AttributeType:string,AttributeTypeName:{Value:string},DateTimeBehavior:{Value:string},DisplayName:{@odata.type:string,LocalizedLabels:[1x{@odata.type:string,Label:string,LanguageCode:number}]},Format:string,RequiredLevel:{CanBeChanged:boolean,ManagedPropertyLogicalName:string,Value:string},SchemaName:string}+#497ea01a {Privileges:[1x{Depth:string,PrivilegeId:string}]}+#55bd8832 {AppId:string,Components:[3x{@odata.id:string}|6x{@odata.type:string,formid:string}|9x{@odata.type:string,savedqueryid:string}|1x{@odata.type:string,savedqueryvisualizationid:string}]}+#5c895103 {description:string}+#8e40ff9d {name:string}+#97e1522c {description:string,fetchxml:string,layoutxml:string,name:string,returnedtypecode:string}+#9bb0a025 {isdefault:boolean}+#9bbb6c67 {AppUniqueName:string,SettingName:string,SolutionUniqueName:string,Value:string}+#a48e6542 {sitemapname:string,sitemapxml:string}+#d6b4b26e {@odata.type:string,ChangeTrackingEnabled:boolean,CollectionSchemaName:string,Description:{LocalizedLabels:[1x{HasChanged:null,IsManaged:boolean,Label:string,LanguageCode:number,MetadataId:string}],UserLocalizedLabel:{HasChanged:null,IsManaged:boolean,Label:string,LanguageCode:number,MetadataId:string}},DisplayCollectionName:{LocalizedLabels:[1x{HasChanged:null,IsManaged:boolean,Label:string,LanguageCode:number,MetadataId:string}],UserLocalizedLabel:{HasChanged:null,IsManaged:boolean,Label:string,LanguageCode:number,MetadataId:string}},DisplayName:{LocalizedLabels:[1x{HasChanged:null,IsManaged:boolean,Label:string,LanguageCode:number,MetadataId:string}],UserLocalizedLabel:{HasChanged:null,IsManaged:boolean,Label:string,LanguageCode:number,MetadataId:string}},EntitySetName:string,HasActivities:boolean,HasNotes:boolean,IconLargeName:null,IconMediumName:null,IconSmallName:null,IconVectorName:string,IsActivity:boolean,IsCustomEntity:boolean,IsIntersect:boolean,IsManaged:boolean,IsQuickCreateEnabled:boolean,LogicalCollectionName:string,LogicalName:string,MetadataId:string,ObjectTypeCode:number,OwnershipType:string,PrimaryIdAttribute:string,PrimaryImageAttribute:string,PrimaryNameAttribute:string,Privileges:[8x{CanBeBasic:boolean,CanBeDeep:boolean,CanBeEntityReference:boolean,CanBeGlobal:boolean,CanBeLocal:boolean,CanBeParentEntityReference:boolean,Name:string,PrivilegeId:string,PrivilegeType:string}],SchemaName:string,TableType:string}+#e0abe8e4 {formxml:string,name:string,objecttypecode:string,type:number}+#e39def73 {formxml:string}+#f07e5c5f {@odata.id:string}diff --git a/plugins/model-apps/scripts/tests/golden/lifecycle-trail.rebuild.txt b/plugins/model-apps/scripts/tests/golden/lifecycle-trail.rebuild.txtnew file mode 100644index 000000000..4a5b8bf21--- /dev/null+++ b/plugins/model-apps/scripts/tests/golden/lifecycle-trail.rebuild.txt@@ -0,0 +1,227 @@+# 333 requests, 4 publishes+## up to publish 1: importexportxml(entities(entity=contoso_project))+ 1x GET /EntityDefinitions(LogicalName='appmodule')?$select=EntitySetName -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_project') -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_project')/Attributes/Microsoft.Dynamics.CRM.MultiSelectPicklistAttributeMetadata?$select=LogicalName&$expand=OptionSet($select=Options) -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_project')/Attributes/Microsoft.Dynamics.CRM.PicklistAttributeMetadata?$select=LogicalName&$expand=OptionSet($select=Options) -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_project')/Attributes/Microsoft.Dynamics.CRM.StateAttributeMetadata?$select=LogicalName&$expand=OptionSet($select=Options) -> 200+ 2x GET /EntityDefinitions(LogicalName='contoso_project')/Attributes/Microsoft.Dynamics.CRM.StatusAttributeMetadata?$select=LogicalName&$expand=OptionSet($select=Options) -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_project')/Attributes?$select=LogicalName,RequiredLevel -> 200+ 2x GET /EntityDefinitions(LogicalName='contoso_project')/OneToManyRelationships?$select=SchemaName,ReferencingEntity,ReferencingAttribute -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_project')?$select=EntitySetName -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_project')?$select=LogicalName,EntitySetName&$expand=Keys($select=SchemaName,KeyAttributes) -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_tag')/Attributes?$select=LogicalName,RequiredLevel -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_tag')?$select=LogicalName,EntitySetName -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_task') -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_task')/Attributes?$select=LogicalName,RequiredLevel -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_task')/ManyToManyRelationships?$select=SchemaName,Entity1LogicalName,Entity2LogicalName,IntersectEntityName,Entity1IntersectAttribute,Entity2IntersectAttribute -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_task')?$select=EntitySetName -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_task')?$select=LogicalName,EntitySetName -> 200+ 1x GET /EntityDefinitions(LogicalName='solution')?$select=EntitySetName -> 200+ 1x GET /EntityDefinitions(LogicalName='webresource')?$select=EntitySetName -> 200+ 1x GET /GlobalOptionSetDefinitions(Name='contoso_stage')?$select=MetadataId -> 200+ 2x GET /appmodulecomponents?$select=objectid&$filter=_appmoduleidunique_value eq <id> and componenttype eq 62 -> 200+ 1x GET /appmodules(<id>)?$select=appmoduleid -> 200+ 2x GET /appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()?$select=appmoduleid,appmoduleidunique,componentstate&$filter=appmoduleid eq <id> -> 200+ 1x GET /appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()?$select=appmoduleid,name,uniquename,description,aiappdescription&$filter=appmoduleid eq <id>&$top=1 -> 200+ 2x GET /appmodules?$select=appmoduleid&$filter=uniquename eq 'contoso_kitchensink'&$top=1 -> 200+ 1x GET /contoso_projects?$select=contoso_name,contoso_projectid&$filter=contoso_name eq 'Apollo'&$top=5000 -> 200+ 1x GET /contoso_tasks?$select=contoso_title,contoso_taskid&$filter=contoso_title eq 'Kickoff'&$top=5000 -> 200+ 1x GET /sitemaps(<id>)?$select=sitemapid -> 200+ 1x GET /sitemaps/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()?$select=sitemapid,sitemapname,sitemapnameunique,sitemapxml&$filter=sitemapid eq <id>&$top=1 -> 200+ 2x GET /solutions?$select=solutionid&$filter=uniquename eq 'ContosoKitchen'&$top=1 -> 200+ 1x GET /webresourceset?$select=webresourceid,content&$filter=name eq 'contoso_project.js'&$top=1 -> 200+ 1x GET /webresourceset?$select=webresourceid,content&$filter=name eq 'contoso_projecticon.svg'&$top=1 -> 200+ 1x POST /PublishXml #1b71745d -> 204+ 1x PUT /EntityDefinitions(<id>) #2b71ae7d -> 204+ 1x PUT /EntityDefinitions(<id>) #d6b4b26e -> 204+## up to publish 2: importexportxml(entities(entity=contoso_project entity=contoso_tag entity=contoso_task))+ 1x GET /EntityDefinitions(LogicalName='appaction')?$select=EntitySetName -> 200+ 1x GET /EntityDefinitions(LogicalName='appmodulecomponent')?$select=EntitySetName -> 200+ 1x GET /EntityDefinitions(LogicalName='contact')?$select=MetadataId,EntitySetName -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_project')?$select=MetadataId,EntitySetName -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_task')?$select=MetadataId,EntitySetName -> 200+ 3x GET /EntityDefinitions(LogicalName='savedquery')?$select=EntitySetName -> 200+ 1x GET /EntityDefinitions(LogicalName='savedqueryvisualization')?$select=EntitySetName -> 200+ 1x GET /EntityDefinitions(LogicalName='solutioncomponent')?$select=EntitySetName -> 200+ 4x GET /EntityDefinitions(LogicalName='systemform')?$select=EntitySetName -> 200+ 1x GET /appactions?$select=appactionid,buttonlabeltext&$filter=contextvalue eq 'contoso_project'&$top=1 -> 200+ 1x GET /appmodulecomponents?$select=objectid,componenttype&$filter=_appmoduleidunique_value eq <id> and componenttype eq 59 -> 200+ 1x GET /appmodulecomponents?$select=objectid,componenttype&$filter=_appmoduleidunique_value eq <id> and componenttype eq 60 -> 200+ 1x GET /appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()?$select=appmoduleid,appmoduleidunique,componentstate&$filter=appmoduleid eq <id> -> 200+ 1x GET /appmodules?$select=appmoduleid&$filter=uniquename eq 'contoso_kitchensink'&$top=1 -> 200+ 7x GET /savedqueries(<id>)/Microsoft.Dynamics.CRM.RetrieveUnpublished()?$select=savedqueryid,name,description,fetchxml,layoutxml,querytype,returnedtypecode,isdefault -> 200+ 7x GET /savedqueries(<id>)?$select=savedqueryid -> 200+ 1x GET /savedqueries?$select=savedqueryid&$filter=returnedtypecode eq 'contoso_project' and name eq 'Open Projects'&$top=2 -> 200+ 1x GET /savedqueries?$select=savedqueryid&$filter=returnedtypecode eq 'contoso_task' and name eq 'My Open Tasks'&$top=2 -> 200+ 1x GET /savedqueries?$select=savedqueryid&$filter=returnedtypecode eq 'contoso_task' and name eq 'Open Tasks'&$top=2 -> 200+ 1x GET /savedqueries?$select=savedqueryid,name,canbedeleted,fetchxml,createdon&$filter=returnedtypecode eq 'contoso_project' and querytype eq 0 -> 200+ 1x GET /savedqueries?$select=savedqueryid,name,canbedeleted,fetchxml,createdon&$filter=returnedtypecode eq 'contoso_task' and querytype eq 0 -> 200+ 1x GET /savedqueryvisualizations(<id>)/Microsoft.Dynamics.CRM.RetrieveUnpublished()?$select=savedqueryvisualizationid,name,description,primaryentitytypecode,datadescription,presentationdescription,charttype,type,isdefault -> 200+ 1x GET /savedqueryvisualizations(<id>)?$select=savedqueryvisualizationid -> 200+ 1x GET /savedqueryvisualizations/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()?$select=savedqueryvisualizationid,primaryentitytypecode&$filter=savedqueryvisualizationid eq <id> -> 200+ 1x GET /savedqueryvisualizations?$select=savedqueryvisualizationid&$filter=primaryentitytypecode eq 'contoso_project' and name eq 'Projects by Priority'&$top=2 -> 200+ 1x GET /solutioncomponents?$select=objectid&$filter=_solutionid_value eq <id> and componenttype eq 60 and (objectid eq <id>)&$top=50 -> 200+ 1x GET /solutioncomponents?$select=objectid,componenttype,rootcomponentbehavior&$filter=_solutionid_value eq <id> and (componenttype eq 26 or componenttype eq 59 or componenttype eq 60 or componenttype eq 61 or componenttype eq 62 or componenttype eq 80 or componenttype eq 20 or componenttype eq 29 or componenttype eq 1) -> 200+ 2x GET /solutions?$select=solutionid&$filter=uniquename eq 'ContosoKitchen'&$top=1 -> 200+ 6x GET /systemforms(<id>)/Microsoft.Dynamics.CRM.RetrieveUnpublished()?$select=formid,formxml,name,type,objecttypecode,formpresentation,formactivationstate,uniquename,description,versionnumber -> 200+ 2x GET /systemforms(<id>)/Microsoft.Dynamics.CRM.RetrieveUnpublished()?$select=formid,formxml,type -> 200+ 1x GET /systemforms/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()?$select=formid,objecttypecode&$filter=formid eq <id> or formid eq <id> or formid eq <id> or formid eq <id> or formid eq <id> or formid eq <id> -> 200+ 1x GET /systemforms?$select=formid&$filter=objecttypecode eq 'contoso_project' and name eq 'Project Card' and type eq 6&$top=2 -> 200+ 1x GET /systemforms?$select=formid&$filter=objecttypecode eq 'contoso_project' and name eq 'Project' and type eq 2&$top=2 -> 200+ 1x GET /systemforms?$select=formid&$filter=objecttypecode eq 'contoso_task' and name eq 'Task Quick Create' and type eq 7&$top=2 -> 200+ 1x GET /systemforms?$select=formid&$filter=objecttypecode eq 'contoso_task' and name eq 'Task' and type eq 2&$top=2 -> 200+ 1x GET /systemforms?$select=formid,name&$filter=name eq 'Kitchen Overview' and type eq 0&$top=10 -> 200+ 1x GET /systemforms?$select=formid,name&$filter=objecttypecode eq 'contoso_task' and type eq 2 and formactivationstate eq 1&$top=250 -> 200+ 1x GET /webresourceset?$select=webresourceid&$filter=name eq 'contoso_kitchensink_icon'&$top=1 -> 200+ 4x PATCH /savedqueries(<id>)?$select=savedqueryid #97e1522c -> 200+ 2x PATCH /systemforms(<id>) #9bb0a025 -> 204+ 1x POST /PublishXml #1b71745d -> 204+## up to publish 3: importexportxml(appmodules(appmodule=#id))+ 1x GET /EntityDefinitions(LogicalName='contoso_project')?$select=MetadataId,EntitySetName -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_tag')?$select=MetadataId,EntitySetName -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_task')?$select=MetadataId,EntitySetName -> 200+ 1x GET /EntityDefinitions(LogicalName='sitemap')?$select=EntitySetName -> 200+ 1x GET /EntityDefinitions(LogicalName='uxagentproject')?$select=EntitySetName -> 200+ 1x GET /EntityDefinitions(LogicalName='uxagentproject')?$select=ObjectTypeCode -> 200+ 1x GET /EntityDefinitions(LogicalName='uxagentprojectfile')?$select=EntitySetName -> 200+ 1x GET /agentconversationmessages?$select=agentconversationmessageid,message,messagesender,createdon&$filter=_regardingobjectid_value eq <id>&$orderby=createdon asc,versionnumber asc -> 200+ 9x GET /appmodulecomponents?$select=objectid&$filter=_appmoduleidunique_value eq <id> and componenttype eq 62 -> 200+ 1x GET /appmodulecomponents?$select=objectid,componenttype&$filter=_appmoduleidunique_value eq <id> -> 200+ 2x GET /appmodulecomponents?$select=objectid,componenttype&$filter=_appmoduleidunique_value eq <id> and componenttype eq 1 -> 200+ 4x GET /appmodulecomponents?$select=objectid,componenttype&$filter=_appmoduleidunique_value eq <id> and componenttype eq 62&$top=1 -> 200+ 5x GET /appmodules(<id>)?$select=appmoduleid -> 200+ 12x GET /appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()?$select=appmoduleid,appmoduleidunique,componentstate&$filter=appmoduleid eq <id> -> 200+ 3x GET /appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()?$select=appmoduleid,appmoduleidunique,uniquename,componentstate -> 200+ 5x GET /appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()?$select=appmoduleid,name,uniquename,description,aiappdescription&$filter=appmoduleid eq <id>&$top=1 -> 200+ 1x GET /appmodules?$select=appmoduleid,appmoduleidunique&$filter=uniquename eq 'contoso_kitchensink'&$top=1 -> 200+ 3x GET /appmodules?$select=appmoduleid,appmoduleidunique&$filter=uniquename eq 'fabrikam_widgets'&$top=1 -> 200+ 3x GET /appmodules?$select=appmoduleid,appmoduleidunique,uniquename -> 200+ 1x GET /savedqueries?$select=savedqueryid&$filter=returnedtypecode eq 'contoso_project' and querytype eq 0 and statecode eq 0 -> 200+ 1x GET /savedqueries?$select=savedqueryid&$filter=returnedtypecode eq 'contoso_tag' and querytype eq 0 and statecode eq 0 -> 200+ 1x GET /savedqueries?$select=savedqueryid&$filter=returnedtypecode eq 'contoso_task' and querytype eq 0 and statecode eq 0 -> 200+ 1x GET /savedqueryvisualizations?$select=savedqueryvisualizationid&$filter=primaryentitytypecode eq 'contoso_project' -> 200+ 1x GET /savedqueryvisualizations?$select=savedqueryvisualizationid&$filter=primaryentitytypecode eq 'contoso_tag' -> 200+ 1x GET /savedqueryvisualizations?$select=savedqueryvisualizationid&$filter=primaryentitytypecode eq 'contoso_task' -> 200+ 4x GET /sitemaps(<id>)?$select=sitemapid -> 200+ 4x GET /sitemaps/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()?$select=sitemapid,sitemapname,sitemapnameunique,sitemapxml&$filter=sitemapid eq <id>&$top=1 -> 200+ 3x GET /sitemaps/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()?$select=sitemapid,sitemapxml,componentstate,sitemapnameunique -> 200+ 1x GET /sitemaps?$select=sitemapid&$filter=sitemapnameunique eq 'contoso_kitchensink'&$top=1 -> 200+ 4x GET /sitemaps?$select=sitemapxml&$filter=sitemapid eq <id>&$top=1 -> 200+ 1x GET /solutioncomponents?$select=objectid,componenttype,rootcomponentbehavior&$filter=_solutionid_value eq <id> and (componenttype eq 10200) -> 200+ 1x GET /solutions?$select=solutionid&$filter=uniquename eq 'ContosoKitchen'&$top=1 -> 200+ 1x GET /systemforms?$select=formid&$filter=objecttypecode eq 'contoso_project' and type eq 2 and formactivationstate eq 1 -> 200+ 1x GET /systemforms?$select=formid&$filter=objecttypecode eq 'contoso_tag' and type eq 2 and formactivationstate eq 1 -> 200+ 1x GET /systemforms?$select=formid&$filter=objecttypecode eq 'contoso_task' and type eq 2 and formactivationstate eq 1 -> 200+ 4x GET /uxagentprojectfiles(<id>)/filecontent/$value -> 200+ 1x GET /uxagentprojectfiles?$select=uxagentprojectfileid,filename,filetype&$filter=_uxagentprojectid_value eq <id> -> 200+ 1x GET /uxagentprojectfiles?$select=uxagentprojectfileid,versionnumber,_uxagentprojectid_value&$filter=_uxagentprojectid_value eq <id> -> 200+ 1x GET /uxagentprojects(<id>)?$select=uxagentprojectid,name -> 200+ 1x GET /uxagentprojects/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()?$select=uxagentprojectid&$filter=uxagentprojectid eq <id> -> 200+ 1x GET /uxagentprojects?$select=uxagentprojectid,name -> 200+ 1x GET /uxagentprojects?$select=uxagentprojectid,versionnumber&$filter=uxagentprojectid eq <id> -> 200+ 1x GET /webresourceset?$select=webresourceid,content&$filter=name eq 'contoso_kitchensink_pagemanifest'&$top=1 -> 200+ 1x PATCH /sitemaps(<id>)?$select=sitemapid #a48e6542 -> 200+ 1x POST /AddAppComponents #55bd8832 -> 204+ 1x POST /PublishXml #1b71745d -> 204+## up to publish 4: importexportxml(appmodules(appmodule=#id) entities(entity=contoso_project entity=contoso_task))+ 1x GET /EntityDefinitions(LogicalName='appmodule')?$select=LogicalName,Privileges -> 200+ 1x GET /EntityDefinitions(LogicalName='appmodulecomponent')?$select=EntitySetName -> 200+ 1x GET /EntityDefinitions(LogicalName='businessunit')?$select=EntitySetName -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_project')?$select=LogicalName,Privileges -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_tag')?$select=LogicalName,Privileges -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_task')?$select=LogicalName,Privileges -> 200+ 1x GET /EntityDefinitions(LogicalName='role')?$select=EntitySetName -> 200+ 1x GET /EntityDefinitions(LogicalName='savedquery')?$select=EntitySetName -> 200+ 4x GET /appmodulecomponents?$select=objectid&$filter=_appmoduleidunique_value eq <id> and componenttype eq 62 -> 200+ 1x GET /appmodulecomponents?$select=objectid,componenttype&$filter=_appmoduleidunique_value eq <id> and componenttype eq 26 -> 200+ 2x GET /appmodules(<id>)?$select=appmoduleid -> 200+ 5x GET /appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()?$select=appmoduleid,appmoduleidunique,componentstate&$filter=appmoduleid eq <id> -> 200+ 2x GET /appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()?$select=appmoduleid,name,uniquename,description,aiappdescription&$filter=appmoduleid eq <id>&$top=1 -> 200+ 1x GET /appsettings/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()?$select=appsettingid,value&$filter=_parentappmoduleid_value eq <id> and _settingdefinitionid_value eq <id> -> 200+ 2x GET /businessunits?$select=businessunitid&$filter=_parentbusinessunitid_value eq null&$top=1 -> 200+ 1x GET /roles?$select=roleid,description,ismanaged&$filter=name eq 'Kitchen Planner' and _businessunitid_value eq <id> -> 200+ 1x GET /roles?$select=roleid,name,ismanaged&$filter=name eq 'Basic User' and _businessunitid_value eq <id>&$top=5 -> 200+ 7x GET /savedqueries(<id>)/Microsoft.Dynamics.CRM.RetrieveUnpublished()?$select=savedqueryid,name,description,fetchxml,layoutxml,querytype,returnedtypecode,isdefault -> 200+ 7x GET /savedqueries(<id>)?$select=savedqueryid -> 200+ 1x GET /savedqueries?$select=savedqueryid&$filter=returnedtypecode eq 'contoso_project' and querytype eq 0 and isdefault eq true&$top=1 -> 200+ 1x GET /savedqueryvisualizations(<id>)/Microsoft.Dynamics.CRM.RetrieveUnpublished()?$select=savedqueryvisualizationid,name,description,primaryentitytypecode,datadescription,presentationdescription,charttype,type,isdefault -> 200+ 1x GET /savedqueryvisualizations(<id>)?$select=savedqueryvisualizationid -> 200+ 1x GET /settingdefinitions?$select=settingdefinitionid,uniquename,displayname&$filter=uniquename eq 'HeaderAndNavigationRefresh' -> 200+ 2x GET /sitemaps(<id>)?$select=sitemapid -> 200+ 2x GET /sitemaps/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()?$select=sitemapid,sitemapname,sitemapnameunique,sitemapxml&$filter=sitemapid eq <id>&$top=1 -> 200+ 4x GET /systemforms(<id>)/Microsoft.Dynamics.CRM.RetrieveUnpublished()?$select=formid,formxml,name,type,objecttypecode,formpresentation,formactivationstate,uniquename,description,versionnumber -> 200+ 2x GET /systemforms(<id>)/Microsoft.Dynamics.CRM.RetrieveUnpublished()?$select=formid,formxml,type -> 200+ 1x GET /systemforms(<id>)?$select=formid -> 200+ 1x PATCH /systemforms(<id>) #e39def73 -> 204+ 1x POST /PublishXml #1b71745d -> 204+ 1x POST /SaveSettingValue #9bbb6c67 -> 204+ 1x POST /appmodules(<id>)/appmoduleroles_association/$ref #f07e5c5f -> 400+ 1x POST /roles(<id>)/Microsoft.Dynamics.CRM.AddPrivilegesRole #497ea01a -> 204+ 1x POST /roles(<id>)/Microsoft.Dynamics.CRM.ReplacePrivilegesRole #20224ada -> 204+## after the last publish+ 1x GET /EntityDefinitions(LogicalName='contact')?$select=MetadataId -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_project')/Attributes/Microsoft.Dynamics.CRM.MultiSelectPicklistAttributeMetadata?$select=LogicalName&$expand=OptionSet($select=Options) -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_project')/Attributes/Microsoft.Dynamics.CRM.PicklistAttributeMetadata?$select=LogicalName&$expand=OptionSet($select=Options) -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_project')/Attributes/Microsoft.Dynamics.CRM.StateAttributeMetadata?$select=LogicalName&$expand=OptionSet($select=Options) -> 200+ 2x GET /EntityDefinitions(LogicalName='contoso_project')/Attributes/Microsoft.Dynamics.CRM.StatusAttributeMetadata?$select=LogicalName&$expand=OptionSet($select=Options) -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_project')/Attributes?$select=LogicalName,SchemaName,DisplayName,AttributeType,IsCustomAttribute -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_project')/Keys?$select=LogicalName,SchemaName,KeyAttributes -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_project')/ManyToManyRelationships?$select=SchemaName,Entity1LogicalName,Entity2LogicalName,IntersectEntityName,Entity1IntersectAttribute,Entity2IntersectAttribute -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_project')/ManyToOneRelationships?$select=SchemaName,ReferencedEntity,ReferencingAttribute -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_project')?$select=MetadataId -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_tag')/Attributes?$select=LogicalName,SchemaName,DisplayName,AttributeType,IsCustomAttribute -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_tag')?$select=MetadataId -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_task')/Attributes?$select=LogicalName,SchemaName,DisplayName,AttributeType,IsCustomAttribute -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_task')/ManyToManyRelationships?$select=SchemaName,Entity1LogicalName,Entity2LogicalName,IntersectEntityName,Entity1IntersectAttribute,Entity2IntersectAttribute -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_task')/ManyToOneRelationships?$select=SchemaName,ReferencedEntity,ReferencingAttribute -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_task')?$select=MetadataId -> 200+ 1x GET /EntityDefinitions(LogicalName='entity')?$select=MetadataId -> 404+ 1x GET /EntityDefinitions(LogicalName='roleprivileges')?$select=EntitySetName -> 200+ 1x GET /EntityDefinitions?$select=LogicalName,SchemaName,EntitySetName,DisplayName,IsCustomEntity -> 200+ 1x GET /WhoAmI -> 200+ 1x GET /appactions?$select=appactionid,buttonlabeltext&$filter=contextvalue eq 'contoso_project'&$top=1 -> 200+ 1x GET /appmodulecomponents?$select=objectid,componenttype&$filter=_appmoduleidunique_value eq <id> and componenttype eq 1 -> 200+ 1x GET /appmodulecomponents?$select=objectid,componenttype&$filter=_appmoduleidunique_value eq <id> and componenttype eq 62&$top=1 -> 200+ 1x GET /appmodules(<id>)/appmoduleroles_association?$select=roleid -> 200+ 1x GET /appmodules?$select=appmoduleid&$filter=uniquename eq 'contoso_kitchensink'&$top=1 -> 200+ 2x GET /appmodules?$select=appmoduleid,appmoduleidunique&$filter=uniquename eq 'contoso_kitchensink'&$top=1 -> 200+ 1x GET /businessunits?$select=businessunitid&$filter=_parentbusinessunitid_value eq null&$top=1 -> 200+ 2x GET /roleprivilegescollection?$select=privilegeid,privilegedepthmask&$filter=roleid eq <id> -> 200+ 1x GET /roles?$select=roleid,description,ismanaged&$filter=name eq 'Kitchen Planner' and _businessunitid_value eq <id>&$top=5 -> 200+ 1x GET /roles?$select=roleid,name&$filter=name eq 'Basic User' and _businessunitid_value eq <id>&$top=5 -> 200+ 1x GET /savedqueries?$select=returnedtypecode&$filter=savedqueryid eq <id>&$top=1 -> 200+ 1x GET /savedqueries?$select=savedqueryid,layoutxml,fetchxml&$filter=returnedtypecode eq 'contoso_project' and name eq 'Open Projects'&$top=1 -> 200+ 1x GET /savedqueries?$select=savedqueryid,layoutxml,fetchxml&$filter=returnedtypecode eq 'contoso_task' and name eq 'My Open Tasks'&$top=1 -> 200+ 1x GET /savedqueries?$select=savedqueryid,layoutxml,fetchxml&$filter=returnedtypecode eq 'contoso_task' and name eq 'Open Tasks'&$top=1 -> 200+ 1x GET /savedqueryvisualizations?$select=primaryentitytypecode&$filter=savedqueryvisualizationid eq <id>&$top=1 -> 200+ 1x GET /savedqueryvisualizations?$select=savedqueryvisualizationid&$filter=primaryentitytypecode eq 'contoso_project' and name eq 'Projects by Priority'&$top=1 -> 200+ 1x GET /sitemaps?$select=sitemapxml&$filter=sitemapid eq <id>&$top=1 -> 200+ 1x GET /systemforms(<id>)/Microsoft.Dynamics.CRM.RetrieveUnpublished()?$select=formid,name,description,formxml,type,objecttypecode,istabletenabled,iscustomizable,componentstate,versionnumber -> 200+ 2x GET /systemforms(<id>)/Microsoft.Dynamics.CRM.RetrieveUnpublished()?$select=formxml -> 200+ 1x GET /systemforms/Microsoft.Dynamics.CRM.RetrieveFilteredForms(EntityLogicalName=@e,FormType=@t,User=@u)?@e='contoso_task'&@t=2&@u={'@odata.id':'systemusers(<id>)'} -> 200+ 2x GET /systemforms?$select=formid&$filter=objecttypecode eq 'contoso_project' and name eq 'Project Card' and type eq 6&$top=2 -> 200+ 2x GET /systemforms?$select=formid&$filter=objecttypecode eq 'contoso_project' and name eq 'Project' and type eq 2&$top=2 -> 200+ 2x GET /systemforms?$select=formid&$filter=objecttypecode eq 'contoso_task' and name eq 'Task Quick Create' and type eq 7&$top=2 -> 200+ 2x GET /systemforms?$select=formid&$filter=objecttypecode eq 'contoso_task' and name eq 'Task' and type eq 2&$top=2 -> 200+ 2x GET /systemforms?$select=formid,formxml&$filter=formid eq <id>&$top=1 -> 200+ 4x GET /systemforms?$select=formid,isdefault,formxml&$filter=formid eq <id>&$top=1 -> 200+ 1x GET /systemforms?$select=formid,name&$filter=objecttypecode eq 'contoso_task' and type eq 2&$top=250 -> 200+ 1x GET /systemforms?$select=formid,name&$filter=type eq 0 and name eq 'Kitchen Overview' -> 200+ 1x GET /uxagentprojects?$select=uxagentprojectid,name -> 200+ 1x GET /webresourceset?$select=content&$filter=name eq 'contoso_kitchensink_pagemanifest'&$top=1 -> 200+ 1x GET /webresourceset?$select=webresourceid,content&$filter=name eq 'contoso_project.js'&$top=1 -> 200+ 1x GET /webresourceset?$select=webresourceid,content&$filter=name eq 'contoso_projecticon.svg'&$top=1 -> 200+# shapes+#1b71745d {ParameterXml:string}+#20224ada {Privileges:[5x{Depth:string,PrivilegeId:string}]}+#2b71ae7d {@odata.type:string,ChangeTrackingEnabled:boolean,CollectionSchemaName:string,Description:{LocalizedLabels:[1x{HasChanged:null,IsManaged:boolean,Label:string,LanguageCode:number,MetadataId:string}],UserLocalizedLabel:{HasChanged:null,IsManaged:boolean,Label:string,LanguageCode:number,MetadataId:string}},DisplayCollectionName:{LocalizedLabels:[1x{HasChanged:null,IsManaged:boolean,Label:string,LanguageCode:number,MetadataId:string}],UserLocalizedLabel:{HasChanged:null,IsManaged:boolean,Label:string,LanguageCode:number,MetadataId:string}},DisplayName:{LocalizedLabels:[1x{HasChanged:null,IsManaged:boolean,Label:string,LanguageCode:number,MetadataId:string}],UserLocalizedLabel:{HasChanged:null,IsManaged:boolean,Label:string,LanguageCode:number,MetadataId:string}},EntitySetName:string,HasActivities:boolean,HasNotes:boolean,IconLargeName:null,IconMediumName:null,IconSmallName:null,IconVectorName:null,IsActivity:boolean,IsCustomEntity:boolean,IsIntersect:boolean,IsManaged:boolean,IsQuickCreateEnabled:boolean,LogicalCollectionName:string,LogicalName:string,MetadataId:string,ObjectTypeCode:number,OwnershipType:string,PrimaryIdAttribute:string,PrimaryImageAttribute:null,PrimaryNameAttribute:string,Privileges:[8x{CanBeBasic:boolean,CanBeDeep:boolean,CanBeEntityReference:boolean,CanBeGlobal:boolean,CanBeLocal:boolean,CanBeParentEntityReference:boolean,Name:string,PrivilegeId:string,PrivilegeType:string}],SchemaName:string,TableType:string}+#497ea01a {Privileges:[1x{Depth:string,PrivilegeId:string}]}+#55bd8832 {AppId:string,Components:[3x{@odata.id:string}|6x{@odata.type:string,formid:string}|9x{@odata.type:string,savedqueryid:string}|1x{@odata.type:string,savedqueryvisualizationid:string}]}+#97e1522c {description:string,fetchxml:string,layoutxml:string,name:string,returnedtypecode:string}+#9bb0a025 {isdefault:boolean}+#9bbb6c67 {AppUniqueName:string,SettingName:string,SolutionUniqueName:string,Value:string}+#a48e6542 {sitemapname:string,sitemapxml:string}+#d6b4b26e {@odata.type:string,ChangeTrackingEnabled:boolean,CollectionSchemaName:string,Description:{LocalizedLabels:[1x{HasChanged:null,IsManaged:boolean,Label:string,LanguageCode:number,MetadataId:string}],UserLocalizedLabel:{HasChanged:null,IsManaged:boolean,Label:string,LanguageCode:number,MetadataId:string}},DisplayCollectionName:{LocalizedLabels:[1x{HasChanged:null,IsManaged:boolean,Label:string,LanguageCode:number,MetadataId:string}],UserLocalizedLabel:{HasChanged:null,IsManaged:boolean,Label:string,LanguageCode:number,MetadataId:string}},DisplayName:{LocalizedLabels:[1x{HasChanged:null,IsManaged:boolean,Label:string,LanguageCode:number,MetadataId:string}],UserLocalizedLabel:{HasChanged:null,IsManaged:boolean,Label:string,LanguageCode:number,MetadataId:string}},EntitySetName:string,HasActivities:boolean,HasNotes:boolean,IconLargeName:null,IconMediumName:null,IconSmallName:null,IconVectorName:string,IsActivity:boolean,IsCustomEntity:boolean,IsIntersect:boolean,IsManaged:boolean,IsQuickCreateEnabled:boolean,LogicalCollectionName:string,LogicalName:string,MetadataId:string,ObjectTypeCode:number,OwnershipType:string,PrimaryIdAttribute:string,PrimaryImageAttribute:string,PrimaryNameAttribute:string,Privileges:[8x{CanBeBasic:boolean,CanBeDeep:boolean,CanBeEntityReference:boolean,CanBeGlobal:boolean,CanBeLocal:boolean,CanBeParentEntityReference:boolean,Name:string,PrivilegeId:string,PrivilegeType:string}],SchemaName:string,TableType:string}+#e39def73 {formxml:string}+#f07e5c5f {@odata.id:string}diff --git a/plugins/model-apps/scripts/tests/golden/lifecycle-trail.teardown.txt b/plugins/model-apps/scripts/tests/golden/lifecycle-trail.teardown.txtnew file mode 100644index 000000000..fe4978340--- /dev/null+++ b/plugins/model-apps/scripts/tests/golden/lifecycle-trail.teardown.txt@@ -0,0 +1,89 @@+# 129 requests, 1 publishes+## up to publish 1: importexportxml(entities(entity=contoso_project entity=contoso_task))+ 4x DELETE /agentconversationmessages(<id>) -> 204+ 4x DELETE /appactions(<id>) -> 204+ 1x DELETE /roles(<id>) -> 204+ 3x DELETE /savedqueries(<id>) -> 204+ 1x DELETE /savedqueryvisualizations(<id>) -> 204+ 5x DELETE /systemforms(<id>) -> 204+ 1x DELETE /uxagentprojects(<id>) -> 204+ 1x GET /EntityDefinitions(LogicalName='appaction')?$select=EntitySetName -> 200+ 1x GET /EntityDefinitions(LogicalName='appmodule')?$select=EntitySetName -> 200+ 1x GET /EntityDefinitions(LogicalName='appmodulecomponent')?$select=EntitySetName -> 200+ 1x GET /EntityDefinitions(LogicalName='businessunit')?$select=EntitySetName -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_project')?$select=MetadataId -> 200+ 1x GET /EntityDefinitions(LogicalName='role')?$select=EntitySetName -> 200+ 1x GET /EntityDefinitions(LogicalName='savedquery')?$select=EntitySetName -> 200+ 1x GET /EntityDefinitions(LogicalName='savedqueryvisualization')?$select=EntitySetName -> 200+ 1x GET /EntityDefinitions(LogicalName='sitemap')?$select=EntitySetName -> 200+ 1x GET /EntityDefinitions(LogicalName='solution')?$select=EntitySetName -> 200+ 1x GET /EntityDefinitions(LogicalName='solutioncomponent')?$select=EntitySetName -> 200+ 1x GET /EntityDefinitions(LogicalName='systemform')?$select=EntitySetName -> 200+ 1x GET /EntityDefinitions(LogicalName='webresource')?$select=EntitySetName -> 200+ 2x GET /agentconversationmessages?$select=agentconversationmessageid,message,messagesender,createdon&$filter=_regardingobjectid_value eq <id>&$orderby=createdon asc,versionnumber asc -> 200+ 1x GET /appactions?$select=appactionid&$filter=_contextentity_value eq <id> -> 200+ 1x GET /appactions?$select=appactionid,_parentappactionid_value&$filter=contextvalue eq 'contoso_project'&$top=200 -> 200+ 1x GET /appactions?$select=appactionid,buttonlabeltext&$filter=contextvalue eq 'contoso_project'&$top=1 -> 200+ 1x GET /appmodulecomponents?$select=_appmoduleidunique_value&$filter=componenttype eq 62 and objectid eq <id> -> 200+ 2x GET /appmodulecomponents?$select=objectid&$filter=_appmoduleidunique_value eq <id> and componenttype eq 62 -> 200+ 1x GET /appmodulecomponents?$select=objectid,componenttype&$filter=_appmoduleidunique_value eq <id> and componenttype eq 62&$top=1 -> 200+ 1x GET /appmodules(<id>)?$select=appmoduleid,name,uniquename,description,aiappdescription -> 200+ 1x GET /appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()?$select=appmoduleid&$filter=appmoduleidunique eq <id> -> 200+ 2x GET /appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()?$select=appmoduleid,appmoduleidunique,componentstate&$filter=appmoduleid eq <id> -> 200+ 1x GET /appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()?$select=appmoduleid,name,appmoduleidunique&$filter=uniquename eq 'contoso_kitchensink'&$top=1 -> 200+ 1x GET /appmodules?$select=appmoduleid&$filter=appmoduleroles_association/any(x:x/roleid eq <id>)&$top=1 -> 200+ 1x GET /appmodules?$select=appmoduleid,appmoduleidunique&$filter=uniquename eq 'contoso_kitchensink'&$top=1 -> 200+ 1x GET /businessunits?$select=businessunitid&$filter=_parentbusinessunitid_value eq null&$top=1 -> 200+ 1x GET /roles?$select=roleid,name,description,ismanaged&$filter=name eq 'Kitchen Planner' and _businessunitid_value eq <id>&$top=50 -> 200+ 8x GET /savedqueries(<id>)/Microsoft.Dynamics.CRM.RetrieveUnpublished()?$select=savedqueryid,name,description,fetchxml,layoutxml,querytype,returnedtypecode,isdefault -> 200+ 8x GET /savedqueries(<id>)?$select=savedqueryid -> 200+ 1x GET /savedqueries?$select=savedqueryid,name&$filter=name eq 'My Open Tasks' and returnedtypecode eq 'contoso_task'&$top=10 -> 200+ 1x GET /savedqueries?$select=savedqueryid,name&$filter=name eq 'Open Projects' and returnedtypecode eq 'contoso_project'&$top=10 -> 200+ 1x GET /savedqueries?$select=savedqueryid,name&$filter=name eq 'Open Tasks' and returnedtypecode eq 'contoso_task'&$top=10 -> 200+ 1x GET /savedqueries?$select=savedqueryid,name,canbedeleted,fetchxml,createdon&$filter=returnedtypecode eq 'contoso_project' and querytype eq 0 -> 200+ 1x GET /savedqueries?$select=savedqueryid,name,canbedeleted,fetchxml,createdon&$filter=returnedtypecode eq 'contoso_task' and querytype eq 0 -> 200+ 1x GET /savedqueryvisualizations?$select=savedqueryvisualizationid,name&$filter=name eq 'Projects by Priority' and primaryentitytypecode eq 'contoso_project'&$top=10 -> 200+ 1x GET /sitemaps(<id>)?$select=sitemapid -> 200+ 1x GET /sitemaps/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()?$select=sitemapid,sitemapnameunique,sitemapxml&$filter=sitemapid eq <id>&$top=1 -> 200+ 1x GET /sitemaps?$select=sitemapxml&$filter=sitemapid eq <id>&$top=1 -> 200+ 1x GET /solutioncomponents?$select=objectid&$filter=_solutionid_value eq <id> and componenttype eq 60 and (objectid eq <id>)&$top=50 -> 200+ 1x GET /solutions?$select=solutionid&$filter=uniquename eq 'ContosoKitchen'&$top=1 -> 200+ 5x GET /systemforms(<id>)/Microsoft.Dynamics.CRM.RetrieveUnpublished()?$select=type -> 200+ 1x GET /systemforms?$select=formid&$filter=objecttypecode eq 'contoso_project' and name eq 'Project Card' and type eq 6&$top=2 -> 200+ 1x GET /systemforms?$select=formid&$filter=objecttypecode eq 'contoso_project' and name eq 'Project' and type eq 2&$top=2 -> 200+ 1x GET /systemforms?$select=formid&$filter=objecttypecode eq 'contoso_task' and name eq 'Task Quick Create' and type eq 7&$top=2 -> 200+ 1x GET /systemforms?$select=formid&$filter=objecttypecode eq 'contoso_task' and name eq 'Task' and type eq 2&$top=2 -> 200+ 1x GET /systemforms?$select=formid,formactivationstate,isdefault&$filter=objecttypecode eq 'contoso_project' and type eq 2&$top=50 -> 200+ 1x GET /systemforms?$select=formid,formactivationstate,isdefault&$filter=objecttypecode eq 'contoso_task' and type eq 2&$top=50 -> 200+ 1x GET /systemforms?$select=formid,name&$filter=name eq 'Kitchen Overview' and type eq 0&$top=10 -> 200+ 1x GET /uxagentprojects/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()?$select=uxagentprojectid,name,componentstate&$filter=uxagentprojectid eq <id> -> 200+ 1x GET /webresourceset?$select=content&$filter=name eq 'contoso_kitchensink_pagemanifest'&$top=1 -> 200+ 4x PATCH /savedqueries(<id>)?$select=savedqueryid #97e1522c -> 200+ 2x PATCH /systemforms(<id>) #9bb0a025 -> 204+ 1x POST /$batch -> 200+ > DELETE /appmodules(<id>)+ > DELETE /sitemaps(<id>)+ 1x POST /PublishXml #1b71745d -> 204+## after the last publish+ 1x DELETE /EntityDefinitions(LogicalName='contoso_project') -> 204+ 1x DELETE /EntityDefinitions(LogicalName='contoso_tag') -> 204+ 1x DELETE /EntityDefinitions(LogicalName='contoso_task') -> 204+ 1x DELETE /GlobalOptionSetDefinitions(Name='contoso_stage') -> 204+ 2x DELETE /RelationshipDefinitions(<id>) -> 204+ 1x DELETE /solutions(<id>) -> 204+ 4x DELETE /webresourceset(<id>) -> 204+ 3x GET /EntityDefinitions?$select=LogicalName,SchemaName,EntitySetName,DisplayName,IsCustomEntity -> 200+ 1x GET /RelationshipDefinitions?$filter=SchemaName eq 'contoso_project_contoso_project'&$select=MetadataId -> 200+ 1x GET /RelationshipDefinitions?$filter=SchemaName eq 'contoso_project_contoso_task'&$select=MetadataId -> 200+ 1x GET /RelationshipDefinitions?$filter=SchemaName eq 'contoso_tag_contoso_task'&$select=MetadataId -> 200+ 4x GET /savedqueries(<id>)/Microsoft.Dynamics.CRM.RetrieveUnpublished()?$select=savedqueryid,name,description,fetchxml,layoutxml,querytype,returnedtypecode,isdefault -> 200+ 4x GET /savedqueries(<id>)?$select=savedqueryid -> 200+ 1x GET /solutions?$select=solutionid,uniquename&$filter=uniquename eq 'ContosoKitchen'&$top=1 -> 200+ 1x GET /webresourceset?$select=webresourceid,name&$filter=name eq 'contoso_kitchensink_icon'&$top=1 -> 200+ 1x GET /webresourceset?$select=webresourceid,name&$filter=name eq 'contoso_kitchensink_pagemanifest'&$top=1 -> 200+ 1x GET /webresourceset?$select=webresourceid,name&$filter=name eq 'contoso_project.js'&$top=1 -> 200+ 1x GET /webresourceset?$select=webresourceid,name&$filter=name eq 'contoso_projecticon.svg'&$top=1 -> 200+# shapes+#1b71745d {ParameterXml:string}+#97e1522c {description:string,fetchxml:string,layoutxml:string,name:string,returnedtypecode:string}+#9bb0a025 {isdefault:boolean}diff --git a/plugins/model-apps/scripts/tests/golden/lifecycle-trail.verify.txt b/plugins/model-apps/scripts/tests/golden/lifecycle-trail.verify.txtnew file mode 100644index 000000000..58f617cad--- /dev/null+++ b/plugins/model-apps/scripts/tests/golden/lifecycle-trail.verify.txt@@ -0,0 +1,69 @@+# 78 requests, 0 publishes+## after the last publish+ 1x GET /EntityDefinitions(LogicalName='appaction')?$select=EntitySetName -> 200+ 1x GET /EntityDefinitions(LogicalName='appmodule')?$select=EntitySetName -> 200+ 1x GET /EntityDefinitions(LogicalName='appmodule')?$select=LogicalName,Privileges -> 200+ 1x GET /EntityDefinitions(LogicalName='appmodulecomponent')?$select=EntitySetName -> 200+ 1x GET /EntityDefinitions(LogicalName='businessunit')?$select=EntitySetName -> 200+ 1x GET /EntityDefinitions(LogicalName='contact')?$select=MetadataId -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_project')/Attributes/Microsoft.Dynamics.CRM.MultiSelectPicklistAttributeMetadata?$select=LogicalName&$expand=OptionSet($select=Options) -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_project')/Attributes/Microsoft.Dynamics.CRM.PicklistAttributeMetadata?$select=LogicalName&$expand=OptionSet($select=Options) -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_project')/Attributes/Microsoft.Dynamics.CRM.StateAttributeMetadata?$select=LogicalName&$expand=OptionSet($select=Options) -> 200+ 2x GET /EntityDefinitions(LogicalName='contoso_project')/Attributes/Microsoft.Dynamics.CRM.StatusAttributeMetadata?$select=LogicalName&$expand=OptionSet($select=Options) -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_project')/Attributes?$select=LogicalName,SchemaName,DisplayName,AttributeType,IsCustomAttribute -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_project')/Keys?$select=LogicalName,SchemaName,KeyAttributes -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_project')/ManyToManyRelationships?$select=SchemaName,Entity1LogicalName,Entity2LogicalName,IntersectEntityName,Entity1IntersectAttribute,Entity2IntersectAttribute -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_project')/ManyToOneRelationships?$select=SchemaName,ReferencedEntity,ReferencingAttribute -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_project')?$select=LogicalName,Privileges -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_project')?$select=MetadataId -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_tag')/Attributes?$select=LogicalName,SchemaName,DisplayName,AttributeType,IsCustomAttribute -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_tag')?$select=LogicalName,Privileges -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_tag')?$select=MetadataId -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_task')/Attributes?$select=LogicalName,SchemaName,DisplayName,AttributeType,IsCustomAttribute -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_task')/ManyToManyRelationships?$select=SchemaName,Entity1LogicalName,Entity2LogicalName,IntersectEntityName,Entity1IntersectAttribute,Entity2IntersectAttribute -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_task')/ManyToOneRelationships?$select=SchemaName,ReferencedEntity,ReferencingAttribute -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_task')?$select=LogicalName,Privileges -> 200+ 1x GET /EntityDefinitions(LogicalName='contoso_task')?$select=MetadataId -> 200+ 1x GET /EntityDefinitions(LogicalName='entity')?$select=MetadataId -> 404+ 1x GET /EntityDefinitions(LogicalName='role')?$select=EntitySetName -> 200+ 1x GET /EntityDefinitions(LogicalName='roleprivileges')?$select=EntitySetName -> 200+ 1x GET /EntityDefinitions(LogicalName='savedquery')?$select=EntitySetName -> 200+ 1x GET /EntityDefinitions(LogicalName='savedqueryvisualization')?$select=EntitySetName -> 200+ 1x GET /EntityDefinitions(LogicalName='sitemap')?$select=EntitySetName -> 200+ 1x GET /EntityDefinitions(LogicalName='systemform')?$select=EntitySetName -> 200+ 1x GET /EntityDefinitions(LogicalName='webresource')?$select=EntitySetName -> 200+ 1x GET /EntityDefinitions?$select=LogicalName,SchemaName,EntitySetName,DisplayName,IsCustomEntity -> 200+ 1x GET /WhoAmI -> 200+ 1x GET /appactions?$select=appactionid,buttonlabeltext&$filter=contextvalue eq 'contoso_project'&$top=1 -> 200+ 1x GET /appmodulecomponents?$select=objectid,componenttype&$filter=_appmoduleidunique_value eq <id> and componenttype eq 1 -> 200+ 1x GET /appmodulecomponents?$select=objectid,componenttype&$filter=_appmoduleidunique_value eq <id> and componenttype eq 62&$top=1 -> 200+ 1x GET /appmodules(<id>)/appmoduleroles_association?$select=roleid -> 200+ 1x GET /appmodules?$select=appmoduleid&$filter=uniquename eq 'contoso_kitchensink'&$top=1 -> 200+ 2x GET /appmodules?$select=appmoduleid,appmoduleidunique&$filter=uniquename eq 'contoso_kitchensink'&$top=1 -> 200+ 1x GET /businessunits?$select=businessunitid&$filter=_parentbusinessunitid_value eq null&$top=1 -> 200+ 2x GET /roleprivilegescollection?$select=privilegeid,privilegedepthmask&$filter=roleid eq <id> -> 200+ 1x GET /roles?$select=roleid,description,ismanaged&$filter=name eq 'Kitchen Planner' and _businessunitid_value eq <id>&$top=5 -> 200+ 1x GET /roles?$select=roleid,name&$filter=name eq 'Basic User' and _businessunitid_value eq <id>&$top=5 -> 200+ 1x GET /savedqueries?$select=returnedtypecode&$filter=savedqueryid eq <id>&$top=1 -> 200+ 1x GET /savedqueries?$select=savedqueryid,layoutxml,fetchxml&$filter=returnedtypecode eq 'contoso_project' and name eq 'Open Projects'&$top=1 -> 200+ 1x GET /savedqueries?$select=savedqueryid,layoutxml,fetchxml&$filter=returnedtypecode eq 'contoso_task' and name eq 'My Open Tasks'&$top=1 -> 200+ 1x GET /savedqueries?$select=savedqueryid,layoutxml,fetchxml&$filter=returnedtypecode eq 'contoso_task' and name eq 'Open Tasks'&$top=1 -> 200+ 1x GET /savedqueryvisualizations?$select=primaryentitytypecode&$filter=savedqueryvisualizationid eq <id>&$top=1 -> 200+ 1x GET /savedqueryvisualizations?$select=savedqueryvisualizationid&$filter=primaryentitytypecode eq 'contoso_project' and name eq 'Projects by Priority'&$top=1 -> 200+ 1x GET /sitemaps?$select=sitemapxml&$filter=sitemapid eq <id>&$top=1 -> 200+ 1x GET /systemforms(<id>)/Microsoft.Dynamics.CRM.RetrieveUnpublished()?$select=formid,name,description,formxml,type,objecttypecode,istabletenabled,iscustomizable,componentstate,versionnumber -> 200+ 2x GET /systemforms(<id>)/Microsoft.Dynamics.CRM.RetrieveUnpublished()?$select=formxml -> 200+ 1x GET /systemforms/Microsoft.Dynamics.CRM.RetrieveFilteredForms(EntityLogicalName=@e,FormType=@t,User=@u)?@e='contoso_task'&@t=2&@u={'@odata.id':'systemusers(<id>)'} -> 200+ 2x GET /systemforms?$select=formid&$filter=objecttypecode eq 'contoso_project' and name eq 'Project Card' and type eq 6&$top=2 -> 200+ 2x GET /systemforms?$select=formid&$filter=objecttypecode eq 'contoso_project' and name eq 'Project' and type eq 2&$top=2 -> 200+ 2x GET /systemforms?$select=formid&$filter=objecttypecode eq 'contoso_task' and name eq 'Task Quick Create' and type eq 7&$top=2 -> 200+ 2x GET /systemforms?$select=formid&$filter=objecttypecode eq 'contoso_task' and name eq 'Task' and type eq 2&$top=2 -> 200+ 2x GET /systemforms?$select=formid,formxml&$filter=formid eq <id>&$top=1 -> 200+ 4x GET /systemforms?$select=formid,isdefault,formxml&$filter=formid eq <id>&$top=1 -> 200+ 1x GET /systemforms?$select=formid,name&$filter=objecttypecode eq 'contoso_task' and type eq 2&$top=250 -> 200+ 1x GET /systemforms?$select=formid,name&$filter=type eq 0 and name eq 'Kitchen Overview' -> 200+ 1x GET /uxagentprojects?$select=uxagentprojectid,name -> 200+ 1x GET /webresourceset?$select=content&$filter=name eq 'contoso_kitchensink_pagemanifest'&$top=1 -> 200+ 1x GET /webresourceset?$select=webresourceid,content&$filter=name eq 'contoso_project.js'&$top=1 -> 200+ 1x GET /webresourceset?$select=webresourceid,content&$filter=name eq 'contoso_projecticon.svg'&$top=1 -> 200+# shapesdiff --git a/plugins/model-apps/scripts/tests/helpers/build-failure-diagnostics.js b/plugins/model-apps/scripts/tests/helpers/build-failure-diagnostics.jsnew file mode 100644index 000000000..121d03c77--- /dev/null+++ b/plugins/model-apps/scripts/tests/helpers/build-failure-diagnostics.js@@ -0,0 +1,220 @@+'use strict';+// What a test's unexpectedly failed build can say about itself, so one failure is enough to diagnose it.+//+// A build in a test runs over a workspace folder on disk. When it fails for a reason the test did not provoke (a file the+// build expected is not there), the assertion that surfaces is only the build's message, for example+// forms failed: ENOENT: no such file or directory, open '<workspace>/manifest.json'+// and the folder is removed straight afterwards, so a failure that never reproduces cannot be investigated. This records what+// the folders looked like at that moment: the whole error chain (name, code, message and stack of the error and of each+// `cause`), the path the failure names as missing and how much of it exists, and a bounded recursive listing of the folders+// the scenario owns.+//+// The error itself is NEVER changed: its message, code, phase and cause stay what the build threw, so a test that rejects with a+// pattern (assert.rejects(..., /push|500|simulated/i)) still checks the build's own text and not a listing that happens to hold+// one of its words. The diagnostics are kept apart (a non-enumerable `buildFailureDiagnostics` property and a pending list) and+// printed with `t.diagnostic` only when the test that threw them fails (installBuildFailureDiagnostics).+//+// Scope. Only the folders the caller names are listed, never their parent or any other folder; a missing path outside them is+// reported as such and not looked at. The walk stops after MAX_LISTING_ENTRIES entries, reads at most MAX_DIRECTORY_READS names+// from one folder, goes no deeper than MAX_DEPTH and never follows a link, so what a failure costs does not depend on what a+// folder holds. The text is passed through the plugin's output redaction and a Bearer-token mask before it is kept.+const fs = require('node:fs');+const path = require('node:path');+const { redactOutput } = require('../../lib/output-redaction.js');++const MAX_LISTING_ENTRIES = 200;+const MAX_DIRECTORY_READS = 500;+const MAX_DEPTH = 8;+const MAX_CHAIN_LENGTH = 8;++// An error followed by its `cause`s, outermost first. A cause is an Error, a plain object or a string, and a chain can+// loop, so stop at a repeat or at MAX_CHAIN_LENGTH.+function causeChain(error) {+ const chain = [];+ for (let current = error; current !== undefined && current !== null && chain.length < MAX_CHAIN_LENGTH && !chain.includes(current); current = current && current.cause) {+ chain.push(current);+ }+ return chain;+}++function describeLink(link, position) {+ if (link === null || typeof link !== 'object') return [` [${position}] ${String(link)}`];+ const name = link.name || (link.constructor && link.constructor.name) || 'Error';+ const facts = ['code', 'errno', 'syscall', 'path', 'phase']+ .filter((key) => link[key] !== undefined)+ .map((key) => `${key}=${JSON.stringify(link[key])}`);+ const lines = [` [${position}] ${name}${facts.length ? ` (${facts.join(', ')})` : ''}: ${link.message}`];+ if (typeof link.stack === 'string') lines.push(...link.stack.split(/\r?\n/).map((line) => ` ${line}`));+ return lines;+}++// Paths a failure reports as missing. A system error carries `path`; a wrapped one (the build quotes the cause's message)+// only has it in the text, where Node writes:+// ENOENT: no such file or directory, open 'C:\Users\maker\AppData\Local\Temp\rebuild-writes-aB3dEf\manifest.json'+function missingPaths(chain) {+ const found = new Set();+ for (const link of chain) {+ if (link === null || typeof link !== 'object') continue;+ if (link.code === 'ENOENT' && typeof link.path === 'string') found.add(link.path);+ for (const match of String(link.message || '').matchAll(/ENOENT[^'\r\n]*'([^'\r\n]+)'/g)) found.add(match[1]);+ }+ return [...found];+}++const isInside = (root, target) => {+ const relative = path.relative(path.resolve(root), path.resolve(target));+ return relative === '' || (!relative.startsWith('..') && !path.isAbsolute(relative));+};++// The deepest folder of the path that exists, looked for only from the path up to `root` (a folder the scenario owns, that+// exists): never above it.+function nearestExistingWithin(root, missing) {+ let current = path.resolve(missing);+ while (!fs.existsSync(current)) {+ if (path.resolve(root) === current) return null;+ current = path.dirname(current);+ }+ return current;+}++// `name/` for a folder and `name (N bytes)` for a file, paths relative to `root`, folders before their contents and+// siblings in name order. Bounded as the header says: `limit` entries listed, MAX_DIRECTORY_READS names read from a folder,+// MAX_DEPTH levels, no link followed (a link is listed as `name -> link`). `truncated` says that the walk stopped before it+// had seen everything; how much more there was is not counted, because counting it is the unbounded walk.+function listTree(root, limit = MAX_LISTING_ENTRIES) {+ const lines = [];+ let truncated = false;+ const add = (line) => {+ if (lines.length >= limit) { truncated = true; return false; }+ lines.push(line);+ return true;+ };+ const readNames = (dir) => {+ const opened = fs.opendirSync(dir);+ const entries = [];+ try {+ for (let entry = opened.readSync(); entry; entry = opened.readSync()) {+ if (entries.length >= MAX_DIRECTORY_READS) { truncated = true; break; }+ entries.push(entry);+ }+ } finally {+ opened.closeSync();+ }+ return entries.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));+ };+ const walk = (dir, depth) => {+ let entries;+ try {+ entries = readNames(dir);+ } catch (error) {+ add(`${path.relative(root, dir).split(path.sep).join('/') || '.'}/ <unreadable: ${error.code || error.message}>`);+ return;+ }+ for (const entry of entries) {+ if (lines.length >= limit) { truncated = true; return; }+ const full = path.join(dir, entry.name);+ const relative = path.relative(root, full).split(path.sep).join('/');+ // Node 20 on Windows reports a junction as a plain directory in a directory entry, so a folder is checked by lstat too+ // (lstat does not follow the link).+ let link = entry.isSymbolicLink();+ if (!link && entry.isDirectory()) {+ try { link = fs.lstatSync(full).isSymbolicLink(); } catch { link = false; }+ }+ if (link) {+ add(`${relative} -> link`);+ } else if (entry.isDirectory()) {+ add(`${relative}/`);+ if (depth + 1 >= MAX_DEPTH) truncated = true;+ else walk(full, depth + 1);+ } else {+ let size;+ try { size = String(fs.lstatSync(full).size); } catch (error) { size = `unreadable: ${error.code || error.message}`; }+ add(`${relative} (${size} bytes)`);+ }+ }+ };+ if (!fs.existsSync(root)) return { lines: [], truncated: false, exists: false };+ walk(root, 0);+ return { lines, truncated, exists: true };+}++function describeFolder({ label, dir }) {+ const tree = listTree(dir);+ if (!tree.exists) return [`${label}: ${dir} does not exist`];+ const header = `${label}: ${dir} (${tree.lines.length} entries listed${tree.truncated ? `; more exist, the listing stops at ${MAX_LISTING_ENTRIES} entries, ${MAX_DIRECTORY_READS} names a folder and ${MAX_DEPTH} levels` : ''})`;+ return [header, ...(tree.lines.length ? tree.lines.map((line) => ` ${line}`) : [' <empty>'])];+}++// A fake transport carries no real token, but a failure's cause can still quote a header; mask the credential forms a request+// carries before the text is kept, then let the plugin's own redaction take out every token this process obtained. Fail closed.+function redacted(text) {+ const masked = text.replace(/\b(Bearer|Basic)\s+[A-Za-z0-9._~+/=-]{8,}/gi, '$1 ****');+ try {+ return redactOutput(masked);+ } catch {+ return '--- build failure diagnostics withheld: the text could not be checked for an access token ---';+ }+}++// `folders` is `[{ label, dir }]`: the folders the scenario owns (workspace, app folder). Nothing else is listed.+function describeBuildFailure(error, folders) {+ const chain = causeChain(error);+ const lines = ['--- build failure diagnostics ---', 'error chain (outermost first):'];+ chain.forEach((link, position) => lines.push(...describeLink(link, position)));+ for (const missing of missingPaths(chain)) {+ const owner = folders.find(({ dir }) => isInside(dir, missing));+ if (!owner) {+ lines.push(`missing path: ${missing} (outside the folders listed below; not looked at)`);+ } else if (!fs.existsSync(owner.dir)) {+ lines.push(`missing path: ${missing} (its ${owner.label} no longer exists)`);+ } else {+ lines.push(`missing path: ${missing} (exists now: ${fs.existsSync(missing)}; nearest existing folder: ${nearestExistingWithin(owner.dir, missing)})`);+ }+ }+ for (const folder of folders) lines.push(...describeFolder(folder));+ lines.push('--- end of build failure diagnostics ---');+ return redacted(lines.join('\n'));+}++const pending = [];++// Keeps the diagnostics apart from `error` and returns `error` exactly as it was thrown. Anything that is not an Error is+// returned untouched.+function recordBuildFailure(error, folders) {+ if (!(error instanceof Error)) return error;+ let text;+ try {+ text = describeBuildFailure(error, folders);+ } catch (diagnosticError) {+ // The diagnostics must never hide the failure they describe.+ text = `--- build failure diagnostics unavailable: ${diagnosticError && diagnosticError.message} ---`;+ }+ pending.push(text);+ try { Object.defineProperty(error, 'buildFailureDiagnostics', { value: text, enumerable: false, configurable: true }); } catch { /* a frozen error cannot carry it; the pending list still has it */ }+ return error;+}++// Prints what was recorded during a test, only when that test failed (a build a test provokes and rejects on purpose passes and+// prints nothing), and forgets it either way. One diagnostic per line: the TAP reporter writes a newline inside one as a+// literal `\n`.+function flushBuildFailureDiagnostics(t) {+ const recorded = pending.splice(0);+ if (t.passed !== false) return;+ for (const text of recorded) for (const line of text.split('\n')) t.diagnostic(line);+}++// Call once at the top of a test file, so the hook covers every test in it.+function installBuildFailureDiagnostics(test) {+ test.afterEach((t) => flushBuildFailureDiagnostics(t));+}++module.exports = {+ recordBuildFailure,+ flushBuildFailureDiagnostics,+ installBuildFailureDiagnostics,+ describeBuildFailure,+ listTree,+ MAX_LISTING_ENTRIES,+ MAX_DIRECTORY_READS,+ MAX_DEPTH,+};diff --git a/plugins/model-apps/scripts/tests/helpers/fake-genpage-sdk.js b/plugins/model-apps/scripts/tests/helpers/fake-genpage-sdk.jsindex 3676ce07e..e601222dd 100644--- a/plugins/model-apps/scripts/tests/helpers/fake-genpage-sdk.js+++ b/plugins/model-apps/scripts/tests/helpers/fake-genpage-sdk.js@@ -209,7 +209,8 @@ class FakeSdk {async queryRecords(entity, options) {this.calls.push({ name: 'queryRecords', args: [entity, options] });const source = this.records[entity];- if (typeof source === 'function') return source(options);+ // A source is also handed the fake itself, for an answer that follows what was pushed (the components an app holds after its push).+ if (typeof source === 'function') return source(options, this);return source || [];}diff --git a/plugins/model-apps/scripts/tests/helpers/lifecycle-harness.js b/plugins/model-apps/scripts/tests/helpers/lifecycle-harness.jsindex 1df8ce5e7..a20366245 100644--- a/plugins/model-apps/scripts/tests/helpers/lifecycle-harness.js+++ b/plugins/model-apps/scripts/tests/helpers/lifecycle-harness.js@@ -8,7 +8,7 @@ const fs = require('node:fs');const path = require('node:path');const { performance } = require('node:perf_hooks');const { createAzHttpClient } = require('../../lib/sdk-http-client.js');-const { createMakerSdk, createNodeWorkspaceStorage } = require('../../lib/maker-sdk.js');+const { createMakerSdk: createVendoredMakerSdk, createNodeWorkspaceStorage } = require('../../lib/maker-sdk.js');const { buildModelApp } = require('../../build-model-app.js');const { verifySpec } = require('../../lib/verify-spec.js');const { readerFor } = require('../../verify-model-app.js');@@ -135,7 +135,9 @@ function kitchenSinkSpec() {// The commands of the lifecycle against one fake environment. `root` is a temporary folder the caller removes; the app folder in it// holds the page's source, and its `.maker-workspace` is the build's, as the CLI makes it next to app-spec.json.-function createLifecycleHarness(org, root) {+// `createMakerSdk` is the factory every command makes its SDK with: the vendored bundle's (lib/maker-sdk.js) unless a test hands in+// another — workspace-upgrade-real-bundle.test.js makes the workspace with the PREVIOUS release's bundle and reads it with this one.+function createLifecycleHarness(org, root, { createMakerSdk = createVendoredMakerSdk } = {}) {const appDir = path.join(root, 'app');const workspaceDir = path.join(appDir, '.maker-workspace');fs.mkdirSync(workspaceDir, { recursive: true });diff --git a/plugins/model-apps/scripts/tests/helpers/previous-bundle.js b/plugins/model-apps/scripts/tests/helpers/previous-bundle.jsnew file mode 100644index 000000000..c26797de7--- /dev/null+++ b/plugins/model-apps/scripts/tests/helpers/previous-bundle.js@@ -0,0 +1,63 @@+'use strict';+// The PREVIOUS release's vendored SDK bundle, for the tests that prove a workspace it wrote is read by this release's+// (workspace-upgrade-*-real-bundle.test.js, and the business-rule and flow upgrade cases).+//+// Where it comes from, in order: the file MODEL_APPS_PREVIOUS_BUNDLE names (CI fetches the release commit by hash and+// extracts the bundle there: .github/workflows/model-apps-script-tests.yml), else the release commit in this checkout's+// git history. Either way its SHA-256 must be the release's, so a wrong file or commit fails loudly instead of proving the+// upgrade from something else. Where neither is there, the tests skip — except in CI (GITHUB_ACTIONS), where a missing+// baseline is a failure: the proof must run there.+//+// On the next re-vendor, point PREVIOUS_RELEASE and PREVIOUS_BUNDLE_SHA256 at the release being replaced (and the workflow's+// fetch at the same commit: tests/run-tests.test.js holds them equal).+const fs = require('node:fs');+const path = require('node:path');+const crypto = require('node:crypto');+const { execFileSync } = require('node:child_process');+const { makeTempDir } = require('./temp-dirs.js');++const PREVIOUS_RELEASE = 'c159268b994b218729ff69ccdd74be3c83c56f86'; // model-apps 2.20.4 (2.20.5 ships the same bundle)+const PREVIOUS_BUNDLE_SHA256 = 'eebd70a2a7f6e12e45d18744640fd803479a738bc936b8e0dce1a9f97a0a4f8c';+const BUNDLE_PATH = 'plugins/model-apps/scripts/vendor/cds-maker-sdk.cjs';+const IN_CI = Boolean(process.env.GITHUB_ACTIONS);++function bytesOfPrevious() {+ const named = process.env.MODEL_APPS_PREVIOUS_BUNDLE;+ if (named) return { bytes: fs.readFileSync(named), from: named };+ try {+ // `cat-file blob` gives the committed bytes as they are: no checkout filter (line ends) is applied.+ const bytes = execFileSync('git', ['cat-file', 'blob', `${PREVIOUS_RELEASE}:${BUNDLE_PATH}`], { cwd: __dirname, maxBuffer: 64 * 1024 * 1024, stdio: ['ignore', 'pipe', 'ignore'] });+ return { bytes, from: `git ${PREVIOUS_RELEASE}` };+ } catch {+ return null;+ }+}++let loaded;+// The previous bundle as a module of its own, or null where it is not available.+function previousBundle() {+ if (loaded !== undefined) return loaded;+ const found = bytesOfPrevious();+ if (!found) return (loaded = null);+ const sha = crypto.createHash('sha256').update(found.bytes).digest('hex');+ if (sha !== PREVIOUS_BUNDLE_SHA256) throw new Error(`the previous release's SDK bundle from ${found.from} has SHA-256 ${sha}, not the release's ${PREVIOUS_BUNDLE_SHA256}`);+ const file = path.join(makeTempDir('previous-bundle-'), 'cds-maker-sdk.cjs');+ fs.writeFileSync(file, found.bytes);+ return (loaded = require(file));+}++// The `skip` option of a test that needs the previous bundle: false where it is available, and in CI (where its absence then+// fails the test, through requirePrevious); the reason elsewhere.+function skipWithoutPrevious() {+ if (previousBundle() || IN_CI) return false;+ return `the previous release's SDK bundle is not available (no git history for ${PREVIOUS_RELEASE}; set MODEL_APPS_PREVIOUS_BUNDLE)`;+}++// The previous bundle, or a failure that says what CI must provide.+function requirePrevious() {+ const bundle = previousBundle();+ if (!bundle) throw new Error(`the previous release's SDK bundle is required here: fetch ${PREVIOUS_RELEASE} and set MODEL_APPS_PREVIOUS_BUNDLE to its ${BUNDLE_PATH}`);+ return bundle;+}++module.exports = { PREVIOUS_RELEASE, PREVIOUS_BUNDLE_SHA256, BUNDLE_PATH, previousBundle, skipWithoutPrevious, requirePrevious };diff --git a/plugins/model-apps/scripts/tests/helpers/workspace-upgrade.js b/plugins/model-apps/scripts/tests/helpers/workspace-upgrade.jsnew file mode 100644index 000000000..a4d642a09--- /dev/null+++ b/plugins/model-apps/scripts/tests/helpers/workspace-upgrade.js@@ -0,0 +1,106 @@+'use strict';+// The upgrade paths of workspace-upgrade-real-bundle.test.js and workspace-upgrade-entry-real-bundle.test.js: an app built by the+// PREVIOUS release's SDK bundle (helpers/previous-bundle.js) into a workspace, and the first thing a maker then does with this+// release on that workspace — each path starting from the state the previous release left, never from one this release has+// already touched — compared with the same steps on a workspace this release's bundle wrote (the control).+const fs = require('node:fs');+const path = require('node:path');+const { makeTempDir } = require('./temp-dirs.js');+const { createLifecycleOrg } = require('./fake-lifecycle-org.js');+const { kitchenSinkSpec, createLifecycleHarness, seedForeignWork, appUniqueName } = require('./lifecycle-harness.js');+const { withVendoredCompiler, createMakerSdk } = require('../../lib/maker-sdk.js');+const { requirePrevious } = require('./previous-bundle.js');++// The projection version of every copy in a workspace, per artifact folder: { apps: [8], forms: [8, 8, 8, 8], ... }.+function projections(workspaceDir) {+ const root = path.join(workspaceDir, '.metadata');+ const out = {};+ if (!fs.existsSync(root)) return out;+ for (const kind of fs.readdirSync(root)) {+ const dir = path.join(root, kind);+ if (!fs.statSync(dir).isDirectory()) continue;+ for (const file of fs.readdirSync(dir).filter((f) => f.endsWith('.meta.json'))) {+ const meta = JSON.parse(fs.readFileSync(path.join(dir, file), 'utf8'));+ if (Number.isInteger(meta.projectionVersion)) (out[kind] = out[kind] || []).push(meta.projectionVersion);+ }+ }+ return out;+}+const versions = (byKind) => [...new Set(Object.values(byKind).flat())].sort((a, b) => a - b);++// A view filter a maker can save in the designer and the typed view model does not hold: a Quick Find marker on a filter BELOW the+// top level, and a multi-value condition (`<value>` children) inside it. The bundled SDK keeps such a filter verbatim (it used to be+// rebuilt from the typed filters by an edit, losing the marker and the values) — the change that raised the projection version.+const RESIDUAL_FILTER = '<filter type="or" isquickfindfields="1"><condition attribute="contoso_title" operator="like" value="{0}" />'+ + '<condition attribute="contoso_hours" operator="in"><value>1</value><value>2</value></condition></filter>';+const RESIDUAL_VIEW = 'My Open Tasks';++// A maker's edits, one to each kind of copy the build keeps and edits: the app header, a view (the one holding the residual+// filter), a form, a chart, the dashboard, the navigation — and a command bar on a table that had none (a build never edits an+// existing bar: recreate to change) and a table the app did not hold.+function editedSpec() {+ const spec = kitchenSinkSpec();+ spec.app.description = 'One app that uses every feature, edited.';+ spec.views.find((v) => v.name === RESIDUAL_VIEW).columns.push('contoso_done');+ spec.views.find((v) => v.name === 'Open Tasks').columns.push('contoso_done');+ spec.forms.find((f) => f.name === 'Task').description = 'The task record, edited.';+ spec.charts[0].description = 'Workload by priority, edited.';+ spec.dashboards[0].description = 'Project health, edited.';+ spec.appShell.areas[0].groups[0].subAreas.find((s) => s.title === 'Help').title = 'Help Center';+ spec.commands.push({ entity: 'contoso_task', label: 'Close Task', location: 'MainTab', library: 'contoso_project.js', function: 'Project.escalate' });+ spec.app.tables.push('account');+ return spec;+}++const residualView = (org) => {+ const rows = org.find('savedqueries', (v) => v.name === RESIDUAL_VIEW && v.returnedtypecode === 'contoso_task');+ if (rows.length !== 1) throw new Error(`one '${RESIDUAL_VIEW}' view, not ${rows.length}`);+ return rows[0];+};++// What a maker does in Maker: the residual filter added to the view, as the Web API call the designer makes.+async function makerAddsResidualFilter(org) {+ const view = residualView(org);+ const fetchxml = String(view.fetchxml).replace(/(<entity name="contoso_task">[\s\S]*?<filter type="and">)/, `$1${RESIDUAL_FILTER}`);+ if (fetchxml === view.fetchxml) throw new Error(`the '${RESIDUAL_VIEW}' view has no top-level filter to add to: ${view.fetchxml}`);+ const res = await org.request({ url: `${org.API}/savedqueries(${view.savedqueryid})`, method: 'PATCH', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ fetchxml }) });+ if (res.statusCode >= 300) throw new Error(`the maker's edit answered ${res.statusCode}: ${res.body}`);+}++const SDKS = {+ previous: () => withVendoredCompiler(requirePrevious().createMakerSdk),+ current: () => createMakerSdk,+};++// The state the first SDK leaves: the kitchen sink built by it (and, with `residualFilter`, the maker's residual filter added in+// Maker and the app rebuilt by the same SDK, so ITS copy of the view holds the filter). Then `next` — this release's harness on the+// same environment and app folder — is the first thing done with this release.+async function startFrom(which, { residualFilter = false } = {}) {+ const org = createLifecycleOrg();+ await seedForeignWork(org);+ const root = makeTempDir(`workspace-upgrade-${which}-`);+ const out = { org, root, seed: org.inventory(), seedContents: org.contents() };+ const first = createLifecycleHarness(org, root, { createMakerSdk: SDKS[which]() });+ out.build = await first.measure(() => first.build(kitchenSinkSpec()));+ if (residualFilter && !out.build.error) {+ await makerAddsResidualFilter(org);+ out.reread = await first.measure(() => first.build(kitchenSinkSpec()));+ }+ out.firstProjections = projections(first.workspaceDir);+ out.afterBuild = org.inventory();+ out.next = createLifecycleHarness(org, root);+ return out;+}++// A step's value, after checking that it threw nothing and sent nothing the fake does not model.+function stage(record, name) {+ if (!record) throw new Error(`the ${name} did not run`);+ if (record.error) throw record.error;+ if (record.unexpected.length) throw new Error(`the ${name} sent requests the fake does not model: ${record.unexpected.join('; ')}`);+ return record;+}++// A spec or a report as text, with every GUID (the fake mints them at random, so two environments never share one) made one placeholder.+const withoutIds = (value) => JSON.stringify(value).replace(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi, '<id>');++module.exports = { projections, versions, editedSpec, residualView, RESIDUAL_FILTER, RESIDUAL_VIEW, startFrom, stage, withoutIds, appUniqueName, kitchenSinkSpec };diff --git a/plugins/model-apps/scripts/tests/iteration-emit.test.js b/plugins/model-apps/scripts/tests/iteration-emit.test.jsindex 918079030..2d59d2be4 100644--- a/plugins/model-apps/scripts/tests/iteration-emit.test.js+++ b/plugins/model-apps/scripts/tests/iteration-emit.test.js@@ -1,20 +1,24 @@'use strict';// What the page compiler does with iteration, and the teaching that answers it (references/rules.md, Critical Rule 24 and-// Common Errors > 5. Iteration that compiles to nothing).+// Common Errors > 5. Iteration that another page compiler can lose).//-// The bundled SDK compiles a page with TypeScript's `transpileModule` and `{ target: ES5, module: ES2020, jsx: React }`-// (scripts/lib/typescript-compiler.js keeps the compiler the maker portal uses). Without `downlevelIteration`, ES5 emit-// reads an iterable by `length` and index: a spread becomes `__spreadArray([], value, true)`, a `for...of` becomes an-// indexed `for` loop, and an array destructure reads `value[0]` (and calls `value.slice` for a rest element). A Map, a Set,-// their iterators, a generator, a native `matchAll` result, URLSearchParams, FormData and Headers have no `length`, so the-// spread contributes nothing, the loop runs zero times, an element is undefined, a default replaces the real value and a-// rest element throws. `transpileModule` reports syntax only, so the TS2802 error a type check would give never appears.+// The bundled SDK compiles a page with TypeScript's `transpileModule` and `{ target: ES5, module: ES2020, jsx: React,+// downlevelIteration: true }` — its default iteration profile, 'iterator', which is what the maker portal's page compiler source+// sets too (scripts/lib/typescript-compiler.js keeps the compiler the portal uses). Under it the inlined helpers follow+// `Symbol.iterator`: a spread becomes `__spreadArray([], __read(value), false)`, a `for...of` loop walks `__values(value)`, and an+// array destructure reads `__read(value, n)`, so a Map, a Set, their iterators, a generator, a native `matchAll` result,+// URLSearchParams, FormData, Headers and a string iterate as modern JavaScript does.//-// Every case here is compiled by the vendored compiler with exactly those options and run in a fresh vm context; the-// expected values are what that emit does, never what modern JavaScript would do. The last test holds those options to what-// the real SDK bundle stores for a page, so an SDK that compiles pages another way fails here first. Results cross the context-// boundary as JSON (undefined and thrown errors are compared separately), so nothing depends on another realm's prototypes. The host's-// own URLSearchParams, FormData and Headers are handed in for their cases: nothing is fetched and no DOM is used.+// The bundles before model-apps 2.20.6 compiled WITHOUT `downlevelIteration` (the 'legacy' profile, which an older maker portal and+// `pac` still use): ES5 emit then reads an iterable by `length` and index, so the spread contributes nothing, the loop runs zero+// times, an element is undefined, a default replaces the real value and a rest element throws — with a clean compile, since+// `transpileModule` reports syntax only. A page compiled again by such a tool loses those values, which is why the teaching keeps+// `Array.from`: it is correct under both profiles. Every case here is compiled by the vendored compiler under the profile it names+// and run in a fresh vm context; the expected values are what that emit does. The last test holds the 'iterator' options to what+// the real SDK bundle stores for a page, so an SDK that compiles pages another way — the legacy emit included — fails there first.+// Results cross the context boundary as JSON (undefined and thrown errors are compared separately), so nothing depends on another+// realm's prototypes. The host's own URLSearchParams, FormData and Headers are handed in for their cases: nothing is fetched and no+// DOM is used.const { test } = require('node:test');const assert = require('node:assert/strict');const fs = require('node:fs');@@ -23,24 +27,26 @@ const vm = require('node:vm');const { loadVendoredTypeScript } = require('../lib/typescript-compiler.js');const RULES = fs.readFileSync(path.join(__dirname, '..', '..', 'references', 'rules.md'), 'utf8').replace(/\r\n?/g, '\n');-const HEADING = '### 5. Iteration that compiles to nothing';+const HEADING = '### 5. Iteration that another page compiler can lose';let typescript;const ts = () => (typescript ||= loadVendoredTypeScript());-// The SDK's options, exactly. A test here is never fixed by changing the target or adding downlevelIteration.-function compile(source) {- const { outputText, diagnostics } = ts().transpileModule(source, {- compilerOptions: { target: ts().ScriptTarget.ES5, module: ts().ModuleKind.ES2020, jsx: ts().JsxEmit.React },- reportDiagnostics: true,- });+// The two emit profiles, exactly: 'iterator' is what the bundled SDK stores (held to it by the last test), 'legacy' what a compiler+// without iterator support stores. 'legacy' OMITS the key, as such a compiler's options do.+const PROFILES = {+ iterator: () => ({ target: ts().ScriptTarget.ES5, module: ts().ModuleKind.ES2020, jsx: ts().JsxEmit.React, downlevelIteration: true }),+ legacy: () => ({ target: ts().ScriptTarget.ES5, module: ts().ModuleKind.ES2020, jsx: ts().JsxEmit.React }),+};+function compile(source, profile = 'iterator') {+ const { outputText, diagnostics } = ts().transpileModule(source, { compilerOptions: PROFILES[profile](), reportDiagnostics: true });return { outputText, codes: (diagnostics || []).map((d) => d.code) };}const HOST_GLOBALS = { URLSearchParams, FormData, Headers };-// Compiles `source`, runs it in a fresh context (plus `prelude`, plain JavaScript run first in the same context) and reads the-// named top-level values back. A value is JSON-normalized; `undefined` stays undefined; a throw is { threw: <error name> }.-function run(source, names, { prelude = '', after = '' } = {}) {- const { outputText, codes } = compile(source);+// Compiles `source` under `profile`, runs it in a fresh context (plus `prelude`, plain JavaScript run first in the same context) and+// reads the named top-level values back. A value is JSON-normalized; `undefined` stays undefined; a throw is { threw: <error name> }.+function run(source, names, { profile = 'iterator', prelude = '', after = '' } = {}) {+ const { outputText, codes } = compile(source, profile);assert.deepEqual(codes, [], 'the compile reports nothing — not even TS2802, which only a type check gives');const context = vm.createContext({ ...HOST_GLOBALS });try {@@ -75,74 +81,91 @@ const FAMILIES = [['Headers', 'return new Headers([["a", "1"]]);', [['a', '1']]],];-test('a spread of each native collection, iterator, generator and host iterable contributes no element; Array.from reads them all', () => {+test('a spread of each native collection, iterator, generator and host iterable reads every element under iterator support, none without it; Array.from reads them all under both', () => {for (const [label, body, values] of FAMILIES) {- const { values: got, outputText } = run(`function make(): any { ${body} }\nconst wrong = [0, ...make()];\nconst right = [0, ...Array.from(make())];\n`, ['wrong', 'right']);- assert.match(outputText, /__spreadArray\(\[0\], make\(\), true\)/, `${label}: ES5 emit copies it as an array-like`);- assert.deepEqual(got.wrong, [0], `${label}: the spread adds nothing, and the elements around it survive`);- assert.deepEqual(got.right, [0, ...values], `${label}: converted first, every value arrives in order`);+ const source = `function make(): any { ${body} }\nconst direct = [0, ...make()];\nconst converted = [0, ...Array.from(make())];\n`;+ const iterator = run(source, ['direct', 'converted']);+ assert.match(iterator.outputText, /__spreadArray\(\[0\], __read\(make\(\)\), false\)/, `${label}: the iterator emit reads it through Symbol.iterator`);+ assert.deepEqual(iterator.values, { direct: [0, ...values], converted: [0, ...values] }, `${label}: every value arrives in order`);+ const legacy = run(source, ['direct', 'converted'], { profile: 'legacy' });+ assert.match(legacy.outputText, /__spreadArray\(\[0\], make\(\), true\)/, `${label}: the legacy emit copies it as an array-like`);+ assert.deepEqual(legacy.values, { direct: [0], converted: [0, ...values] }, `${label}: without iterator support the spread adds nothing; converted first, it is whole`);}});-test('a call or constructor argument spread of an iterable passes no argument; spreading Array.from passes them all', () => {+test('a call or constructor argument spread of an iterable passes every argument under iterator support and none without it; spreading Array.from passes them all under both', () => {const source = `function make(): any { return new Set(["a", "b"]); }function collect(...items: string[]) { return items; }function Collect(this: any, ...items: string[]) { this.items = items; }-const wrongCall = collect("x", ...make());-const rightCall = collect("x", ...Array.from(make()));-const wrongNew = new (Collect as any)(...make()).items;-const rightNew = new (Collect as any)(...Array.from(make())).items;+const directCall = collect("x", ...make());+const convertedCall = collect("x", ...Array.from(make()));+const directNew = new (Collect as any)(...make()).items;+const convertedNew = new (Collect as any)(...Array.from(make())).items;`;- const { values } = run(source, ['wrongCall', 'rightCall', 'wrongNew', 'rightNew']);- assert.deepEqual(values, { wrongCall: ['x'], rightCall: ['x', 'a', 'b'], wrongNew: [], rightNew: ['a', 'b'] });+ const names = ['directCall', 'convertedCall', 'directNew', 'convertedNew'];+ assert.deepEqual(run(source, names).values, { directCall: ['x', 'a', 'b'], convertedCall: ['x', 'a', 'b'], directNew: ['a', 'b'], convertedNew: ['a', 'b'] });+ assert.deepEqual(run(source, names, { profile: 'legacy' }).values, { directCall: ['x'], convertedCall: ['x', 'a', 'b'], directNew: [], convertedNew: ['a', 'b'] });});-test('a for...of over a Map runs zero times, pair binding included; looping over Array.from keeps the loop and its pairs', () => {+test('a for...of over a Map walks its pairs under iterator support and closes the iterator on break; without it the loop runs zero times; looping over Array.from works under both', () => {const source = `const m = new Map([["a", 1], ["b", 2]]);-const wrong: Array<[string, number]> = [];-for (const [k, v] of m) wrong.push([k, v]);-const right: Array<[string, number]> = [];-for (const [k, v] of Array.from(m)) right.push([k, v]);+const direct: Array<[string, number]> = [];+for (const [k, v] of m) direct.push([k, v]);+const converted: Array<[string, number]> = [];+for (const [k, v] of Array.from(m)) converted.push([k, v]);let early = "";for (const [k] of Array.from(m)) { if (k === "b") { early = k; break; } }`;- const { values } = run(source, ['wrong', 'right', 'early']);- assert.deepEqual(values, { wrong: [], right: [['a', 1], ['b', 2]], early: 'b' });+ const iterator = run(source, ['direct', 'converted', 'early']);+ assert.match(iterator.outputText, /__values\(m\)/, 'the loop walks the iterator');+ assert.deepEqual(iterator.values, { direct: [['a', 1], ['b', 2]], converted: [['a', 1], ['b', 2]], early: 'b' });+ assert.deepEqual(run(source, ['direct', 'converted', 'early'], { profile: 'legacy' }).values, { direct: [], converted: [['a', 1], ['b', 2]], early: 'b' });+ const closing = `let closed = false;+const it: any = { [Symbol.iterator]() { let i = 0; return { next: () => ({ value: i++, done: i > 5 }), return: () => { closed = true; return { done: true }; } }; } };+for (const v of it) { if (v === 1) break; }+`;+ assert.equal(run(closing, ['closed']).values.closed, true, 'a break closes the iterator, as modern JavaScript does');});-test('array destructuring of a Set reads indices: an element is undefined, a default replaces the value, a rest element throws', () => {- const element = run('const [first] = new Set([1, 2]);\nconst [second] = Array.from(new Set([1, 2]));\n', ['first', 'second']);- assert.equal(element.values.first, undefined);- assert.equal(element.values.second, 1);- const fallback = run('const [first = "fallback"] = new Set(["actual"]);\nconst [second = "fallback"] = Array.from(new Set(["actual"]));\n', ['first', 'second']);- assert.deepEqual(fallback.values, { first: 'fallback', second: 'actual' });- // A hole moves the index the element is read from; it is still not the iterator's value.- const hole = run('const [, b] = new Set(["x", "y"]);\nconst [, c] = Array.from(new Set(["x", "y"]));\n', ['b', 'c']);- assert.deepEqual(hole.values, { b: undefined, c: 'y' });- const rest = run('const [...rest] = new Set([1, 2]);\n', ['rest']);- assert.equal(rest.threw, 'TypeError', 'the emitted rest element calls slice, which a Set does not have');- assert.match(rest.outputText, /\.slice\(0\)/);- assert.deepEqual(run('const [...rest] = Array.from(new Set([1, 2]));\n', ['rest']).values.rest, [1, 2]);- const assigned = run('let first: any = "before";\n([first] = new Set([1]) as any);\nlet second: any;\n([second] = Array.from(new Set([1])));\n', ['first', 'second']);- assert.deepEqual(assigned.values, { first: undefined, second: 1 });+test('array destructuring of a Set reads its elements under iterator support; without it an element is undefined, a default replaces the value and a rest element throws', () => {+ const cases = [+ ['const [first] = new Set([1, 2]);\n', 'first', 1, undefined],+ ['const [first = "fallback"] = new Set(["actual"]);\n', 'first', 'actual', 'fallback'],+ ['const [, second] = new Set(["x", "y"]);\n', 'second', 'y', undefined],+ ['let first: any = "before";\n([first] = new Set([1]) as any);\n', 'first', 1, undefined],+ ];+ for (const [source, name, withSupport, without] of cases) {+ assert.equal(run(source, [name]).values[name], withSupport, source);+ assert.equal(run(source, [name], { profile: 'legacy' }).values[name], without, source);+ assert.equal(run(source.replace(/= (new Set\([^)]*\))/, '= Array.from($1)'), [name], { profile: 'legacy' }).values[name], withSupport, `Array.from: ${source}`);+ }+ const rest = 'const [...rest] = new Set([1, 2]);\n';+ assert.match(run(rest, ['rest']).outputText, /__read\(new Set\(\[1, 2\]\)\)/);+ assert.deepEqual(run(rest, ['rest']).values.rest, [1, 2]);+ const legacy = run(rest, ['rest'], { profile: 'legacy' });+ assert.equal(legacy.threw, 'TypeError', 'without iterator support the emitted rest element calls slice, which a Set does not have');+ assert.match(legacy.outputText, /\.slice\(0\)/);+ assert.deepEqual(run('const [...rest] = Array.from(new Set([1, 2]));\n', ['rest'], { profile: 'legacy' }).values.rest, [1, 2]);});-test('the unique-value idiom and a Set-based selection append lose every value; Array.from and a native Set copy keep them', () => {- const unique = run('const xs = [1, 1, 2];\nconst wrong = [...new Set(xs)];\nconst right = Array.from(new Set(xs));\n', ['wrong', 'right']);- assert.deepEqual(unique.values, { wrong: [], right: [1, 2] });+test('the unique-value idiom and a Set-based selection append keep every value under iterator support and lose them without it; Array.from and a native Set copy keep them under both', () => {+ const unique = 'const xs = [1, 1, 2];\nconst direct = [...new Set(xs)];\nconst converted = Array.from(new Set(xs));\n';+ assert.deepEqual(run(unique, ['direct', 'converted']).values, { direct: [1, 2], converted: [1, 2] });+ assert.deepEqual(run(unique, ['direct', 'converted'], { profile: 'legacy' }).values, { direct: [], converted: [1, 2] });const source = `const prev = new Set(["a"]);const appended = new Set([...prev, "b"]);const copied = new Set(prev);copied.add("b");-const wrong = Array.from(appended);-const right = Array.from(copied);+const direct = Array.from(appended);+const native = Array.from(copied);`;- assert.deepEqual(run(source, ['wrong', 'right']).values, { wrong: ['b'], right: ['a', 'b'] }, 'the prior selection is lost, then kept');+ assert.deepEqual(run(source, ['direct', 'native']).values, { direct: ['a', 'b'], native: ['a', 'b'] });+ assert.deepEqual(run(source, ['direct', 'native'], { profile: 'legacy' }).values, { direct: ['b'], native: ['a', 'b'] }, 'without iterator support the prior selection is lost');});-// ── Neighbours: what keeps working, and the distinct string and array-like behaviours the teaching states ───────────────────────+// ── Neighbours: what keeps working, and the string, array-like and destructuring behaviours the teaching states ─────────────────-test('ordinary arrays, Object helpers, array-likes, arguments and native constructor copies are unaffected', () => {+test('ordinary arrays, Object helpers, array-likes, arguments and native constructor copies work alike under both profiles', () => {const source = `const rows = [1, 2];const spread = [...rows, 3];let looped = 0;@@ -159,27 +182,56 @@ const copiedSet = Array.from(new Set(new Set([1, 2])));const copiedMap = Array.from(new Map(new Map([["k", 1]])));const objectSpread = { ...{ a: 1 }, b: 2 };`;- const { values } = run(source, ['spread', 'looped', 'head', 'keys', 'entries', 'fromLike', 'fromArguments', 'copiedSet', 'copiedMap', 'objectSpread']);- assert.deepEqual(values, {+ const names = ['spread', 'looped', 'head', 'keys', 'entries', 'fromLike', 'fromArguments', 'copiedSet', 'copiedMap', 'objectSpread'];+ const expected = {spread: [1, 2, 3], looped: 3, head: 1, keys: ['a', 'b'], entries: [['a', 1]], fromLike: ['x', 'y'], fromArguments: [1, 2],copiedSet: [1, 2], copiedMap: [['k', 1]], objectSpread: { a: 1, b: 2 },- });+ };+ assert.deepEqual(run(source, names).values, expected);+ assert.deepEqual(run(source, names, { profile: 'legacy' }).values, expected);});-test('a string spread throws, an ES5 string loop visits UTF-16 code units, and Array.from reads code points', () => {- assert.equal(run('const name = "A😀";\nconst chars = [...name];\n', ['chars']).threw, 'TypeError');- const { values } = run('const name = "A😀";\nconst units: string[] = [];\nfor (const c of name) units.push(c);\nconst points = Array.from(name);\nconst [first] = name;\n', ['units', 'points', 'first']);- assert.equal(values.units.length, 3, 'the astral character is two units');- assert.deepEqual(values.points, ['A', '😀']);- assert.equal(values.first, 'A', 'a first-element binding reads the indexed UTF-16 element');+test('a string spreads, loops and destructures by code point under iterator support; without it a spread throws and a loop visits UTF-16 code units; Array.from reads code points under both', () => {+ const source = 'const name = "😀A";\nconst chars = [...name];\nconst units: string[] = [];\nfor (const c of name) units.push(c);\nconst points = Array.from(name);\nconst [first] = name;\n';+ assert.deepEqual(run(source, ['chars', 'units', 'points', 'first']).values, { chars: ['😀', 'A'], units: ['😀', 'A'], points: ['😀', 'A'], first: '😀' });+ assert.equal(run(source, ['chars'], { profile: 'legacy' }).threw, 'TypeError');+ const legacy = run(source.replace('const chars = [...name];\n', ''), ['units', 'points', 'first'], { profile: 'legacy' });+ assert.equal(legacy.values.units.length, 3, 'the astral character is two units');+ assert.deepEqual(legacy.values.points, ['😀', 'A']);+ assert.equal(legacy.values.first.length, 1, 'a first-element binding reads the indexed UTF-16 element');});-test('a rest destructure of an array-like without slice throws; a custom Symbol.matchAll that returns an array spreads fine', () => {- assert.equal(run('const like: any = { length: 1, 0: "x" };\nconst [...rest] = like;\n', ['rest']).threw, 'TypeError');- const source = `const matcher: any = { [Symbol.matchAll](text: string) { return [text.length]; } };+test('a rest destructure of an array-like without slice throws under both profiles; a custom Symbol.matchAll that returns an array spreads fine under both', () => {+ // `arguments` is an array-like that is ALSO iterable: with iterator support its rest destructure reads it through its iterator, as modern JavaScript does.+ const iterableLike = 'function f(..._: any[]) { const [...rest] = arguments as any; return rest; }\nconst rest = f(1, 2);\n';+ assert.deepEqual(run(iterableLike, ['rest']).values.rest, [1, 2]);+ assert.equal(run(iterableLike, ['rest'], { profile: 'legacy' }).threw, 'TypeError', 'without it the emitted slice is called, which arguments does not have');+ for (const profile of ['iterator', 'legacy']) {+ assert.equal(run('const like: any = { length: 1, 0: "x" };\nconst [...rest] = like;\n', ['rest'], { profile }).threw, 'TypeError', profile);+ const source = `const matcher: any = { [Symbol.matchAll](text: string) { return [text.length]; } };const hits = [..."abc".matchAll(matcher)];`;- assert.deepEqual(run(source, ['hits']).values.hits, [3], 'the string method delegates to the matcher, which may return an array');+ assert.deepEqual(run(source, ['hits'], { profile }).values.hits, [3], `${profile}: the string method delegates to the matcher, which may return an array`);+ }+});++test('the one disclosed difference of iterator support: a destructuring default that writes a later element of the same array is not seen by that element', () => {+ const source = 'const values: any[] = [undefined, 2];\nconst [a = (values[1] = 3), b] = values;\nconst pair = [a, b];\n';+ assert.deepEqual(run(source, ['pair']).values.pair, [3, 2], 'the elements were copied before the default ran');+ assert.deepEqual(run(source, ['pair'], { profile: 'legacy' }).values.pair, [3, 3], 'modern JavaScript and the legacy emit read the element after the default');+});++// skills/genpage/edit-flow.md: converting an existing form is not always neutral — `Array.from` reads the whole iterable, where a destructure or a loop that stops early reads a prefix.+test('under iterator support a destructure or a loop that stops early reads only a prefix of a generator, and Array.from reads all of it — converting such a form runs the rest of the generator', () => {+ const source = `let directReads = 0;+let convertedReads = 0;+let loopReads = 0;+function* values(counter: () => void) { counter(); yield 1; counter(); yield 2; counter(); yield 3; }+const [direct] = values(() => { directReads++; });+const [converted] = Array.from(values(() => { convertedReads++; }));+for (const v of values(() => { loopReads++; })) { if (v === 1) break; }+`;+ assert.deepEqual(run(source, ['direct', 'converted', 'directReads', 'convertedReads', 'loopReads']).values, { direct: 1, converted: 1, directReads: 1, convertedReads: 3, loopReads: 1 });});// ── The teaching: Critical Rule 24 and Common Errors §5 ───────────────────────────────────────────────────────────────────────@@ -204,59 +256,77 @@ function teaching() {return { section, examples };}-// What each pair is taught to do: the WRONG example's emitted result, then the CORRECT one's.+// What each pair is taught to do: the right result, which every CORRECT example gives under both profiles and every WRONG example+// gives under iterator support — and what the WRONG example gives without it.const TAUGHT = {- 'Map values': { name: 'choices', wrong: [], right: [1, 2] },- 'Unique values': { name: 'unique', wrong: [], right: [1, 2] },- 'Map pairs': { name: 'rows', wrong: [], right: [['a', 1], ['b', 2]] },- 'Native matchAll result': { name: 'hits', wrong: [], right: ['1', '2'] },- 'String spread — a separate throw, not an empty iterable result': { name: 'chars', wrong: 'throws', right: ['A', '😀'] },+ 'Map values': { name: 'choices', right: [1, 2], legacyWrong: [] },+ 'Unique values': { name: 'unique', right: [1, 2], legacyWrong: [] },+ 'Map pairs': { name: 'rows', right: [['a', 1], ['b', 2]], legacyWrong: [] },+ 'Native matchAll result': { name: 'hits', right: ['1', '2'], legacyWrong: [] },+ 'String spread — a separate throw, not an empty iterable result': { name: 'chars', right: ['A', '😀'], legacyWrong: 'throws' },};+const EDGE = 'A default that writes the array it destructures — the one difference from modern JavaScript under iterator support';-test('Common Errors §5 holds separate WRONG and CORRECT fences, and each compiles under the SDK options and does what it says', () => {+test('Common Errors §5 holds separate WRONG and CORRECT fences; each compiles under both profiles, the CORRECT one is right under both, the WRONG one only with iterator support', () => {const { examples } = teaching();- assert.ok(examples.length >= 16, 'the pairs are there');+ assert.ok(examples.length >= 18, 'the pairs are there');for (const example of examples) {assert.ok(example.role, `every fence in the section opens with // WRONG or // CORRECT (${example.label})`);assert.equal((example.code.match(/\/\/ (?:WRONG|CORRECT)\b/g) || []).length, 1, `one role per fence, never a WRONG and a CORRECT in one scope (${example.label})`);- assert.deepEqual(compile(example.code).codes, [], `${example.label} ${example.role} compiles`);+ for (const profile of ['iterator', 'legacy']) assert.deepEqual(compile(example.code, profile).codes, [], `${example.label} ${example.role} compiles (${profile})`);+ if (example.role === 'WRONG' && example.label !== EDGE) assert.match(example.code, /^\/\/ WRONG — without iterator support /, `${example.label}: the WRONG comment says when it fails`);}- for (const [label, { name, wrong, right }] of Object.entries(TAUGHT)) {+ for (const [label, { name, right, legacyWrong }] of Object.entries(TAUGHT)) {const pair = examples.filter((example) => example.label === label);assert.deepEqual(pair.map((example) => example.role), ['WRONG', 'CORRECT'], `${label}: one WRONG, then one CORRECT`);- const [bad, good] = pair.map((example) => run(example.code, [name]));- if (wrong === 'throws') assert.equal(bad.threw, 'TypeError', `${label}: the WRONG example throws`);- else assert.deepEqual(bad.values[name], wrong, `${label}: the WRONG example loses the values`);- assert.deepEqual(good.values[name], right, `${label}: the CORRECT example keeps them`);+ const [bad, good] = pair;+ assert.deepEqual(run(bad.code, [name]).values[name], right, `${label}: the WRONG example works in a page this plugin uploads`);+ const badLegacy = run(bad.code, [name], { profile: 'legacy' });+ if (legacyWrong === 'throws') assert.equal(badLegacy.threw, 'TypeError', `${label}: the WRONG example throws without iterator support`);+ else assert.deepEqual(badLegacy.values[name], legacyWrong, `${label}: the WRONG example loses the values without iterator support`);+ for (const profile of ['iterator', 'legacy']) assert.deepEqual(run(good.code, [name], { profile }).values[name], right, `${label}: the CORRECT example keeps them (${profile})`);}});-test('the destructuring pairs: an undefined element, a default that replaces the value, and a rest element that throws', () => {+test('the destructuring pairs: without iterator support an undefined element, a default that replaces the value and a rest element that throws; the CORRECT forms are right under both', () => {const pairs = teaching().examples.filter((example) => example.label === 'Destructuring');assert.deepEqual(pairs.map((example) => example.role), ['WRONG', 'CORRECT', 'WRONG', 'CORRECT', 'WRONG', 'CORRECT']);- const [elementBad, elementGood, defaultBad, defaultGood, restBad, restGood] = pairs.map((example) => run(example.code, /\.\.\.rest/.test(example.code) ? ['rest'] : ['first']));- assert.equal(elementBad.values.first, undefined);- assert.equal(elementGood.values.first, 1);- assert.equal(defaultBad.values.first, 'fallback');- assert.equal(defaultGood.values.first, 'actual');- assert.equal(restBad.threw, 'TypeError');- assert.deepEqual(restGood.values.rest, [1, 2]);+ const names = (example) => (/\.\.\.rest/.test(example.code) ? ['rest'] : ['first']);+ const legacy = pairs.map((example) => run(example.code, names(example), { profile: 'legacy' }));+ assert.equal(legacy[0].values.first, undefined);+ assert.equal(legacy[2].values.first, 'fallback');+ assert.equal(legacy[4].threw, 'TypeError');+ const right = [1, 1, 'actual', 'actual', [1, 2], [1, 2]];+ pairs.forEach((example, i) => {+ const key = names(example)[0];+ assert.deepEqual(run(example.code, [key]).values[key], right[i], `${example.role} ${i} under iterator support`);+ if (example.role === 'CORRECT') assert.deepEqual(legacy[i].values[key], right[i], `CORRECT ${i} without iterator support`);+ });});// The selection examples are component-body code: they run here under a controlled `React.useState` whose state already holds a// prior selection, and the handler is called as an event would call it — never a setter called unconditionally during render.-test('the selection-state pair: the WRONG updater loses the prior ids and its render read loses every value; the CORRECT one keeps them', () => {+test('the selection-state pair: without iterator support the WRONG updater loses the prior ids and its render read loses every value; the CORRECT one keeps them under both', () => {const pair = teaching().examples.filter((example) => /^Selection state/.test(example.label || ''));assert.deepEqual(pair.map((example) => example.role), ['WRONG', 'CORRECT']);const prelude = `var __state = new Set(["a"]);var React = { useState: function () { return [__state, function (next) { __state = typeof next === "function" ? next(__state) : next; }]; } };`;const after = 'addSelected("b"); var __after = Array.from(__state); var __render = chosen;';- const [bad, good] = pair.map((example) => {- assert.doesNotMatch(example.code, /^set[A-Z]\w*\(/m, 'no setter is called at the top level of the render');- return run(example.code, ['__after', '__render'], { prelude, after });- });- assert.deepEqual(bad.values, { __after: ['b'], __render: [] }, 'the updater keeps only the new id, and the render read is empty');- assert.deepEqual(good.values, { __after: ['a', 'b'], __render: ['a'] }, 'the native copy keeps the prior id, and Array.from reads the selection');+ for (const example of pair) assert.doesNotMatch(example.code, /^set[A-Z]\w*\(/m, 'no setter is called at the top level of the render');+ const kept = { __after: ['a', 'b'], __render: ['a'] };+ const [bad, good] = pair;+ assert.deepEqual(run(bad.code, ['__after', '__render'], { prelude, after, profile: 'legacy' }).values, { __after: ['b'], __render: [] }, 'the updater keeps only the new id, and the render read is empty');+ assert.deepEqual(run(bad.code, ['__after', '__render'], { prelude, after }).values, kept, 'with iterator support it keeps them');+ for (const profile of ['iterator', 'legacy']) assert.deepEqual(run(good.code, ['__after', '__render'], { prelude, after, profile }).values, kept, `the native copy keeps the prior id (${profile})`);+});++test('the default-that-writes-the-array pair: the WRONG one differs from modern JavaScript under iterator support; the CORRECT one gives the modern answer under both', () => {+ const pair = teaching().examples.filter((example) => example.label === EDGE);+ assert.deepEqual(pair.map((example) => example.role), ['WRONG', 'CORRECT']);+ const [bad, good] = pair;+ assert.deepEqual(run(bad.code, ['a', 'b']).values, { a: 3, b: 2 });+ assert.deepEqual(run(bad.code, ['a', 'b'], { profile: 'legacy' }).values, { a: 3, b: 3 });+ for (const profile of ['iterator', 'legacy']) assert.deepEqual(run(good.code, ['a', 'b'], { profile }).values, { a: 3, b: 3 }, profile);});test('Critical Rule 24 names the forms, the conversion and the section, after Rule 23 and before the separator', () => {@@ -268,19 +338,93 @@ test('Critical Rule 24 names the forms, the conversion and the section, after Rufor (const form of ['`[...new Set(xs)]`', '`[...m.values()]`', '`for (const [k, v] of m)`', '`new Set([...prev, id])`', '`[...selected]`', '`[...text.matchAll(re)]`', '`Array.from`']) {assert.ok(rule[1].includes(form), `Rule 24 names ${form}`);}- assert.match(rule[1], /See \*\*Common Errors > 5\. Iteration that compiles to nothing\*\*\.$/);+ assert.match(rule[1], /compile with iterator support/, 'it says what this plugin\'s pages compile with');+ assert.match(rule[1], /See \*\*Common Errors > 5\. Iteration that another page compiler can lose\*\*\.$/);assert.equal(RULES.split(`\n${HEADING}\n`).length, 2, 'one canonical section');+ assert.ok(!RULES.includes('Iteration that compiles to nothing'), 'the old heading is gone');+});++// ── The upgrade: pages an earlier release compiled without iterator support ─────────────────────────────────────────────────────++// A page uploaded by model-apps 2.20.5 or earlier holds the legacy emit: that bundle stored exactly what the legacy options emit for a+// page that reads no table (the sentinel this file held then). The SDK keeps a page's stored compiled output only when its source AND its data+// sources are unchanged and that output can be kept, so the first run of this release over such a page must neither rewrite nor republish it as+// "changed" for its new emit, nor report its published copy as different from the record a build kept of it: the page keeps the bytes it was+// published with until its source or its data sources change — and then it is compiled again, with iterator support.+test('a page stored with the legacy emit keeps it on an unchanged update, a rename and a published-copy check, and takes the iterator emit when its source changes', async () => {+ const { makeGenpageSdk } = require('../lib/genpage-sdk.js');+ const { sha256 } = require('../lib/hash.js');+ const { FakeGenPageServer, INSTANCE } = require('./helpers/fake-genpage-server.js');+ const source = "import * as React from 'react';\nconst m = new Map<string, number>([['a', 1]]);\nexport default function Page() { return <div>{[...m.keys()].length}</div>; }\n";+ const legacy = compile(source, 'legacy').outputText;+ const pageId = '5e1f0000-0000-4000-8000-000000000001';+ const server = new FakeGenPageServer();+ server.seedPage(pageId, { name: 'Upgraded', source, compiled: legacy });+ server.otherWorkspacePublishes(pageId);+ const genpage = makeGenpageSdk(INSTANCE, { httpClient: server.http() });+ const content = { source, name: 'Upgraded', dataSources: [] };+ const changes = (from) => server.writes().slice(from).filter((w) => !/PublishXml/.test(w));+ try {+ const recorded = sha256(legacy);+ const check = await genpage.publishedDiffers(pageId, content, { runtimeSha256: recorded });+ assert.deepEqual(check.differing, [], 'the published copy matches the record an earlier build kept, compiled output included');+ let from = server.writes().length;+ const kept = await genpage.update(pageId, { ...content, prompt: 'p', agentMessage: 'a', publishedFingerprint: check.fingerprint });+ assert.equal(kept.unchanged, true);+ assert.equal(kept.publish.kind, 'skipped', 'the record still holds: nothing is written or published again');+ assert.deepEqual(server.writes().slice(from), []);+ from = server.writes().length;+ const unrecorded = await genpage.update(pageId, { ...content, prompt: 'p', agentMessage: 'a', runtimeEvidence: true });+ assert.equal(unrecorded.unchanged, true, 'the source is unchanged, whatever this release would compile it to');+ assert.deepEqual(changes(from), [], 'nothing is written');+ assert.equal(unrecorded.runtimeSha256, recorded, 'the runtime it publishes is the one it held');+ from = server.writes().length;+ const renamed = await genpage.update(pageId, { ...content, name: 'Upgraded again', prompt: 'p', agentMessage: 'a', runtimeEvidence: true });+ assert.ok(!changes(from).some((w) => /filecontent/.test(w)), 'a rename writes no file content');+ assert.equal(renamed.runtimeSha256, recorded);+ assert.equal(server.rowText(pageId, 'src/pages/page.compiled'), legacy, 'the stored output is the legacy emit still');+ const changed = await genpage.update(pageId, { ...content, name: 'Upgraded again', source: source.replace('<div>', '<div title="t">'), prompt: 'p2', agentMessage: 'a2', runtimeEvidence: true });+ assert.equal(changed.publish.kind, 'verified');+ assert.match(server.rowText(pageId, 'src/pages/page.compiled'), /__spreadArray\(\[\], __read\(m\.keys\(\)\), false\)/, 'a changed source is compiled with iterator support');+ assert.notEqual(changed.runtimeSha256, recorded);+ } finally {+ await genpage.dispose();+ }+});++test('a page stored with the legacy emit is compiled again when only its data sources change — the same source then reads the values the legacy emit lost', async () => {+ const { makeGenpageSdk } = require('../lib/genpage-sdk.js');+ const { sha256 } = require('../lib/hash.js');+ const { FakeGenPageServer, INSTANCE, ACCOUNT_TABLE } = require('./helpers/fake-genpage-server.js');+ const source = "import * as React from 'react';\nconst m = new Map<string, number>([['a', 1]]);\nexport default function Page() { return <div>{[...m.keys()].length}</div>; }\n";+ const legacy = compile(source, 'legacy').outputText;+ const pageId = '5e1f0000-0000-4000-8000-000000000002';+ const server = new FakeGenPageServer();+ server.serveTable(ACCOUNT_TABLE);+ server.seedPage(pageId, { name: 'Upgraded', source, compiled: legacy });+ server.otherWorkspacePublishes(pageId);+ const genpage = makeGenpageSdk(INSTANCE, { httpClient: server.http() });+ try {+ const out = await genpage.update(pageId, { source, name: 'Upgraded', dataSources: ['account'], prompt: 'p', agentMessage: 'a', runtimeEvidence: true });+ assert.equal(out.unchanged, undefined, 'a data source was added: the page changed');+ assert.equal(out.publish.kind, 'verified');+ assert.equal(server.rowText(pageId, 'src/pages/page.tsx'), source, 'the source is the same bytes');+ const compiled = server.rowText(pageId, 'src/pages/page.compiled');+ assert.match(compiled, /__spreadArray\(\[\], __read\(m\.keys\(\)\), false\)/, 'compiled again, with iterator support');+ assert.notEqual(out.runtimeSha256, sha256(legacy));+ } finally {+ await genpage.dispose();+ }});// ── The contract these proofs assume, read from the real SDK ──────────────────────────────────────────────────────────────────────-// Everything above compiles with the options the SDK compiled pages with when it was written. This pushes a page through the REAL-// vendored SDK bundle (over the stateful fake of the page tables, helpers/fake-genpage-server.js) and holds the compiled output it stores-// to exactly what those options emit. When an SDK uptake compiles pages another way — with `downlevelIteration` (a spread then reads-// `__read(…)`, a loop `__values(…)`) or an ES2015+ target (spreads and loops kept as written) — this fails first: then Critical Rule 24-// and Common Errors §5 in references/rules.md, the skills that repeat the rule, and the expectations in this file are revised together,-// once the maker portal is shown to compile pages the same way (the plugin keeps parity with it: lib/typescript-compiler.js).-test('the real SDK stores a page compiled exactly as these proofs compile it: ES5, without iterator downleveling', async () => {+// This pushes a page through the REAL vendored SDK bundle (over the stateful fake of the page tables, helpers/fake-genpage-server.js)+// and holds the compiled output it stores to exactly what the 'iterator' options emit. When an SDK uptake compiles pages another way —+// back to the legacy emit (a spread then reads `__spreadArray([], value, true)`, a loop indexes `length`), or an ES2015+ target+// (spreads and loops kept as written) — this fails first: then Critical Rule 24 and Common Errors §5 in references/rules.md, the+// skills that repeat the rule, and the expectations in this file are revised together.+test('the real SDK stores a page compiled exactly as these proofs compile it under iterator support: ES5 with downlevelIteration, never the legacy emit', async () => {const { makeGenpageSdk } = require('../lib/genpage-sdk.js');const { FakeGenPageServer, INSTANCE } = require('./helpers/fake-genpage-server.js');const source = [@@ -303,9 +447,11 @@ test('the real SDK stores a page compiled exactly as these proofs compile it: ESawait genpage.dispose();}const changed = 'the vendored SDK no longer compiles pages as these proofs assume: revise Critical Rule 24, Common Errors §5 and this file';- assert.equal(stored, compile(source).outputText, `what the SDK stores is what the options these proofs use emit — ${changed}`);- assert.match(stored, /__spreadArray\(\[\], seen\.values\(\), true\)/, 'a spread reads the iterator by length and index');- assert.match(stored, /for \(var _i = 0, seen_1 = seen; _i < seen_1\.length; _i\+\+\)/, 'a loop walks it by index');- assert.match(stored, /var first = new Set\(\["x"\]\)\[0\];/, 'a destructure reads an index');- assert.doesNotMatch(stored, /__read|__values|\[\.\.\.seen|for \(const/, `no iterator downleveling, and no ES2015 form left as written — ${changed}`);+ assert.equal(stored, compile(source, 'iterator').outputText, `what the SDK stores is what the iterator options emit — ${changed}`);+ assert.notEqual(stored, compile(source, 'legacy').outputText, `not the legacy emit — ${changed}`);+ assert.match(stored, /__spreadArray\(\[\], __read\(seen\.values\(\)\), false\)/, 'a spread reads the iterator through Symbol.iterator');+ assert.match(stored, /__values\(seen\)/, 'a loop walks the iterator');+ assert.match(stored, /__read\(new Set\(\["x"\]\), 1\)/, 'a destructure reads the iterator');+ assert.doesNotMatch(stored, /__spreadArray\(\[\], seen\.values\(\), true\)|_i < seen_1\.length|new Set\(\["x"\]\)\[0\]/, `no legacy index emit — ${changed}`);+ assert.doesNotMatch(stored, /\[\.\.\.seen|for \(const/, `no ES2015 form left as written — ${changed}`);});diff --git a/plugins/model-apps/scripts/tests/lifecycle-trail-golden-real-bundle.test.js b/plugins/model-apps/scripts/tests/lifecycle-trail-golden-real-bundle.test.jsnew file mode 100644index 000000000..64eb7d363--- /dev/null+++ b/plugins/model-apps/scripts/tests/lifecycle-trail-golden-real-bundle.test.js@@ -0,0 +1,371 @@+'use strict';+// THE REQUEST TRAIL OF THE WHOLE LIFECYCLE, pinned request by request, over the REAL vendored SDK.+//+// lifecycle-matrix-real-bundle.test.js pins what each phase WRITES (a count per `METHOD resource`) and what it PUBLISHES, and holds its+// reads under a ceiling. That leaves three kinds of change invisible: a read added or removed under the ceiling (a new SDK that reads an+// app's token once more after each update), a body that gains or loses a member (a view update that now sends `returnedtypecode`, a date+// column that now states its behaviour), and requests that reorder. Each is a change a maker can observe — in the requests the+// environment sees, its audit and its throttling budget — and at an SDK uptake each must be explained by a release-note line. This file+// makes every such change fail a named test with a precise diff instead of being found by luck or on a live environment.+//+// The lifecycle is the kitchen-sink App Spec (helpers/lifecycle-harness.js) over the stateful fake Dataverse+// (helpers/fake-lifecycle-org.js), with another maker's work in the environment first, run as a maker runs it:+// build first build (--apply --publish --sample-data --verify)+// rebuild the same spec, unchanged+// edit a rebuild of an EDITED spec: a column added to two tables (one a Date and Time column), a view's columns and another+// view's description changed, the app's description changed and the page's source changed+// download the app downloaded to a spec+// verify the edited spec verified+// teardown the edited spec torn down+//+// Each phase's golden (scripts/tests/golden/lifecycle-trail.<phase>.txt) lists every HTTP request: method, path with query (GUIDs and+// timestamps masked), the SHAPE of its body — member names, value types and how many elements of each shape a list holds, never values: `{name:string,type:number}` — by a short hash+// into the legend at the end, and the status the fake answered; a `$batch` lists its operations, in their order, below it. The requests+// are cut into SEGMENTS by the phase's publishes (each PublishXml, with EVERYTHING its ParameterXml names, is a segment's last line), and the segments are+// in order: a write that moves to the other side of a publish — so that the publish no longer makes it live, or makes it live early —+// is a difference. WITHIN a segment the requests are listed sorted and counted (`3x GET …`), not in the order they were sent: the build+// creates and enriches the views of different tables concurrently, and measured over eight runs under load the interleaving of those+// requests varied (one run in two) while the multiset of every segment never did. So what is pinned is: the exact multiset of requests+// (with query, body shape and status), the order and content of the publishes, and which publish each request precedes. What is NOT+// pinned is the order of two requests between the same two publishes — the fake refuses a request out of dependency order (a column of+// a table not yet created), and the lifecycle tests prove what each phase leaves behind.+//+// WHEN THIS FAILS: the message prints, per phase, the requests added and removed (counted by `METHOD resource`) and the first lines where+// the golden differs. Every difference must be explained — at an SDK uptake, by a release-note line (`Changed` for a behaviour, `Fixed`+// for a bug the new SDK fixes); in a skill change, by the change. Then regenerate the goldens ON A DEVELOPER MACHINE and review their diff:+// UPDATE_GOLDENS=1 node --test scripts/tests/lifecycle-trail-golden-real-bundle.test.js+// (PowerShell: `$env:UPDATE_GOLDENS='1'; node --test …; Remove-Item Env:UPDATE_GOLDENS`.) A run that rewrites a golden FAILS, so it is+// never what turns a run green: run again without UPDATE_GOLDENS. Under CI (CI, GITHUB_ACTIONS or TF_BUILD set) UPDATE_GOLDENS=1 is+// refused before anything runs or is written.+const test = require('node:test');+const assert = require('node:assert/strict');+const crypto = require('node:crypto');+const { spawnSync } = require('node:child_process');+const fs = require('node:fs');+const path = require('node:path');+const { makeTempDir } = require('./helpers/temp-dirs.js');+const { createLifecycleOrg } = require('./helpers/fake-lifecycle-org.js');+const { kitchenSinkSpec, createLifecycleHarness, seedForeignWork, appUniqueName } = require('./helpers/lifecycle-harness.js');+const { GOLDEN_DIR } = require('./helpers/golden.js');++const PHASES = ['build', 'rebuild', 'edit', 'download', 'verify', 'teardown'];+const goldenFile = (phase) => path.join(GOLDEN_DIR, `lifecycle-trail.${phase}.txt`);++// The fake mints GUIDs for every row it creates, and the SDK mints some of its own (a page's conversation messages): masked, so the+// golden pins what is asked for and not which id it was given. A timestamp in a query (a modifiedon filter) likewise.+const GUID = /[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}/g;+const TIMESTAMP = /\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d+)?Z?/g;+const mask = (text) => String(text).replace(GUID, '<id>').replace(TIMESTAMP, '<time>');++// A body's shape: member names and value types, recursively — `{AttributeType:string,MaxLength:number,DateTimeBehavior:{Value:string}}`.+// An array is its elements' shapes COUNTED, in sorted order — `Attributes:[1x{…DateTimeBehavior…}|11x{…}]` — so one element more of the+// same shape (a column more in one table create) changes it, while the order the elements were listed in does not. A raw body (a page+// file's content) is `string`/`bytes`.+function shape(value) {+ if (value === null) return 'null';+ if (Buffer.isBuffer(value)) return 'bytes';+ if (Array.isArray(value)) {+ const counts = new Map();+ for (const element of value.map(shape)) counts.set(element, (counts.get(element) || 0) + 1);+ return `[${[...counts.keys()].sort().map((element) => `${counts.get(element)}x${element}`).join('|')}]`;+ }+ if (typeof value === 'object') return `{${Object.keys(value).sort().map((key) => `${mask(key)}:${shape(value[key])}`).join(',')}}`;+ return typeof value;+}++// What a publish names, WHOLE: the PublishXml's ParameterXml as a tree, every element kept, children in sorted order (the order a build+// lists tables in is not what it publishes), GUIDs masked —+// <importexportxml><entities><entity>contoso_task</entity><entity>contoso_project</entity></entities><appmodules><appmodule>{id}</appmodule></appmodules></importexportxml>+// -> importexportxml(appmodules(appmodule=#id) entities(entity=contoso_project entity=contoso_task))+// so a publish that names one more table, one more kind of component (an option set, a site map) or one fewer is a difference. A+// ParameterXml this reader cannot take apart (an attribute, a self-closing element, text outside the one document element or beside child+// elements, a second root) is kept as it was sent, masked: never dropped, never mistaken for a valid envelope.+// See https://learn.microsoft.com/power-apps/developer/data-platform/webapi/reference/publishxml+function publishTargetsOf(parameterXml) {+ // A GUID (braced or not) is written #id here, not <id>, which would read as an element.+ const xml = String(parameterXml).replace(/\{?[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}\}?/g, '#id').replace(TIMESTAMP, '#time');+ const token = /<(\/?)([A-Za-z_][\w.-]*)>|([^<]+)/g;+ const root = { children: [] };+ const stack = [root];+ for (const m of xml.matchAll(token)) {+ const top = stack[stack.length - 1];+ if (m[3] !== undefined) { if (m[3].trim()) top.text = (top.text || '') + m[3].trim(); continue; }+ if (m[1]) {+ if (stack.length < 2 || top.tag !== m[2]) return `raw:${xml}`;+ stack.pop();+ } else {+ const node = { tag: m[2], children: [] };+ top.children.push(node);+ stack.push(node);+ }+ }+ if (stack.length !== 1 || xml.replace(token, '') !== '') return `raw:${xml}`;+ // Only ONE element-only document is taken apart: exactly one root, no text outside it, and no element that holds both text and+ // elements. Anything else — `undefined<importexportxml>…`, a trailing word, `<appmodules>unexpected<appmodule>…`, two roots — is+ // kept raw, so it can never read as the valid envelope it resembles.+ const mixed = (node) => (node.children.length > 0 && node.text !== undefined) || node.children.some(mixed);+ if (root.text !== undefined || root.children.length !== 1 || mixed(root.children[0])) return `raw:${xml}`;+ const render = (node) => (node.children.length ? `${node.tag}(${node.children.map(render).sort().join(' ')})` : `${node.tag}=${node.text || ''}`);+ return render(root.children[0]);+}+// One phase's golden text, and the shapes its lines refer to by hash (a hash, not a running number, so one new shape does not renumber+// every later line of the diff).+function trailOf(org, step) {+ const legend = new Map();+ const ref = (body) => {+ if (body === undefined) return '';+ const s = shape(body);+ const hash = crypto.createHash('sha256').update(s).digest('hex').slice(0, 8);+ legend.set(hash, s);+ return ` #${hash}`;+ };+ const publishes = org.requests.slice(step.mark, step.end).filter((r) => r.path === '/PublishXml').map((r) => publishTargetsOf(r.body && r.body.ParameterXml));+ const segments = [[]];+ for (const r of org.requests.slice(step.mark, step.end)) {+ const unit = [`${r.method} ${mask(r.path)}${r.operations ? '' : ref(r.body)} -> ${r.status}`];+ for (const op of r.operations || []) unit.push(` > ${op.method} ${mask(op.path)}${ref(op.body)}`);+ segments[segments.length - 1].push(unit.join('\n'));+ if (r.path === '/PublishXml') segments.push([]);+ }+ const lines = [`# ${step.end - step.mark} requests, ${publishes.length} publishes`];+ segments.forEach((units, i) => {+ if (i === segments.length - 1 && !units.length) return;+ lines.push(i < publishes.length ? `## up to publish ${i + 1}: ${publishes[i]}` : '## after the last publish');+ const counts = new Map();+ for (const unit of units) counts.set(unit, (counts.get(unit) || 0) + 1);+ for (const unit of [...counts.keys()].sort()) lines.push(`${String(counts.get(unit)).padStart(3)}x ${unit}`);+ });+ const legendLines = [...legend].sort(([a], [b]) => a.localeCompare(b)).map(([hash, s]) => `#${hash} ${s}`);+ return [...lines, '# shapes', ...legendLines].join('\n') + '\n';+}++// The edits of the `edit` phase: one of each kind a maker makes most, each an existing artifact the build changes in place.+function editedSpec() {+ const spec = kitchenSinkSpec();+ spec.app.description = 'One app that uses every feature, edited.';+ spec.entities.find((e) => e.schemaName === 'contoso_tag').columns.push({ schemaName: 'contoso_color', displayName: 'Color', type: 'Text', maxLength: 50 });+ spec.entities.find((e) => e.schemaName === 'contoso_task').columns.push({ schemaName: 'contoso_start', displayName: 'Start', type: 'DateTime' });+ spec.views.find((v) => v.name === 'Open Tasks').columns.push('contoso_done');+ spec.views.find((v) => v.name === 'Open Projects').description = 'Projects still running, edited.';+ return spec;+}+const EDITED_PAGE_SOURCE = "import * as React from 'react';\nexport default function KitchenPage() { return <div>Kitchen, edited</div>; }\n";++let lifecycleP;+const lifecycle = () => lifecycleP || (lifecycleP = runLifecycle());+async function runLifecycle() {+ const org = createLifecycleOrg();+ const harness = createLifecycleHarness(org, makeTempDir('lifecycle-trail-'));+ await seedForeignWork(org);+ const spec = kitchenSinkSpec();+ const edited = editedSpec();+ const out = { org, steps: {} };+ const stage = async (phase, fn) => { out.steps[phase] = await harness.measure(fn); };+ await stage('build', () => harness.build(spec));+ await stage('rebuild', () => harness.build(spec));+ fs.writeFileSync(path.join(harness.appDir, 'KitchenPage.tsx'), EDITED_PAGE_SOURCE);+ await stage('edit', () => harness.build(edited));+ await stage('download', () => harness.download(appUniqueName(edited), path.join(harness.appDir, '..', 'download')));+ await stage('verify', () => harness.verify(edited));+ await stage('teardown', () => harness.teardown(edited));+ return out;+}++// `METHOD resource` counts of a golden's requests (a `$batch`'s operations counted too, marked), for the summary of a difference: the+// resource as lifecycle-matrix-real-bundle.test.js names it, keys and query left out ("GET appmodules", "PATCH savedqueries").+// " 17x POST /AddSolutionComponent #3c0a1b2d -> 200" a request, sent 17 times in its segment+// " > PATCH /uxagentprojectfiles(<id>)/filecontent #…" an operation of the `$batch` above it, once per time that batch was sent+function countsOf(text) {+ const counts = new Map();+ let times = 0;+ const add = (key, n) => counts.set(key, (counts.get(key) || 0) + n);+ const resourceOf = (where) => where.replace(/\?.*$/, '').replace(/^\//, '').replace(/\((?:[^()']|'[^']*')*\)/g, '');+ for (const line of text.split('\n')) {+ const request = /^\s*(\d+)x (GET|POST|PATCH|PUT|DELETE) (\S+)/.exec(line);+ if (request) { times = Number(request[1]); add(`${request[2]} ${resourceOf(request[3])}`, times); continue; }+ const operation = /^\s+> (GET|POST|PATCH|PUT|DELETE) (\S+)/.exec(line);+ if (operation) add(`(in a $batch) ${operation[1]} ${resourceOf(operation[2])}`, times);+ }+ return counts;+}++// A golden's requests as `segment heading -> request (its body shapes written out, its batch operations under it) -> count`, and its+// publishes, so two goldens can be compared request by request whatever the hashes and line numbers.+function unitsOf(text) {+ const lines = text.split('\n');+ const legend = new Map(lines.filter((l) => /^#[0-9a-f]{8} /.test(l)).map((l) => [l.slice(0, 9), l.slice(10)]));+ const spell = (line) => line.replace(/#[0-9a-f]{8}\b/g, (hash) => legend.get(hash) || hash);+ const units = new Map();+ const publishes = [];+ let heading = '';+ let current = null;+ for (const line of lines) {+ if (line === '# shapes') break;+ if (line.startsWith('## ')) { heading = line.slice(3); const m = /^up to publish \d+: (.*)$/.exec(heading); if (m) publishes.push(m[1]); continue; }+ const request = /^\s*(\d+)x (.*)$/.exec(line);+ if (request) { current = { key: `${heading}\n ${spell(request[2])}`, count: Number(request[1]) }; units.set(current.key, (units.get(current.key) || 0) + current.count); continue; }+ if (current && /^\s+> /.test(line)) {+ // An operation belongs to the batch above it: re-key that unit with the operation appended.+ const count = units.get(current.key) - current.count;+ if (count) units.set(current.key, count); else units.delete(current.key);+ current.key = `${current.key}\n ${spell(line.trim())}`;+ units.set(current.key, (units.get(current.key) || 0) + current.count);+ }+ }+ return { units, publishes };+}++// What a reader needs to explain a difference: the requests added and removed by `METHOD resource`, the publishes if they changed, and+// each request that is in one golden and not (as often) in the other, in its segment, with its body shapes written out.+function describeDifference(phase, expected, actual) {+ const before = countsOf(expected);+ const after = countsOf(actual);+ const moved = [...new Set([...before.keys(), ...after.keys()])].sort()+ .map((key) => [key, (after.get(key) || 0) - (before.get(key) || 0)]).filter(([, delta]) => delta !== 0)+ .map(([key, delta]) => ` ${delta > 0 ? '+' : ''}${delta} ${key}`);+ const was = unitsOf(expected);+ const now = unitsOf(actual);+ const clip = (text) => text.split('\n').map((l) => (l.length > 400 ? `${l.slice(0, 400)}…` : l)).join('\n');+ const changed = [...new Set([...was.units.keys(), ...now.units.keys()])].sort()+ .filter((key) => (was.units.get(key) || 0) !== (now.units.get(key) || 0))+ .map((key) => ` [${was.units.get(key) || 0}x before, ${now.units.get(key) || 0}x now] in "${clip(key)}`.replace('\n', '":\n'));+ const LIMIT = 30;+ return [+ `The ${phase} phase's request trail differs from scripts/tests/golden/lifecycle-trail.${phase}.txt.`,+ moved.length ? ` Requests added (+) and removed (-), by METHOD resource:\n${moved.join('\n')}` : ' The same requests by METHOD resource: a query, a body shape, a status, or the publish a request precedes differs.',+ JSON.stringify(was.publishes) === JSON.stringify(now.publishes) ? '' : ` The publishes were:\n ${was.publishes.join('\n ')}\n and are now:\n ${now.publishes.join('\n ')}`,+ ` Each request that differs (${changed.length}${changed.length > LIMIT ? `, the first ${LIMIT}` : ''}):`,+ ...changed.slice(0, LIMIT),+ ' Explain EVERY difference — at an SDK uptake by a release-note line (Changed / Fixed), otherwise by the change that made it —',+ ' then regenerate with UPDATE_GOLDENS=1 and review the golden\'s diff.',+ ].filter(Boolean).join('\n');+}+// The CI systems this repository's checks run on say so in the environment: GitHub Actions sets CI and GITHUB_ACTIONS, Azure Pipelines+// TF_BUILD. See https://docs.github.com/actions/learn-github-actions/variables#default-environment-variables+const inCi = (env) => ['CI', 'GITHUB_ACTIONS', 'TF_BUILD'].some((name) => env[name] && !/^(?:false|0)$/i.test(env[name]));+function regenerationRefusal(env) {+ if (env.UPDATE_GOLDENS !== '1' || !inCi(env)) return null;+ return 'UPDATE_GOLDENS=1 is refused under CI: a CI run compares the request trail with the committed goldens and never rewrites them. Regenerate on a developer machine, review the diff, and commit it.';+}++// Compare a phase's trail with its golden. With UPDATE_GOLDENS=1 (never under CI) a golden that differs is rewritten AND the run fails,+// so a regenerated golden is never what turns a run green: review `git diff`, then run again without it. A golden that already holds the+// trail is left alone and passes.+function settleGolden(phase, file, actual, env = process.env) {+ const refused = regenerationRefusal(env);+ if (refused) assert.fail(refused);+ // A Windows checkout may turn the committed LF into CRLF (helpers/golden.js): compare content, not line endings.+ const expected = fs.existsSync(file) ? fs.readFileSync(file, 'utf8').replace(/\r\n/g, '\n') : null;+ if (actual === expected) return;+ if (env.UPDATE_GOLDENS === '1') {+ fs.mkdirSync(path.dirname(file), { recursive: true });+ fs.writeFileSync(file, actual);+ assert.fail(`regenerated ${path.basename(file)}: review its diff and explain every change, then run again without UPDATE_GOLDENS (a run that regenerates never passes).`);+ }+ assert.fail(expected === null ? `${path.basename(file)} is missing: regenerate it with UPDATE_GOLDENS=1 on a developer machine.` : describeDifference(phase, expected, actual));+}++for (const phase of PHASES) {+ test(`lifecycle trail: the ${phase} phase sends exactly the requests, bodies and publishes it sent before`, async (t) => {+ // Refused before the lifecycle runs: a CI run that asks to regenerate does no work and fails.+ const refused = regenerationRefusal(process.env);+ if (refused) assert.fail(refused);+ const run = await lifecycle();+ const step = run.steps[phase];+ if (step.error) throw step.error;+ // A phase that failed would pin a failure's trail: the lifecycle tests prove each phase succeeds; here it is a precondition.+ const value = step.value || {};+ if (value.result && value.result.ok === false) assert.fail(`the ${phase} phase failed: ${JSON.stringify(value.result.errors || value.result.error)}`);+ if (phase === 'verify') assert.deepEqual({ ok: value.ok, missing: value.missing, unverified: value.unverified || [] }, { ok: true, missing: [], unverified: [] }, 'verify passes');+ if (phase === 'download') assert.equal(value.emitted && value.emitted.ok, true, `the download succeeds: ${value.stderr}`);+ assert.deepEqual(step.unexpected, [], `every request the ${phase} phase sent is one the fake models`);+ t.diagnostic(`${phase}: ${step.end - step.mark} requests in ${step.ms} ms`);+ settleGolden(phase, goldenFile(phase), trailOf(run.org, step));+ });+}++// The wire regression a normalizer could hide, on this run's own recorded build: every publish's ParameterXml with text before its+// envelope (`undefined<importexportxml>…`, what a string concatenated onto an unset value sends). The fake accepts such a body, so only the+// trail can notice it: the build's trail must then differ from the golden, and the difference must name the publishes.+test('lifecycle trail: a build whose publishes carry text outside their envelope does not match the golden', async () => {+ const run = await lifecycle();+ const step = run.steps.build;+ if (step.error) throw step.error;+ const prefixed = run.org.requests.map((r) => (r.path === '/PublishXml' ? { ...r, body: { ...r.body, ParameterXml: `undefined${r.body.ParameterXml}` } } : r));+ const expected = fs.readFileSync(goldenFile('build'), 'utf8').replace(/\r\n/g, '\n');+ assert.equal(trailOf(run.org, step), expected, 'the recorded build matches its golden');+ const seen = trailOf({ requests: prefixed }, step);+ assert.notEqual(seen, expected, 'publishes with text outside their envelope change the trail');+ assert.match(describeDifference('build', expected, seen), /The publishes were:[\s\S]*and are now:[\s\S]*raw:undefined<importexportxml>/);+});+// The guard of the guard, over the real trail builder: one more read, one more member in one body, and a write moved to the other side+// of a publish each change the golden and are named in the description — and the one thing that is tolerated, two requests of one+// segment sent in the other order, does not — so the golden can never rot into a check that passes whatever is sent.+test('lifecycle trail (meta): one more read, one more body member and a write moved past a publish each fail; a reorder between publishes does not', () => {+ const publish = (what) => ({ method: 'POST', path: '/PublishXml', body: { ParameterXml: `<importexportxml><appmodules><appmodule>${what}</appmodule></appmodules></importexportxml>` }, status: 204 });+ const read = { method: 'GET', path: "/appmodules?$select=appmoduleid&$filter=uniquename eq 'contoso_x'", status: 200 };+ const view = { method: 'PATCH', path: '/savedqueries(0a1b2c3d-0000-4000-8000-00000000abcd)', body: { fetchxml: '<fetch/>' }, status: 204 };+ const form = { method: 'PATCH', path: '/systemforms(0a1b2c3d-0000-4000-8000-00000000abce)', body: { formxml: '<form/>' }, status: 204 };+ const trail = (requests) => trailOf({ requests }, { mark: 0, end: requests.length });+ const golden = trail([read, view, form, publish('a'), read]);+ assert.equal(trail([read, form, view, publish('a'), read]), golden, 'two requests between the same publishes may be sent in either order');+ const moreReads = describeDifference('build', golden, trail([read, read, view, form, publish('a'), read]));+ assert.match(moreReads, /\+1 GET appmodules/);+ const newMember = describeDifference('edit', golden, trail([read, { ...view, body: { fetchxml: '<fetch/>', returnedtypecode: 'contoso_x' } }, form, publish('a'), read]));+ assert.match(newMember, /The same requests by METHOD resource[\s\S]*\[0x before, 1x now\] in "up to publish 1: importexportxml\(appmodules\(appmodule=a\)\)":\n\s+PATCH \/savedqueries\(<id>\) \{fetchxml:string,returnedtypecode:string\}/);+ const late = trail([read, view, publish('a'), form, read]);+ assert.notEqual(late, golden, 'a write moved past the publish that should make it live');+ assert.match(describeDifference('rebuild', golden, late), /The same requests by METHOD resource[\s\S]*\[1x before, 0x now\] in "up to publish 1: importexportxml\(appmodules\(appmodule=a\)\)":\n\s+PATCH \/systemforms\(<id>\) \{formxml:string\}/);+ assert.equal(shape({ b: [1, 'x', { c: null }], a: true }), '{a:boolean,b:[1xnumber|1xstring|1x{c:null}]}');+ assert.equal(mask('/x(0a1b2c3d-0000-4000-8000-00000000abcd)?$filter=modifiedon gt 2026-01-02T03:04:05Z'), '/x(<id>)?$filter=modifiedon gt <time>');+ // Nothing a request carries is collapsed away: one more element of the same shape in a body's list (a column more in a table's+ // create), and one more kind of component in a publish (an option set beside the app), each change the trail.+ const table = { method: 'POST', path: '/EntityDefinitions', body: { Attributes: [{ SchemaName: 'contoso_name', MaxLength: 100 }] }, status: 204 };+ const twoColumns = { ...table, body: { Attributes: [...table.body.Attributes, { SchemaName: 'contoso_extra', MaxLength: 100 }] } };+ assert.notEqual(trail([twoColumns]), trail([table]), 'a column more in the same request changes the trail');+ assert.match(describeDifference('build', trail([table]), trail([twoColumns])), /\[0x before, 1x now\][\s\S]*Attributes:\[2x\{/);+ const appOnly = publish('11111111-0000-4000-8000-000000000001');+ const broader = { ...appOnly, body: { ParameterXml: appOnly.body.ParameterXml.replace('</importexportxml>', '<optionsets><optionset>contoso_stage</optionset></optionsets></importexportxml>') } };+ assert.notEqual(trail([broader]), trail([appOnly]), 'a publish that names one more kind of component changes the trail');+ assert.match(describeDifference('build', trail([appOnly]), trail([broader])), /The publishes were:[\s\S]*and are now:[\s\S]*optionset=contoso_stage/);+ // A publish whose ParameterXml is not ONE element-only document is kept raw, never normalized into a valid envelope's notation: text+ // before or after the document element (`undefined<importexportxml>…`), text beside child elements, or a second root.+ const valid = appOnly.body.ParameterXml;+ const targets = publishTargetsOf(valid);+ for (const bad of [`undefined${valid}`, `${valid}x`, valid.replace('<appmodules>', '<appmodules>unexpected'), `${valid}${valid}`]) {+ const seen = publishTargetsOf(bad);+ assert.notEqual(seen, targets, `kept apart from the valid envelope: ${bad}`);+ assert.match(seen, /^raw:/, `kept raw: ${bad}`);+ }+ assert.equal(publishTargetsOf(` \n${valid}\n `), targets, 'whitespace around the document element is not content');+});++// UPDATE_GOLDENS must never be the way a CI run turns green: a run that regenerates in CI compares nothing and would pass whatever was+// sent. So the regeneration is refused under CI, before the lifecycle runs and before anything is written — proven by running this file+// in a child process with CI's variables set (the child's own copy of this test returns at once).+test('lifecycle trail: UPDATE_GOLDENS=1 under CI is refused before anything is written, and the run fails', () => {+ if (process.env.LIFECYCLE_TRAIL_CHILD === '1') return;+ const before = PHASES.map((phase) => fs.readFileSync(goldenFile(phase)));+ const env = { ...process.env, CI: 'true', GITHUB_ACTIONS: 'true', UPDATE_GOLDENS: '1', LIFECYCLE_TRAIL_CHILD: '1' };+ // A child of `node --test` that inherits NODE_TEST_CONTEXT reports to its parent's runner instead of running as a run of its own.+ delete env.NODE_TEST_CONTEXT;+ const child = spawnSync(process.execPath, ['--test', '--test-name-pattern', 'phase sends exactly', __filename], { env, encoding: 'utf8', timeout: 180000 });+ const output = `${child.stdout}${child.stderr}`;+ assert.notEqual(child.status, 0, `the regenerating run under CI must fail:\n${output.slice(-2000)}`);+ assert.match(output, /UPDATE_GOLDENS=1 is refused under CI/);+ assert.deepEqual(PHASES.map((phase) => fs.readFileSync(goldenFile(phase))), before, 'and no golden was written');+});++// The regeneration rules themselves, on a golden of the test's own: refused under CI with nothing written; locally, a golden that differs+// is rewritten and the run fails; one that already holds the trail is not touched and passes.+test('lifecycle trail (meta): regeneration is refused under CI, and a local run that regenerates fails', () => {+ const file = path.join(makeTempDir('lifecycle-trail-golden-'), 'lifecycle-trail.meta.txt');+ fs.writeFileSync(file, 'stale\n');+ assert.throws(() => settleGolden('meta', file, 'fresh\n', { UPDATE_GOLDENS: '1', CI: 'true' }), /refused under CI/);+ assert.throws(() => settleGolden('meta', file, 'fresh\n', { UPDATE_GOLDENS: '1', TF_BUILD: 'True' }), /refused under CI/);+ assert.equal(fs.readFileSync(file, 'utf8'), 'stale\n', 'nothing was written under CI');+ assert.throws(() => settleGolden('meta', file, 'fresh\n', { UPDATE_GOLDENS: '1', CI: 'false' }), /regenerated lifecycle-trail\.meta\.txt/);+ assert.equal(fs.readFileSync(file, 'utf8'), 'fresh\n', 'a local run rewrites the golden');+ assert.doesNotThrow(() => settleGolden('meta', file, 'fresh\n', { UPDATE_GOLDENS: '1' }), 'a golden that already holds the trail passes');+ assert.throws(() => settleGolden('meta', file, 'other\n', {}), /trail differs/);+});\ No newline at end of filediff --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 7681c79b5..957406ea7 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@@ -23,7 +23,9 @@ const os = require('node:os');const path = require('node:path');const { createMakerSdk, createNodeWorkspaceStorage } = require('../vendor/cds-maker-sdk.cjs');// An apply that names no app folder and no workspace gets an app folder of its own: it holds its build lease in its workspace (helpers/own-app-folder.js).-const { inOwnFolder } = require('./helpers/own-app-folder.js');+const { inOwnFolder, ownAppFolder } = require('./helpers/own-app-folder.js');+const { recordBuildFailure, installBuildFailureDiagnostics } = require('./helpers/build-failure-diagnostics.js');+installBuildFailureDiagnostics(test);const { runSdkBuild: runSdkBuildInPlace, settleOwedPublishes } = require('../lib/sdk-build.js');const runSdkBuild = inOwnFolder(runSdkBuildInPlace);const { createFakeDataverse } = require('./helpers/fake-dataverse.js');@@ -99,7 +101,15 @@ function scenario(fakeOptions = {}) {async function build(spec, { publish = true, phases, sdk, warnings = [] } = {}) {const mark = fake.mark();const useSdk = sdk || await sdkOver();- const result = await runSdkBuild(spec, { sdk: useSdk, apply: true, publish, phases: phases || PHASES, warn: (w) => warnings.push(String(w)) });+ // A build that throws is usually one the test provokes (a failed write) and checks with assert.rejects; the one-off failure+ // of a build that should succeed (a file missing from the workspace) is diagnosed from the output alone, because the folder+ // is gone afterwards. The error is rethrown as it was; what the two folders held is printed only if the test fails.+ let result;+ try {+ result = await runSdkBuild(spec, { sdk: useSdk, apply: true, publish, phases: phases || PHASES, warn: (w) => warnings.push(String(w)) });+ } catch (error) {+ throw recordBuildFailure(error, [{ label: 'scenario workspace', dir }, { label: 'app folder', dir: ownAppFolder({ apply: true }).appDir }]);+ }return { result, mark, writes: fake.writeCounts(mark), warnings, sdk: useSdk };}return { fake, dir, sdkOver, build };diff --git a/plugins/model-apps/scripts/tests/retry-policy.test.js b/plugins/model-apps/scripts/tests/retry-policy.test.jsindex 43efdafb2..387b54a39 100644--- a/plugins/model-apps/scripts/tests/retry-policy.test.js+++ b/plugins/model-apps/scripts/tests/retry-policy.test.js@@ -57,6 +57,28 @@ test('judgeFailure: an explicit never wins over everything the failure carries,assert.strictEqual(judgeFailure({ message: 'x', cause: { transient: false, statusCode: 429 } }).never, true, 'the old reading of the error and its cause still holds');});+// REAL BUNDLE: the bundled SDK's errors for a write whose answer was lost. The SDK keeps the ConnectionError the write failed with — a 503, a+// 429, a reset — as the cause, and says the write MAY have committed and is never sent again. A whole build run again would send it again, so+// these are never run again, whatever the cause says; any other typed error beside a 503 still is (the control).+test('judgeFailure: an SDK write whose outcome is unknown is never run again, even when the answer it lost was a 503 or a reset', () => {+ const bundle = require('../vendor/cds-maker-sdk.cjs');+ const lost = (status) => new ConnectionError('https://contoso.crm.dynamics.com/api/data/v9.2/contoso_tasks(contoso_key=\'A-1\')', status, status ? 'Service Unavailable' : 'Request failed: read ECONNRESET');+ for (const status of [503, 429, 0]) {+ const upsert = new bundle.UpsertOutcomeUnknownError('contoso_task', { contoso_key: 'A-1' }, status, undefined, 'The upsert of contoso_task may have been written; it was not sent again.', lost(status));+ assert.strictEqual(upsert.code, 'UPSERT_OUTCOME_UNKNOWN');+ assert.strictEqual(judgeFailure(upsert).never, true, `UPSERT_OUTCOME_UNKNOWN over ${status}`);+ assert.strictEqual(retryPolicyFor(upsert), RETRY.NEVER);+ assert.strictEqual(isTransientHalt(new BuildHalt('sample-data failed', { phase: 'sample-data', cause: upsert, retry: retryPolicyFor(upsert) })), false);+ const app = Object.assign(new SdkError('APP_UPDATE_OUTCOME_UNKNOWN', 'The app update may have committed.'), { statusCode: status });+ Object.defineProperty(app, 'cause', { value: lost(status), enumerable: false });+ assert.strictEqual(judgeFailure(app).never, true, `APP_UPDATE_OUTCOME_UNKNOWN over ${status}`);+ // The control: another typed error over the same lost answer is still the service's to explain.+ const other = Object.assign(new SdkError('SOME_OTHER_CODE', 'x'), { statusCode: status });+ Object.defineProperty(other, 'cause', { value: lost(status), enumerable: false });+ assert.strictEqual(judgeFailure(other).never, false, `another typed error over ${status}`);+ }+});+test('judgeFailure: the HTTP status decides first — 429, 502, 503 and 504 are transient wherever in the chain the service\'s answer sits', () => {for (const status of [429, 502, 503, 504]) {assert.strictEqual(isTransientHalt(connectionError(status, 'nothing to read here')), true, `${status} on the error`);diff --git a/plugins/model-apps/scripts/tests/run-tests.test.js b/plugins/model-apps/scripts/tests/run-tests.test.jsindex 91c1a3c26..d5c199ef6 100644--- a/plugins/model-apps/scripts/tests/run-tests.test.js+++ b/plugins/model-apps/scripts/tests/run-tests.test.js@@ -7,6 +7,7 @@ const path = require('node:path');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');+const { PREVIOUS_RELEASE, BUNDLE_PATH } = require('./helpers/previous-bundle.js');test('pluginTestFiles discovers every *.test.js as a scripts/tests path, sorted', () => {const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'runtests-'));@@ -390,6 +391,22 @@ test('the model-apps CI workflow runs the suite once with pinned TypeScript andif (release !== null) assert.strictEqual(JSON.parse(release).version, '2.13.0', 'the fetched commit is the 2.13.0 release');});+// The upgrade tests (workspace-upgrade-*-real-bundle.test.js) need the previous release's SDK bundle, which a shallow checkout does not+// have, and FAIL in CI without it: each job that runs the suite fetches that release by its hash and names the bundle — the same commit+// helpers/previous-bundle.js checks the bundle's SHA-256 against, so the two cannot drift apart on a re-vendor.+test('the model-apps CI workflow gives every suite run the previous release\'s SDK bundle the upgrade tests read', () => {+ const { PREVIOUS_RELEASE, BUNDLE_PATH } = require('./helpers/previous-bundle.js');+ const wf = fs.readFileSync(WORKFLOW, 'utf8');+ for (const id of ['test-model-apps-scripts', 'test-model-apps-lexer-oracles']) {+ const job = workflowJob(wf, id);+ const fetchAt = job.indexOf(`git fetch --no-tags --depth=1 origin ${PREVIOUS_RELEASE}`);+ assert.ok(fetchAt >= 0, `${id} fetches the previous release (${PREVIOUS_RELEASE}) by its hash`);+ assert.ok(job.includes(`git cat-file blob FETCH_HEAD:${BUNDLE_PATH} > "$RUNNER_TEMP/previous-cds-maker-sdk.cjs"`), `${id} extracts its bundle under RUNNER_TEMP`);+ assert.match(job, /echo "MODEL_APPS_PREVIOUS_BUNDLE=\$RUNNER_TEMP\/previous-cds-maker-sdk\.cjs" >> "\$GITHUB_ENV"/, `${id} names it to the later steps`);+ assert.ok(fetchAt < job.search(/^ {14}run: node scripts\/run-tests\.js[ \t]*$/m), `${id} fetches it before the suite runs`);+ }+});+// The eval tests and runners read committed fixtures, which a Windows checkout gives CRLF line ends, and the routing runner starts agent CLIs as// child processes (.cmd shims on Windows), so the eval job runs on every system and Node version the suite job runs on; the lexer's oracle// sweeps compare it with parsers whose identifier tables are not those of the Node version's engine, so they run on both Node versions. Textdiff --git a/plugins/model-apps/scripts/tests/sdk-error-codes-real-bundle.test.js b/plugins/model-apps/scripts/tests/sdk-error-codes-real-bundle.test.jsnew file mode 100644index 000000000..a8a8bddba--- /dev/null+++ b/plugins/model-apps/scripts/tests/sdk-error-codes-real-bundle.test.js@@ -0,0 +1,209 @@+'use strict';+// EVERY CODE THE BUNDLED SDK CAN REPORT, and what the skills do with it — so a new SDK code fails a named test at the uptake instead of+// reaching a maker unclassified.+//+// The skills decide three things from an SDK error's `code`, never from its words:+// - whether the build runs again (lib/retry-policy.js, judgeFailure): a typed error is a refusal (rule 6) unless the failure it carries+// as its `cause` is transient — EXCEPT a code that says a write was sent and its outcome is unknown (OUTCOME_UNKNOWN_CODES), which+// is never run again, because a run again re-sends the write the SDK refused to re-send; and the codes that wrap a failure+// (WRAPPED_SERVICE_CODES, CAUSE_WRAPPER_CODES), which are judged by what they wrap;+// - whether a failed page push wrote nothing (lib/genpage-sdk.js, writeOutcome / PRE_WRITE_REFUSALS);+// - which step a maker is told to take (lib/entity-provision.js, operatorRemedy).+// A code the SDK adds lands in the first rule's default — a refusal over a clean failure, run again over a transient one — which is+// right for most codes and WRONG for one that says a write's outcome is unknown. This uptake brought three new codes the skill could+// receive with no test failing; this file makes the next one fail here.+//+// HOW THE CODES ARE FOUND. The SDK publishes no list of its codes: `SdkError.code` is a free string, raised in many forms — the bundle,+// minified, shows `new X.SdkError("CODE", …)`, `super("CODE", …)` in a subclass, `X.FOO_CODE = "CODE"` constants, `{ code: "CODE" }` and+// `{ errorCode: "CODE" }` results by value, `warn("CODE", …)` warnings, `reasonCode: "CODE"` observations and issue kinds pushed onto a+// list. So the scan takes EVERY code-shaped string literal in the bundle (upper case, at least one underscore) and leaves out only the+// OCCURRENCES that are provably not a code — an enum's reverse mapping and a re-export's property name (isNonCodeOccurrence) — never a+// value because of how it is spelled: a literal is a code if any one of its occurrences is not one of those two.+// ITS LIMITS, which a reader must know before trusting a green run:+// - a code that does not follow the convention — lower case, a digit first, one word with no underscore (`"FAILED"`) — is not seen;+// - a code built at run time from pieces (`"FOO_" + kind`, a template) is not seen — none is today;+// - a code that only ever arrives from the service (an OData `0x8004…` code) is not an SDK code and is the retry policy's own table;+// - a literal that is not a code is listed (harmless: it is acknowledged once as `diagnostic`).+// Within the convention it over-collects rather than misses, which is the side a regression net must err on; the authoritative list is an+// SDK-side ask.+//+// THE FIXTURE (fixtures/sdk-error-codes.json) names every code the scan finds, with what the skills do with it:+// connection CONNECTION_ERROR: the HTTP status it carries decides (429/502/503/504 run again; any other is final)+// outcome-unknown a write that may have committed; NEVER run again, whatever failure it carries (OUTCOME_UNKNOWN_CODES)+// outcome-unknown-unresolved OPEN DECISION, not a contract: a code whose words say an outcome is unknown that the retry policy today+// runs again when the failure it carries is a transient TRANSPORT failure (a business process flow's+// create rollback, deactivate and reactivate; a deactivate the gateway answers with a 5xx carries the+// SDK's own typed error as its cause instead, which is final). Whether a run again is safe is undecided: finding the flow by name is not proof it is+// this build's. Pinned as it is today so that the decision, either way, is a deliberate move of these+// codes — to `outcome-unknown` (and OUTCOME_UNKNOWN_CODES) or to `typed`.+// wraps-failure judged by the failure it wraps (WRAPPED_SERVICE_CODES, CAUSE_WRAPPER_CODES)+// page-pre-write a page push refused before it sent a write: writeOutcome says it wrote 'nothing' (PRE_WRITE_REFUSALS)+// typed a refusal: final over a clean failure, run again over a transient one (the default)+// diagnostic not an error the skills receive as a failure: a warning, an observation's reason, an issue kind+// Each category's behaviour is asserted below against the plugin's own policy with the bundle's own error classes.+//+// WHEN THIS FAILS: a code the bundle has and the fixture does not is NEW — decide, in this order: does its SDK message say a write may+// have committed (add it to OUTCOME_UNKNOWN_CODES in lib/retry-policy.js, category `outcome-unknown`)? does it wrap a failure? is it a page+// refusal raised before any write (PRE_WRITE_REFUSALS in lib/genpage-sdk.js)? does a maker need a step only a person can take+// (operatorRemedy in lib/entity-provision.js)? Then add it to the fixture with its category. A code the fixture has and the bundle does not+// was REMOVED or renamed: every branch of the plugin on it (the message lists the files) is now dead — move it to the new code.+const test = require('node:test');+const assert = require('node:assert/strict');+const fs = require('node:fs');+const path = require('node:path');+const { judgeFailure } = require('../lib/retry-policy.js');+const { writeOutcome } = require('../lib/genpage-sdk.js');+const { SdkError, ConnectionError } = require('../lib/maker-sdk.js');++const SCRIPTS = path.resolve(__dirname, '..');+const BUNDLE = path.join(SCRIPTS, 'vendor', 'cds-maker-sdk.cjs');+const FIXTURE = path.join(__dirname, 'fixtures', 'sdk-error-codes.json');+const CATEGORIES = ['connection', 'outcome-unknown', 'outcome-unknown-unresolved', 'wraps-failure', 'page-pre-write', 'typed', 'diagnostic'];++const LITERAL = /["'`]([A-Z][A-Z0-9]*(?:_[A-Z0-9]+)+)["'`]/g;+// The two OCCURRENCES of a code-shaped literal that are provably not a code, read from what stands right before it:+// e[e.ONE_COLUMN=0]="ONE_COLUMN" a TypeScript enum's reverse mapping: the member's name+// Object.defineProperty(t,"FOO_UNREADABLE_CODE",{…}) a re-export: the property's name (its VALUE is the code, a literal elsewhere)+// Only that occurrence is left out. The same text anywhere else — `new SdkError("ONE_COLUMN", …)`, a code that happens to end in+// `_CODE` — is a code, so no spelling can hide one.+function isNonCodeOccurrence(source, at, literal) {+ const before = source.slice(Math.max(0, at - 160), at);+ return new RegExp(`\\[[\\w$]+\\.${literal}=\\d+\\]=$`).test(before) || /\bdefineProperty\(\s*[\w$.]+\s*,\s*$/.test(before);+}+function codesIn(source) {+ const codes = new Set();+ for (const m of source.matchAll(LITERAL)) if (!isNonCodeOccurrence(source, m.index, m[1])) codes.add(m[1]);+ return codes;+}++// Where the plugin's own sources name a code (outside the bundle and the tests), so a removed code's message says what now branches on nothing.+function pluginMentions() {+ const mentions = new Map();+ const walk = (dir) => {+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {+ const full = path.join(dir, entry.name);+ if (entry.isDirectory()) {+ if (!['vendor', '_vendor-build', 'node_modules', 'tests'].includes(entry.name)) walk(full);+ } else if (entry.name.endsWith('.js')) {+ for (const m of fs.readFileSync(full, 'utf8').matchAll(LITERAL)) {+ if (!mentions.has(m[1])) mentions.set(m[1], new Set());+ mentions.get(m[1]).add(path.relative(SCRIPTS, full).replace(/\\/g, '/'));+ }+ }+ }+ };+ walk(SCRIPTS);+ return mentions;+}++// The difference between the bundle's codes and the fixture's, as the failure message a maintainer acts on.+function describeCodeDrift(bundleCodes, fixture, mentions) {+ const added = [...bundleCodes].filter((code) => !Object.prototype.hasOwnProperty.call(fixture, code)).sort();+ const removed = Object.keys(fixture).filter((code) => !bundleCodes.has(code)).sort();+ const lines = [];+ if (added.length) {+ lines.push(`The bundled SDK has ${added.length} code(s) fixtures/sdk-error-codes.json does not classify:`);+ for (const code of added) lines.push(` ${code}${mentions.has(code) ? ` (named by ${[...mentions.get(code)].join(', ')})` : ''}`);+ lines.push(' For each: if its SDK message says a write may have committed, add it to OUTCOME_UNKNOWN_CODES (lib/retry-policy.js); if it is a page',+ ' refusal raised before any write, to PRE_WRITE_REFUSALS (lib/genpage-sdk.js); if a maker must act, give it a step (operatorRemedy,',+ ' lib/entity-provision.js). Then add it to the fixture with its category (see the header of this test).');+ }+ if (removed.length) {+ lines.push(`The bundled SDK no longer has ${removed.length} code(s) the fixture lists:`);+ for (const code of removed) lines.push(` ${code}${mentions.has(code) ? ` — still named by ${[...mentions.get(code)].join(', ')}: those branches can no longer be taken` : ''}`);+ lines.push(' Find what the SDK raises instead, move the plugin\'s branches to it, and update the fixture.');+ }+ return lines.join('\n');+}++const fixture = () => JSON.parse(fs.readFileSync(FIXTURE, 'utf8'));+const URL = 'https://contoso.crm.dynamics.com/api/data/v9.2/contoso_tasks';+// The bundle attaches the failure an error wraps as its `cause`, not enumerably (its attachCause): so is it here.+const over = (error, cause) => Object.defineProperty(error, 'cause', { value: cause, enumerable: false, configurable: true });+const unavailable = () => new ConnectionError(URL, 503, 'Service Unavailable');+const reset = () => new ConnectionError(URL, 0, 'Request failed: read ECONNRESET');+const badRequest = () => new ConnectionError(URL, 400, 'Bad Request');++test('SDK codes: every code the bundled SDK can report is classified in fixtures/sdk-error-codes.json, and nothing more', () => {+ const codes = codesIn(fs.readFileSync(BUNDLE, 'utf8'));+ const drift = describeCodeDrift(codes, fixture(), pluginMentions());+ assert.equal(drift, '', drift);+});++test('SDK codes: the fixture uses only the known categories and is sorted, one code per line', () => {+ const text = fs.readFileSync(FIXTURE, 'utf8').replace(/\r\n/g, '\n');+ const codes = fixture();+ const unknown = Object.entries(codes).filter(([, category]) => !CATEGORIES.includes(category)).map(([code, category]) => `${code}: ${category}`);+ assert.deepEqual(unknown, [], 'every category is one this test asserts');+ assert.deepEqual(Object.keys(codes), Object.keys(codes).sort(), 'the fixture is sorted, so a diff shows exactly the codes that moved');+ assert.equal(text, `${JSON.stringify(codes, null, 2)}\n`, 'the fixture is written as JSON.stringify(…, null, 2)');+});++test('SDK codes: each category holds in the plugin\'s retry policy and page outcome, over the bundle\'s own error classes', () => {+ const failures = [];+ const expect = (code, what, actual, wanted) => { if (actual !== wanted) failures.push(`${code}: ${what} is ${actual}, expected ${wanted}`); };+ for (const [code, category] of Object.entries(fixture())) {+ const make = () => new SdkError(code, `the SDK refused (${code})`);+ switch (category) {+ case 'connection':+ expect(code, 'a 503 is never run again', judgeFailure(unavailable()).never, false);+ expect(code, 'a 400 is never run again', judgeFailure(badRequest()).never, true);+ break;+ case 'outcome-unknown':+ for (const cause of [unavailable(), reset()]) expect(code, `over ${cause.message}, never run again`, judgeFailure(over(make(), cause)).never, true);+ expect(code, 'alone, never run again', judgeFailure(make()).never, true);+ break;+ case 'outcome-unknown-unresolved':+ case 'typed':+ case 'page-pre-write':+ expect(code, 'alone, never run again', judgeFailure(make()).never, true);+ for (const cause of [unavailable(), reset()]) expect(code, `over ${cause.message}, never run again`, judgeFailure(over(make(), cause)).never, false);+ expect(code, 'over a 400, never run again', judgeFailure(over(make(), badRequest())).never, true);+ if (category === 'page-pre-write') expect(code, 'a page push it refuses wrote', writeOutcome(make()), 'nothing');+ break;+ case 'wraps-failure':+ if (code === 'WEB_RESOURCE_UNVERIFIED') {+ // A web resource whose published content could not be confirmed: with no failure behind it, a run again writes it again by id.+ expect(code, 'alone, never run again', judgeFailure(make()).never, false);+ expect(code, 'over a 400, never run again', judgeFailure(over(make(), badRequest())).never, true);+ } else if (code === 'ENRICH_DEFAULT_VIEWS_PUBLISH_FAILED') {+ // The SDK's own sentence around the publish it could not make (lib/retry-policy.js, WRAPPER_SENTENCE): what it embeds decides.+ const wrapped = (inner) => new SdkError(code, `enrichDefaultViews: 2 view(s) on 'contoso_task' were saved but the publish FAILED, so none of them is live (${inner}). Re-publish the entity to make them visible; the saves themselves are unaffected.`);+ expect(code, 'around a 503, never run again', judgeFailure(wrapped('HTTP 503 from https://contoso.crm.dynamics.com/api/data/v9.2/PublishXml: Service Unavailable')).never, false);+ expect(code, 'around a 400, never run again', judgeFailure(wrapped('HTTP 400 from https://contoso.crm.dynamics.com/api/data/v9.2/PublishXml: Bad Request')).never, true);+ } else {+ failures.push(`${code}: a wrapper this test does not know how to exercise — add its case`);+ }+ break;+ case 'diagnostic':+ break;+ default:+ failures.push(`${code}: unknown category ${category}`);+ }+ }+ assert.deepEqual(failures, [], `The plugin's handling of these codes is not what fixtures/sdk-error-codes.json says:\n${failures.join('\n')}`);+});++// The guard of the guard: the scan sees a code in each form the bundle raises one, leaves enum names and constant names out, and the+// drift message names a new and a removed code with the plugin files that name it — so the check can never pass because it sees nothing.+test('SDK codes (meta): the scan finds a code in every form the bundle raises one, and the drift message names what moved', () => {+ const codes = codesIn(fs.readFileSync(BUNDLE, 'utf8'));+ for (const code of [+ 'VERSION_CONFLICT', // super("VERSION_CONFLICT", …) in a subclass+ 'APP_UPDATE_OUTCOME_UNKNOWN', // new X.SdkError("APP_UPDATE_OUTCOME_UNKNOWN", …)+ 'COMMAND_IMMUTABLE_COLUMN_CHANGED', // a constant: X.COMMAND_IMMUTABLE_COLUMN_CHANGED_CODE = "COMMAND_IMMUTABLE_COLUMN_CHANGED"+ 'ARTIFACT_ALREADY_EXISTS', // a push result by value: { code: "ARTIFACT_ALREADY_EXISTS", … }+ 'PREVIEW_APP_PIN_GUARD_NOT_EVALUATED', // a warning: warn("PREVIEW_APP_PIN_GUARD_NOT_EVALUATED", …)+ ]) assert.ok(codes.has(code), `the scan finds ${code}`);+ // What is left out is proven on isolated sources, not by what the whole bundle happens to hold today (a later SDK may legitimately raise a+ // code that is also an enum member's name): only an OCCURRENCE that is provably not a code is left out — never a value because of how it is spelled.+ assert.deepEqual([...codesIn('throw new SdkError("INVALID_ERROR_CODE", "bad")')], ['INVALID_ERROR_CODE'], 'a code that ends in _CODE is a code');+ assert.deepEqual([...codesIn('e[e.TWO_COLUMN=1]="TWO_COLUMN";throw new SdkError("TWO_COLUMN", "bad")')], ['TWO_COLUMN'], 'a code that is also an enum member name is a code');+ assert.deepEqual([...codesIn('(function(e){e[e.ONE_COLUMN=0]="ONE_COLUMN"})(x)')], [], 'an enum reverse mapping alone is not');+ assert.deepEqual([...codesIn('Object.defineProperty(t,"FOO_UNREADABLE_CODE",{enumerable:!0,get:function(){return r.FOO_UNREADABLE_CODE}});r.FOO_UNREADABLE_CODE="FOO_UNREADABLE"')], ['FOO_UNREADABLE'], 'an export\'s property name is not a code; the constant\'s value is');+ const mentions = new Map([['OLD_CODE', new Set(['lib/sdk-build.js'])]]);+ const drift = describeCodeDrift(new Set(['KEPT', 'NEW_CODE']), { KEPT: 'typed', OLD_CODE: 'typed' }, mentions);+ assert.match(drift, /does not classify:\n {2}NEW_CODE\n/);+ assert.match(drift, /no longer has 1 code\(s\)[^\n]*\n {2}OLD_CODE — still named by lib\/sdk-build\.js/);+ assert.equal(describeCodeDrift(new Set(['KEPT']), { KEPT: 'typed' }, mentions), '');+});diff --git a/plugins/model-apps/scripts/tests/sdk-http-client.test.js b/plugins/model-apps/scripts/tests/sdk-http-client.test.jsindex 9018e80a7..fec36d840 100644--- a/plugins/model-apps/scripts/tests/sdk-http-client.test.js+++ b/plugins/model-apps/scripts/tests/sdk-http-client.test.js@@ -1907,3 +1907,68 @@ test('publish once: the service protection codes are the three the api-limits pa['nothing', null],]) assert.strictEqual(isServiceProtectionRefusal(res), false, what);});++// A failure's body carries the history of the sends that led to it, so a caller that would read a later answer as a definitive refusal (the business-rule gate in+// lib/sdk-build.js) can tell it is not one when an earlier send of the same request may have run. The marker is not enumerable: nothing that compares or prints a body sees it.+const { HTTP_SEND_HISTORY } = require('../lib/sdk-http-client.js');+const MEMBER_POST = 'https://org.crm.dynamics.com/api/data/v9.0/workflows(00000000-0000-0000-0000-000000000000)/Microsoft.Dynamics.CRM.CreateProcessWithWfomJson';+const REFUSED = { statusCode: 400, headers: {}, body: '{"error":{"code":"0x80040216","message":"An unexpected error occurred."}}' };+const clientOver = (scripted) => {+ const { request, calls } = fakeTransport(scripted);+ return { calls, http: createAzHttpClient('https://org.crm.dynamics.com', { getToken: () => 'TOK', request, sleep: async () => {} }) };+};++test('a failure answered on the first send carries { sends: 1, earlierAmbiguous: false }, and the marker is invisible to a comparison', async () => {+ const { http } = clientOver(REFUSED);+ const res = await http.post(MEMBER_POST, {});+ assert.deepStrictEqual(res.body[HTTP_SEND_HISTORY], { sends: 1, earlierAmbiguous: false });+ assert.deepStrictEqual(res.body, { error: { code: '0x80040216', message: 'An unexpected error occurred.' } });+});++test('a 503 re-sent by the client and then answered 400 says an earlier send was ambiguous', async () => {+ const { http, calls } = clientOver((opts, n) => (n === 1 ? { statusCode: 503, headers: {}, body: '{"error":{"code":"x","message":"gateway"}}' } : REFUSED));+ const res = await http.post(MEMBER_POST, {});+ assert.strictEqual(calls.length, 2);+ assert.strictEqual(res.status, 400);+ assert.deepStrictEqual(res.body[HTTP_SEND_HISTORY], { sends: 2, earlierAmbiguous: true });+});++test('a send that got no answer, re-sent and then refused, says so as well', async () => {+ const { http } = clientOver((opts, n) => (n === 1 ? { error: 'socket hang up', code: 'ECONNRESET' } : REFUSED));+ const res = await http.post(MEMBER_POST, {});+ assert.deepStrictEqual(res.body[HTTP_SEND_HISTORY], { sends: 2, earlierAmbiguous: true });+});++test('the same request called again by the caller after a 5xx it gave up on is refused as one whose earlier send was ambiguous', async () => {+ // The SDK re-calls a request itself: the second call is a first send of this client's loop, and only the ledger knows of the first.+ const { http } = clientOver((opts, n) => (n <= 6 ? { statusCode: 503, headers: {}, body: '' } : REFUSED));+ assert.strictEqual((await http.post(MEMBER_POST, {})).status, 503);+ const second = await http.post(MEMBER_POST, {});+ assert.strictEqual(second.status, 400);+ assert.deepStrictEqual(second.body[HTTP_SEND_HISTORY], { sends: 1, earlierAmbiguous: true });+});++test('what proves a send did not run is not ambiguity: a 401 refresh and a service protection 429 leave earlierAmbiguous false', async () => {+ const protection = { statusCode: 429, headers: {}, body: '{"error":{"code":"0x80072322","message":"Number of requests exceeded the limit"}}' };+ for (const first of [{ statusCode: 401, headers: {}, body: '' }, protection]) {+ const { http } = clientOver((opts, n) => (n === 1 ? first : REFUSED));+ const res = await http.post(MEMBER_POST, {});+ assert.strictEqual(res.status, 400);+ assert.strictEqual(res.body[HTTP_SEND_HISTORY].earlierAmbiguous, false, String(first.statusCode));+ assert.strictEqual(res.body[HTTP_SEND_HISTORY].sends, 2);+ }+});++test('the ledger is per request: another URL, and a read of the same URL, are not poisoned by an ambiguous write', async () => {+ const { http } = clientOver((opts) => (opts.url.endsWith('/poisoned') ? { statusCode: 503, headers: {}, body: '' } : REFUSED));+ await http.post('https://org.crm.dynamics.com/api/data/v9.0/poisoned', {});+ assert.strictEqual((await http.post(MEMBER_POST, {})).body[HTTP_SEND_HISTORY].earlierAmbiguous, false);+ assert.strictEqual((await http.get('https://org.crm.dynamics.com/api/data/v9.0/poisoned')).status, 503);+ assert.strictEqual((await http.get(MEMBER_POST)).body[HTTP_SEND_HISTORY].earlierAmbiguous, false);+});++test('a success carries no history', async () => {+ const { http } = clientOver({ statusCode: 200, headers: {}, body: '{"ok":true}' });+ const res = await http.post(MEMBER_POST, {});+ assert.deepStrictEqual(Object.getOwnPropertySymbols(res.body), []);+});diff --git a/plugins/model-apps/scripts/tests/sdk-opt-ins.test.js b/plugins/model-apps/scripts/tests/sdk-opt-ins.test.jsindex 1feb0af3b..ccfeca578 100644--- a/plugins/model-apps/scripts/tests/sdk-opt-ins.test.js+++ b/plugins/model-apps/scripts/tests/sdk-opt-ins.test.js@@ -165,3 +165,15 @@ test('the build creates every app published: its app definition leaves `publishe// (RetrieveUnpublishedMultiple), where the build's own probes could not see a draft.assert.deepStrictEqual(scriptsMatching(/\bpublished\s*:\s*false\b/), ['apps.js'], 'no other script creates a draft app, which its own probes cannot see');});++// --- results whose meaning the bundled SDK changed -------------------------------------------------------------++// The bundled SDK's upsertRecord() reports `created` as `undefined` unless it is asked to classify the write (`reportCreated: true`):+// a plain upsert answers 204 to an insert and to an update alike, so the `false` it used to report for every insert was wrong. And its+// fetchSolution() now returns kinds it used to drop (environment variables, connection references, field security profiles, Custom+// APIs, duplicate-detection rules). No script calls either, so neither change reaches a maker; a script that starts to must read+// `created === true` / `=== false` (never `!created`) and ignore the kinds it does not model — this fails until it is looked at.+test('no script reads upsertRecord() or fetchSolution(), whose results the bundled SDK changed', () => {+ assert.deepStrictEqual(scriptsMatching(/\bupsertRecord\b/), [], 'upsertRecord: `created` is undefined unless reportCreated is asked; UPSERT_OUTCOME_UNKNOWN is never re-sent (lib/retry-policy.js)');+ assert.deepStrictEqual(scriptsMatching(/\bfetchSolution\b/), [], 'fetchSolution: it now returns kinds the plugin does not model');+});diff --git a/plugins/model-apps/scripts/tests/sdk-options-real-bundle.test.js b/plugins/model-apps/scripts/tests/sdk-options-real-bundle.test.jsnew file mode 100644index 000000000..d57367e33--- /dev/null+++ b/plugins/model-apps/scripts/tests/sdk-options-real-bundle.test.js@@ -0,0 +1,342 @@+'use strict';+// THE OPTIONS THE SKILLS PASS TO THE BUNDLED SDK: THAT IT STILL READS THEM, AND THAT EACH STILL DOES WHAT IT IS PASSED FOR.+//+// An option is a property of a plain object, so an SDK that renames or drops one does not fail: it ignores it, and the behaviour the+// option asked for silently goes away — the language a form's labels are written in, the recovery of a form create whose answer was+// lost, the publish a build defers to one envelope. sdk-surface-contract.test.js guards the METHODS the skills call; this file guards+// their OPTIONS, at the real bundle's boundary:+//+// 1. Factory options. Every option a script passes to createMakerSdk — found by scanning the call sites, so a new one is forced into+// SKILL_FACTORY_OPTIONS — is READ by the bundle's own createMakerSdk (an options object that records the keys read of it). The+// bundle reads each option by name at construction (measured: it never spreads or enumerates the object, so an option it does not+// know is never read — the meta test proves an unknown key is not reported as read). lib/maker-sdk.js adds two (the compiler, the+// Power Apps service client) and keeps one of the plugin's own (`connectivity`) from reaching the SDK.+// 2. Per-call options with no trace on a fault-free request: `overwrite` (fetchArtifact discards a dirty local copy), `publish:false` and+// `excludeViewIds` (enrichDefaultViews defers its publish and leaves the author's views alone), and the read options of queryRecords+// and findTables. Each is called on the stateful fake environment with an options object that records what is read, and the effect+// of `publish:false` — no publish sent, the publish owed reported — is asserted as well.+//+// 3. EFFECTS. A read is only a rename detector: an SDK that reads an option and then ignores it passes it. So what each option is passed+// for is asserted by what it changes, here or in the test that owns that behaviour (named beside each factory option below):+// readConcurrency here: the page backend's four file downloads are in flight at once+// excludeViewIds here: an excluded default view is not written; without the option it is+// overwrite here: an edited workspace copy is handed back without it, replaced with it+// publish:false here: no publish is sent and the publish owed is reported; without it one is sent+// queryRecords here: select, filter, orderBy and top reach the query; paginate reads to the last page, and without it the+// first page only; findTables' top caps its answer+// detail genpage-verbs-real-bundle.test.js (generateGenPageRuntimeTypes, through `genpage.js types`)+// verify sdk-publication-real-bundle.test.js (publishArtifact answers `verified` from its read-back)+// The options that are a request's DATA — a column's maxLength, a status reason's label, a lookup's criteria (resolveArtifact,+// findArtifact), the members a push adds — change the request body or URL, which the lifecycle's request trail pins for every call+// on its path (lifecycle-trail-golden-real-bundle.test.js). Off that path and not pinned: updateColumn's options, the BPF reads' orderBy+// beyond the query string (no lifecycle BPF), seedRecordGraph's entitySetFor/createdIds beyond the sample data the lifecycle seeds.+// A failure says which option no longer reads, or no longer does what it is passed for: find what the SDK calls or does now, and move every+// call site and this file to it.+const test = require('node:test');+const assert = require('node:assert/strict');+const fs = require('node:fs');+const path = require('node:path');+const { makeTempDir } = require('./helpers/temp-dirs.js');+const { productionScripts, scriptLabel, withoutComments } = require('./helpers/production-scripts.js');+const { createLifecycleOrg } = require('./helpers/fake-lifecycle-org.js');+const { seedForeignWork, FOREIGN } = require('./helpers/lifecycle-harness.js');+const { createAzHttpClient } = require('../lib/sdk-http-client.js');+const makerSdk = require('../lib/maker-sdk.js');++const BUNDLE = path.resolve(__dirname, '..', 'vendor', 'cds-maker-sdk.cjs');++// Every option the scripts pass to createMakerSdk, and where its effect is pinned. Alphabetical, one per line.+const SKILL_FACTORY_OPTIONS = {+ createRecovery: 'form-create-recovery-real-bundle.test.js — a lost-answer Main form create is adopted with it, and halts without it',+ httpClient: 'every real-bundle test — the transport',+ instanceUrl: 'every real-bundle test — the environment the requests go to',+ languageCode: 'lcid-real-bundle.test.js — FormXML labels stamped at the LCID given, and at 1033 without it',+ readConcurrency: 'this file (effect): a page\'s four file downloads are in flight at once; sdk-opt-ins.test.js: passed exactly where a read it overlaps is made',+ solutionUniqueName: 'table-columns-in-create.test.js — each column request carries MSCRM.SolutionUniqueName; form-create-recovery-real-bundle.test.js — which instance carries it',+ workspaceStorage: 'workspace-projection-real-bundle.test.js — where the workspace copies are kept',+};+// What lib/maker-sdk.js adds to every instance (and which a caller may name to override).+const FACTORY_ADDED_OPTIONS = {+ powerAppsServiceClient: 'connectivity-real-bundle.test.js — the client of the connection and connector reads, for a caller that asks for `connectivity`',+ typescript: 'genpage-sdk-real-bundle.test.js — every page create the backend makes is compiled through it',+};+// The plugin's own request to lib/maker-sdk.js; it must never reach the SDK.+const PLUGIN_ONLY_OPTIONS = ['connectivity'];++// The keys of the object literal that opens at `open` (a `{`): `key: value`, a shorthand `key`, and the keys of each object literal inside a+// spread (`...(languageCode ? { languageCode } : {})`). Strings and template literals are skipped; nested objects in a VALUE are not keys.+// createMakerSdk({ workspaceStorage: storage(dir), instanceUrl: env, httpClient, ...(lang ? { languageCode: lang } : {}) })+// -> workspaceStorage, instanceUrl, httpClient, languageCode+function objectKeys(src, open) {+ const keys = [];+ let depth = 0;+ let i = open;+ let expectKey = false;+ let spreadFrom = -1;+ const skipString = (at) => {+ const quote = src[at];+ let j = at + 1;+ while (j < src.length && src[j] !== quote) j += src[j] === '\\' ? 2 : 1;+ return j;+ };+ for (; i < src.length; i++) {+ const ch = src[i];+ if (ch === '\'' || ch === '"' || ch === '`') { i = skipString(i); continue; }+ if (ch === '{' || ch === '(' || ch === '[') {+ depth++;+ if (depth === 1) expectKey = true;+ else if (ch === '{' && spreadFrom >= 0) {+ const inner = objectKeys(src, i);+ keys.push(...inner.keys);+ i = inner.end;+ depth--;+ }+ continue;+ }+ if (ch === '}' || ch === ')' || ch === ']') {+ depth--;+ if (depth === 0) return { keys, end: i };+ continue;+ }+ if (depth !== 1) continue;+ if (ch === ',') { expectKey = true; spreadFrom = -1; continue; }+ if (!expectKey || /\s/.test(ch)) continue;+ expectKey = false;+ if (src.startsWith('...', i)) { spreadFrom = i; i += 2; continue; }+ const m = /^([A-Za-z_$][\w$]*)\s*(?=[:,}])/.exec(src.slice(i, i + 80));+ if (m) { keys.push(m[1]); i += m[1].length - 1; }+ }+ return { keys, end: i };+}++// Every key a production script passes in a `createMakerSdk({ … })` call, with the scripts that pass it.+function factoryOptionsPassed() {+ const found = new Map();+ for (const file of productionScripts()) {+ const src = withoutComments(fs.readFileSync(file, 'utf8'));+ for (const m of src.matchAll(/\bcreateMakerSdk\(\s*\{/g)) {+ for (const key of objectKeys(src, m.index + m[0].length - 1).keys) {+ if (!found.has(key)) found.set(key, new Set());+ found.get(key).add(scriptLabel(file));+ }+ }+ }+ return found;+}++// The keys `create` reads of the options it is given (an options object that records each `get`).+function keysReadBy(create, options) {+ const read = new Set();+ const recording = new Proxy(options, { get(target, key, receiver) { if (typeof key === 'string') read.add(key); return Reflect.get(target, key, receiver); } });+ create(recording);+ return read;+}++const NOOP_CLIENT = { get: async () => ({}), post: async () => ({}), patch: async () => ({}), delete: async () => ({}), put: async () => ({}) };+function everyFactoryOption(dir) {+ const bundle = require(BUNDLE);+ return {+ workspaceStorage: bundle.createNodeWorkspaceStorage(dir), instanceUrl: 'https://contoso.crm.dynamics.com', httpClient: NOOP_CLIENT,+ solutionUniqueName: 'ContosoCore', languageCode: 1036, createRecovery: 'adoptExact', readConcurrency: 4,+ typescript: () => null, powerAppsServiceClient: NOOP_CLIENT,+ };+}++test('SDK options: every option a script passes to createMakerSdk is in SKILL_FACTORY_OPTIONS (or is the plugin\'s own)', () => {+ const passed = factoryOptionsPassed();+ const known = new Set([...Object.keys(SKILL_FACTORY_OPTIONS), ...Object.keys(FACTORY_ADDED_OPTIONS), ...PLUGIN_ONLY_OPTIONS]);+ const unlisted = [...passed].filter(([key]) => !known.has(key)).map(([key, files]) => `${key} (${[...files].join(', ')})`);+ assert.deepEqual(unlisted, [], `Add these createMakerSdk options to SKILL_FACTORY_OPTIONS, with the test that pins their effect: ${unlisted.join('; ')}`);+ for (const key of ['workspaceStorage', 'instanceUrl', 'httpClient', 'solutionUniqueName', 'languageCode', 'createRecovery', 'readConcurrency']) {+ assert.ok(passed.has(key), `the scan finds ${key} at a call site (a scan that finds nothing guards nothing)`);+ }+});++test('SDK options: the bundled SDK\'s createMakerSdk reads every option the skills give it', () => {+ const bundle = require(BUNDLE);+ const read = keysReadBy(bundle.createMakerSdk, everyFactoryOption(makeTempDir('sdk-options-')));+ const ignored = [...Object.keys(SKILL_FACTORY_OPTIONS), ...Object.keys(FACTORY_ADDED_OPTIONS)].filter((key) => !read.has(key));+ assert.deepEqual(ignored, [], `The bundled SDK no longer reads these options, so what each asked for is silently lost: ${ignored.map((k) => `${k} (${SKILL_FACTORY_OPTIONS[k] || FACTORY_ADDED_OPTIONS[k]})`).join('; ')}`);+});++test('SDK options: lib/maker-sdk.js gives the SDK its compiler and keeps the plugin\'s own `connectivity` from reaching it', () => {+ let given;+ const create = makerSdk.withVendoredCompiler((options) => { given = options; return {}; });+ create({ instanceUrl: 'https://contoso.crm.dynamics.com', connectivity: true, powerAppsServiceClient: NOOP_CLIENT });+ assert.equal(typeof given.typescript, 'function', 'the vendored compiler, loaded when a page is first compiled');+ assert.equal(given.powerAppsServiceClient, NOOP_CLIENT, 'a client the caller names wins');+ for (const key of PLUGIN_ONLY_OPTIONS) assert.equal(Object.prototype.hasOwnProperty.call(given, key), false, `${key} is the plugin's own`);+});++// The per-call options, on the stateful fake environment with another maker's work in it (a table with its generated default views, an app).+test('SDK options: fetchArtifact, enrichDefaultViews, queryRecords and findTables read the options the skills pass them, and publish:false defers the publish', async () => {+ const org = createLifecycleOrg();+ await seedForeignWork(org);+ const client = createAzHttpClient(org.origin, { getToken: () => 'sdk-options-token-0123456789', request: org.request, sleep: async () => {} });+ const sdk = makerSdk.createMakerSdk({ workspaceStorage: makerSdk.createNodeWorkspaceStorage(makeTempDir('sdk-options-call-')), instanceUrl: org.origin, httpClient: client });+ await sdk.initWorkspace();+ const WIDGET_COLUMNS = [{ name: 'fabrikam_name', width: 300, order: 0 }];+ const call = async (fn, options) => {+ const read = new Set();+ const recording = new Proxy(options, { get(target, key, receiver) { if (typeof key === 'string') read.add(key); return Reflect.get(target, key, receiver); } });+ const mark = org.mark();+ const value = await fn(recording);+ return { read, value, sent: org.since(mark) };+ };++ // lib/sdk-build.js, lib/genpage-sdk.js: a fetch that takes the environment's copy over the workspace's (workspace-projection-real-bundle.test.js pins the effect).+ const fetched = await call((o) => sdk.fetchArtifact('app', FOREIGN.app, o), { overwrite: true });+ assert.ok(fetched.read.has('overwrite'), 'fetchArtifact reads `overwrite`');++ // lib/sdk-build.js (views phase, with --publish): the default views are saved, their publish left to the build's one envelope.+ const deferred = await call((o) => sdk.enrichDefaultViews('fabrikam_widget', WIDGET_COLUMNS, o), { excludeViewIds: [], publish: false });+ assert.deepEqual([...deferred.read].sort(), ['excludeViewIds', 'publish'], 'enrichDefaultViews reads both options');+ assert.ok(deferred.value.updated.length > 0, `the table's generated default views were enriched: ${JSON.stringify(deferred.value)}`);+ assert.equal(deferred.sent.filter((r) => r.path === '/PublishXml').length, 0, 'publish:false sends no publish');+ assert.ok((deferred.value.pendingPublish || []).length > 0, 'and reports the publish it owes');+ // The same call without the option publishes at once: the option, not the call, is what deferred it.+ const published = await call((o) => sdk.enrichDefaultViews('fabrikam_widget', WIDGET_COLUMNS, o), {});+ assert.equal(published.sent.filter((r) => r.path === '/PublishXml').length, 1, 'without it, the enrichment publishes the table');++ // download-model-app.js, verify-model-app.js, …: the read options of queryRecords, and findTables' cap (lib/entity-provision.js).+ const queried = await call((o) => sdk.queryRecords('solution', o), { select: ['solutionid'], filter: "uniquename eq 'FabrikamCore'", top: 1 });+ assert.deepEqual([...queried.read].filter((k) => ['select', 'filter', 'top'].includes(k)).sort(), ['filter', 'select', 'top'], 'queryRecords reads select, filter and top');+ assert.equal(queried.value.length, 1, 'and the filter is applied');+ const paged = await call((o) => sdk.queryRecords('solution', o), { select: ['solutionid'], paginate: true });+ assert.ok(paged.read.has('paginate'), 'queryRecords reads paginate');+ const tables = await call((o) => sdk.findTables('fabrikam_widget', o), { top: 50 });+ assert.ok(tables.read.has('top'), 'findTables reads top');+});++// ====================================================================================================================================+// THE EFFECT OF EACH OPTION. That the bundle reads an option (above) catches a rename; it does not prove the option still does what the+// skills pass it for — an SDK that reads `readConcurrency` and then runs one request at a time, or reads `excludeViewIds` and then+// ignores it, passes every read check. Each option below is asserted by what it changes in the requests or the result, with and without+// it where the difference is the point. The options whose effect another test already owns are named in SKILL_FACTORY_OPTIONS.++// What lib/genpage-sdk.js passes it for: a page's file downloads overlap (four at a time). The page backend is made as the scripts make+// it, and its four file downloads are held at a gate that opens when all four are in flight at once — or after a second, so an SDK that+// sends them one by one is measured (as one in flight at a time) instead of hanging.+test('SDK option effects: the page backend\'s readConcurrency overlaps a page\'s file downloads (four in flight at once)', async () => {+ const { makeGenpageSdk } = require('../lib/genpage-sdk.js');+ const org = createLifecycleOrg();+ await seedForeignWork(org);+ const FILE_DOWNLOAD = /\/uxagentprojectfiles\([^)]*\)\/filecontent/;+ let inFlight = 0;+ let most = 0;+ let downloads = 0;+ const waiting = [];+ const gated = async (req) => {+ if (req.method !== 'GET' || !FILE_DOWNLOAD.test(decodeURIComponent(req.url))) return org.request(req);+ downloads += 1;+ inFlight += 1;+ most = Math.max(most, inFlight);+ if (inFlight >= 4) waiting.splice(0).forEach((open) => open());+ else await new Promise((open) => { waiting.push(open); setTimeout(open, 1000); });+ try { return await org.request(req); } finally { inFlight -= 1; }+ };+ const client = createAzHttpClient(org.origin, { getToken: () => 'sdk-options-token-0123456789', request: gated, sleep: async () => {} });+ const genpage = makeGenpageSdk(org.origin, { httpClient: client });+ try {+ const page = await genpage.read(FOREIGN.page);+ assert.equal(typeof page.source, 'string', 'the page was read');+ } finally {+ await genpage.dispose();+ }+ assert.equal(downloads, 4, 'the seeded page has four files');+ assert.equal(most, 4, `the four downloads were in flight at once (most at once: ${most})`);+});++// What lib/sdk-build.js passes it for: the default-view enrichment leaves the author's own views alone. The other maker's table has its+// generated pair; with the Active view excluded only the Inactive one is enriched — and without the option both are.+test('SDK option effects: enrichDefaultViews leaves an excluded view untouched, and enriches it when it is not excluded', async () => {+ const org = createLifecycleOrg();+ await seedForeignWork(org);+ const client = createAzHttpClient(org.origin, { getToken: () => 'sdk-options-token-0123456789', request: org.request, sleep: async () => {} });+ const sdk = makerSdk.createMakerSdk({ workspaceStorage: makerSdk.createNodeWorkspaceStorage(makeTempDir('sdk-options-exclude-')), instanceUrl: org.origin, httpClient: client });+ await sdk.initWorkspace();+ const idOf = (name) => org.find('savedqueries', (v) => v.returnedtypecode === 'fabrikam_widget' && v.name === name)[0].savedqueryid;+ const active = idOf('Active Widgets');+ const inactive = idOf('Inactive Widgets');+ const columns = [{ name: 'fabrikam_name', width: 300, order: 0 }];+ const patchedBy = async (options) => {+ const mark = org.mark();+ const record = await sdk.enrichDefaultViews('fabrikam_widget', columns, options);+ const patched = org.since(mark).filter((r) => r.method === 'PATCH' && /^\/savedqueries\(/.test(r.path)).map((r) => /\(([^)]+)\)/.exec(r.path)[1].toLowerCase());+ return { updated: record.updated.map((v) => String(v.id || v).toLowerCase()).sort(), patched: patched.sort() };+ };+ const excluded = await patchedBy({ excludeViewIds: [active], publish: false });+ assert.deepEqual(excluded.patched, [inactive.toLowerCase()], 'only the view that is not excluded is written');+ assert.deepEqual(excluded.updated, [inactive.toLowerCase()], 'and only it is reported enriched');+ const both = await patchedBy({ publish: false });+ assert.deepEqual(both.patched, [active, inactive].map((id) => id.toLowerCase()).sort(), 'without the option the pair is written');+});++// What lib/genpage-sdk.js and lib/sdk-build.js pass it for: fetching takes the environment's copy over the workspace's. A copy edited in+// the workspace is handed back as it is without the option, and replaced by the environment's with it.+test('SDK option effects: fetchArtifact with overwrite replaces an edited workspace copy; without it the edit is handed back', async () => {+ const org = createLifecycleOrg();+ await seedForeignWork(org);+ const client = createAzHttpClient(org.origin, { getToken: () => 'sdk-options-token-0123456789', request: org.request, sleep: async () => {} });+ const sdk = makerSdk.createMakerSdk({ workspaceStorage: makerSdk.createNodeWorkspaceStorage(makeTempDir('sdk-options-overwrite-')), instanceUrl: org.origin, httpClient: client });+ await sdk.initWorkspace();+ const server = await sdk.fetchArtifact('app', FOREIGN.app, { overwrite: true });+ await sdk.updateElement('app', FOREIGN.app, '/description', 'an edit only the workspace holds');+ const kept = await sdk.fetchArtifact('app', FOREIGN.app);+ assert.equal(kept.description, 'an edit only the workspace holds', 'without overwrite the edited copy is handed back');+ const replaced = await sdk.fetchArtifact('app', FOREIGN.app, { overwrite: true });+ assert.equal(replaced.description, server.description, 'with overwrite the environment\'s copy replaces it');+});++// The read options of queryRecords, on a transport that records each URL and answers the solution list in two pages: select, filter,+// orderBy (lib/sdk-build.js reads business process flows in order) and top reach the query; paginate follows the continuation link to+// the end, and a read without it stops at the first page. findTables' top caps what it answers (lib/entity-provision.js).+test('SDK option effects: queryRecords puts select, filter, orderBy and top in the query, paginate reads every page, and findTables honours top', async () => {+ const ORG = 'https://contoso.crm.dynamics.com';+ const NEXT = `${ORG}/api/data/v9.2/solutions?$select=solutionid&$skiptoken=page2`;+ const urls = [];+ const answer = (body) => ({ status: 200, headers: {}, body });+ const httpClient = {+ get: async (url) => {+ const u = decodeURIComponent(String(url));+ urls.push(u);+ if (/EntityDefinitions\(LogicalName='solution'\)/.test(u)) return answer({ EntitySetName: 'solutions', LogicalName: 'solution' });+ if (/skiptoken=page2/.test(u)) return answer({ value: [{ solutionid: 'b' }] });+ if (/\/solutions\?/.test(u)) return answer({ value: [{ solutionid: 'a' }], '@odata.nextLink': NEXT });+ if (/\/EntityDefinitions\?/.test(u)) {+ const table = (n) => ({ LogicalName: `contoso_item${n}`, SchemaName: `contoso_Item${n}`, EntitySetName: `contoso_item${n}s`, IsCustomEntity: true, DisplayName: { UserLocalizedLabel: { Label: `Item ${n}` } } });+ return answer({ value: [table(1), table(2), table(3)] });+ }+ return answer({});+ },+ post: async () => ({ status: 204, headers: {}, body: null }), patch: async () => ({ status: 204, headers: {}, body: null }),+ put: async () => ({ status: 204, headers: {}, body: null }), delete: async () => ({ status: 204, headers: {}, body: null }),+ };+ const bundle = require(BUNDLE);+ const sdk = bundle.createMakerSdk({ workspaceStorage: bundle.createNodeWorkspaceStorage(makeTempDir('sdk-options-query-')), instanceUrl: ORG, httpClient });+ await sdk.initWorkspace();++ urls.length = 0;+ await sdk.queryRecords('solution', { select: ['solutionid', 'uniquename'], filter: "uniquename eq 'ContosoCore'", orderBy: 'uniquename asc', top: 1 });+ const query = urls.find((u) => /\/solutions\?/.test(u));+ for (const part of ['$select=solutionid,uniquename', "$filter=uniquename eq 'ContosoCore'", '$orderby=uniquename asc', '$top=1']) assert.ok(query.includes(part), `${part} in ${query}`);++ urls.length = 0;+ assert.deepEqual((await sdk.queryRecords('solution', { select: ['solutionid'], paginate: true })).map((r) => r.solutionid), ['a', 'b'], 'paginate reads to the last page');+ assert.ok(urls.some((u) => /skiptoken=page2/.test(u)), 'through the continuation link');+ urls.length = 0;+ assert.deepEqual((await sdk.queryRecords('solution', { select: ['solutionid'] })).map((r) => r.solutionid), ['a'], 'without it, the first page only');+ assert.equal(urls.some((u) => /skiptoken=page2/.test(u)), false);++ assert.equal((await sdk.findTables('contoso_item', { top: 2 })).length, 2, 'findTables answers at most top tables');+ assert.equal((await sdk.findTables('contoso_item', { top: 50 })).length, 3, 'and all of them under a larger cap');+});+// The guard of the guard: the recorder does not report a key the factory never reads, and the scan finds options in each form a+// call site writes them — so neither check can pass because it sees nothing.+test('SDK options (meta): an option the SDK does not know is not reported as read, and the scan reads key, shorthand and spread forms', () => {+ const bundle = require(BUNDLE);+ const read = keysReadBy(bundle.createMakerSdk, { ...everyFactoryOption(makeTempDir('sdk-options-meta-')), contosoRenamedOption: true });+ assert.equal(read.has('contosoRenamedOption'), false);+ const src = "createMakerSdk({ workspaceStorage: storage(dir, { nested: 1 }), instanceUrl: 'https://x/{y}', httpClient, ...(lang ? { languageCode: lang } : {}), readConcurrency: 4 })";+ assert.deepEqual(objectKeys(src, src.indexOf('{')).keys, ['workspaceStorage', 'instanceUrl', 'httpClient', 'languageCode', 'readConcurrency']);+});diff --git a/plugins/model-apps/scripts/tests/sdk-publication-real-bundle.test.js b/plugins/model-apps/scripts/tests/sdk-publication-real-bundle.test.jsnew file mode 100644index 000000000..5e49a07ca--- /dev/null+++ b/plugins/model-apps/scripts/tests/sdk-publication-real-bundle.test.js@@ -0,0 +1,88 @@+'use strict';+// THE PUBLICATION RULES OF THE BUNDLED SDK THAT THE SKILLS ARE BUILT ON, pinned at its boundary.+//+// What a maker sees in a model-driven app is what was PUBLISHED, and each skill decides its own publishes from what the SDK publishes+// by itself and what it leaves to its caller. If a new SDK starts (or stops) publishing inside a push, a skill either publishes+// something the maker did not ask to go live — a page's half-made draft, an app's navigation before its pages exist — or leaves a change+// saved and never live. These are the rules the skills rely on, each asserted on the requests the SDK sends to the stateful fake+// environment (helpers/fake-lifecycle-org.js) through the plugin's own HTTP client:+//+// - a generative page push — create or update — publishes NOTHING. The page backend (lib/genpage-sdk.js) publishes the page itself+// after it has checked what was written (`publish`, `publishArtifact('genPage', id, { verify: true })`), and the build publishes the+// app after the page is in its navigation; a push that published would put an unchecked draft live.+// - publishArtifact('genPage') sends exactly one PublishXml, naming the page, and the published copy is then what was pushed.+// - an app update publishes nothing unless it asks to (`published: true`), and a create publishes unless it asks not to+// (`published: false`, sdk-opt-ins.test.js): the build creates every app published and publishes an existing app in its own envelope+// (lifecycle-trail-golden-real-bundle.test.js pins where).+//+// A failure names the request the SDK sent that it did not send before (or the one it no longer sends). It is an SDK behaviour change+// the skills must answer: adjust the skill's own publishes, and write the release-note line a maker can observe.+const test = require('node:test');+const assert = require('node:assert/strict');+const { makeTempDir } = require('./helpers/temp-dirs.js');+const { createLifecycleOrg } = require('./helpers/fake-lifecycle-org.js');+const { seedForeignWork, FOREIGN } = require('./helpers/lifecycle-harness.js');+const { createAzHttpClient } = require('../lib/sdk-http-client.js');+const { createMakerSdk, createNodeWorkspaceStorage } = require('../lib/maker-sdk.js');++const PAGE_ID = '33333333-0000-4000-8000-000000000001';+const SOURCE = "import * as React from 'react';\nexport default function WidgetPage() { return <div>Widgets</div>; }\n";+const EDITED = "import * as React from 'react';\nexport default function WidgetPage() { return <div>Widgets, edited</div>; }\n";++async function environment() {+ const org = createLifecycleOrg();+ await seedForeignWork(org);+ const client = createAzHttpClient(org.origin, { getToken: () => 'sdk-publication-token-0123456789', request: org.request, sleep: async () => {} });+ const sdk = createMakerSdk({ workspaceStorage: createNodeWorkspaceStorage(makeTempDir('sdk-publication-')), instanceUrl: org.origin, httpClient: client });+ await sdk.initWorkspace();+ // What a call sent: every request, and its publishes (what each PublishXml names).+ const sentBy = async (fn) => {+ const mark = org.mark();+ const value = await fn();+ const sent = org.since(mark);+ const publishes = sent.filter((r) => r.path === '/PublishXml').map((r) => String(r.body.ParameterXml));+ return { value, sent, publishes, writes: org.writeNames(mark) };+ };+ return { org, sdk, sentBy };+}++test('publication: a generative page push publishes nothing, create or update; publishArtifact publishes it once, and only then is it live', async () => {+ const { org, sdk, sentBy } = await environment();+ await sdk.createArtifact('genPage', { id: PAGE_ID, name: 'Widget Page', source: SOURCE, dataSources: ['fabrikam_widget'], newTurn: { prompt: 'A page of widgets', agentMessage: 'Done.' } });+ const created = await sentBy(() => sdk.pushArtifact('genPage', PAGE_ID));+ assert.equal(created.value && created.value.saved, true, `the page was created: ${JSON.stringify(created.value && created.value.error && created.value.error.message)}`);+ assert.ok(created.writes.some((w) => w.startsWith('POST uxagentprojects')), `the push wrote the page: ${created.writes.join(', ')}`);+ assert.deepEqual(created.publishes, [], 'a page create publishes nothing');+ assert.equal(org.pageServer.publishedPages.has(PAGE_ID), false, 'and the page is not live');++ const published = await sentBy(() => sdk.publishArtifact('genPage', PAGE_ID, { verify: true }));+ assert.equal(published.publishes.length, 1, 'publishArtifact sends one publish');+ assert.match(published.publishes[0], new RegExp(`<uxagentproject>\\{?${PAGE_ID}\\}?</uxagentproject>`, 'i'), 'naming the page');+ assert.deepEqual(published.writes.filter((w) => w !== 'POST PublishXml'), [], 'and writes nothing else');+ assert.equal(published.value.publish.kind, 'verified', `the published copy is what was pushed: ${JSON.stringify(published.value.publish)}`);++ await sdk.updateElement('genPage', PAGE_ID, '/source', EDITED);+ await sdk.addElement('genPage', PAGE_ID, '', { newTurn: { prompt: 'Say edited', agentMessage: 'Done.' } });+ const updated = await sentBy(() => sdk.pushArtifact('genPage', PAGE_ID));+ assert.equal(updated.value && updated.value.saved, true, 'the page was updated');+ assert.ok(updated.writes.length > 0, 'the update wrote the page');+ assert.deepEqual(updated.publishes, [], 'a page update publishes nothing: the live page is still the one published before');+});++test('publication: an app update publishes nothing unless it asks to; with `published: true` it publishes the app once', async () => {+ const { sdk, sentBy } = await environment();+ await sdk.fetchArtifact('app', FOREIGN.app, { overwrite: true });+ await sdk.updateElement('app', FOREIGN.app, '/description', 'Widgets, described.');+ const plain = await sentBy(() => sdk.pushArtifact('app', FOREIGN.app));+ assert.equal(plain.value && plain.value.saved, true, `the app was updated: ${JSON.stringify(plain.value && plain.value.error && plain.value.error.message)}`);+ assert.ok(plain.writes.some((w) => w.startsWith('PATCH appmodules')), `the push wrote the app: ${plain.writes.join(', ')}`);+ assert.deepEqual(plain.publishes, [], 'an app update publishes nothing by itself');++ await sdk.updateElement('app', FOREIGN.app, '/description', 'Widgets, described again.');+ // A fetched app carries no `published` member, so the request is added, as a caller adds any member a copy lacks.+ await sdk.addElement('app', FOREIGN.app, '', { published: true });+ const asked = await sentBy(() => sdk.pushArtifact('app', FOREIGN.app));+ assert.equal(asked.value && asked.value.saved, true, 'the app was updated again');+ assert.equal(asked.publishes.length, 1, `an update that asks to be published publishes once: ${asked.writes.join(', ')}`);+ assert.match(asked.publishes[0], new RegExp(`<appmodule>\\{?${FOREIGN.app}\\}?</appmodule>`, 'i'), 'naming the app');+});diff --git a/plugins/model-apps/scripts/tests/sdk-teardown.test.js b/plugins/model-apps/scripts/tests/sdk-teardown.test.jsindex eb8b93f1c..63ab50790 100644--- a/plugins/model-apps/scripts/tests/sdk-teardown.test.js+++ b/plugins/model-apps/scripts/tests/sdk-teardown.test.js@@ -1169,10 +1169,17 @@ test('the table read says whether the table was there before its delete: seen, lassert.deepStrictEqual(await resolveWith(async () => [{ logicalName: 'new_x', isCustom: true }]), [{ id: 'new_x', logical: 'new_x', seen: true }]);assert.deepStrictEqual(await resolveWith(async () => [{ logicalName: 'new_xy', isCustom: true }]), [{ id: 'new_x', logical: 'new_x', seen: false }]);assert.deepStrictEqual(await resolveWith(async () => []), [{ id: 'new_x', logical: 'new_x', seen: false }]);- // A read that failed, or a list cut at the 50 matches it asks for, does not say the table is absent.- assert.deepStrictEqual(await resolveWith(async () => { throw new Error('HTTP 503'); }), [{ id: 'new_x', logical: 'new_x' }]);+ // A list cut at the 50 matches it asks for does not say the table is absent.const fifty = Array.from({ length: 50 }, (_, i) => ({ logicalName: `new_x${i}`, isCustom: true }));assert.deepStrictEqual(await resolveWith(async () => fifty), [{ id: 'new_x', logical: 'new_x' }]);+ // A read that failed says nothing about the table, so nothing is deleted on it: the step fails closed, with the reason and the error kept.+ const failed = new Error('HTTP 503 from https://contoso.crm.dynamics.com/api/data/v9.0/EntityDefinitions?$skiptoken=2: Service Unavailable');+ await assert.rejects(resolveWith(async () => { throw failed; }), (err) => {+ assert.strictEqual(err.failClosed, true);+ assert.strictEqual(err.cause, failed);+ assert.match(err.message, /^table 'new_x' was not deleted: the environment's tables could not be read, so whether it is there, and whether it is a system table, is unknown \(HTTP 503 from /);+ return true;+ });});test('a default-view reset that finds no default view says not found; one that finds views, or fails after finding them, reads as before', async () => {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 8b597eeab..be0959511 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@@ -2266,13 +2266,26 @@ test('A/B with the previous release: the table request and every column body a s...columnPosts(run).map((r) => [r.body.SchemaName, JSON.stringify(r.body)]),...batchColumns(run).map((body) => [body.SchemaName, JSON.stringify(body)]),]);+ // The one field the bundled SDK adds since the previous release: every Date and Time column it creates states its behaviour,+ // `UserLocal` unless asked otherwise. The previous release sent none, and the platform stores `UserLocal` for a column created by+ // its own request or in a change set (only a column inlined in the table's create was stored with none, which then refused every+ // later column of the table) — so a column ends up as it did, Format DateOnly included. Taken out of this build's bodies, after+ // checking it is exactly that, the rest of each body is compared byte for byte.+ const DATE_TIME_BEHAVIOR = JSON.stringify({ Value: 'UserLocal' });+ const withoutStatedBehavior = (bodies) => new Map([...bodies].map(([name, text]) => {+ const body = JSON.parse(text);+ if (body.AttributeType !== 'DateTime') return [name, text];+ assert.strictEqual(JSON.stringify(body.DateTimeBehavior), DATE_TIME_BEHAVIOR, `${name}: a Date and Time column states the behaviour the platform gave it before`);+ delete body.DateTimeBehavior;+ return [name, JSON.stringify(body)];+ }));for (const [what, spec] of specs) {for (const [model, dataverse] of [['honouring', HONOURING], ['overriding', OVERRIDING]]) {const old = await releasedRun(spec, dataverse);const now = await provisionOver(clone(spec), { dataverse });const label = `${what}, ${model}`;assert.deepStrictEqual(tablePosts(now).map((r) => JSON.stringify(r.body)), tablePosts(old).map((r) => JSON.stringify(r.body)), `${label}: the table requests are the same bytes`);- assert.deepStrictEqual([...bodiesBySchemaName(now)].sort(), [...bodiesBySchemaName(old)].sort(), `${label}: every column is the same body, whether the released code posted it by itself or this build put it in the change set`);+ assert.deepStrictEqual([...withoutStatedBehavior(bodiesBySchemaName(now))].sort(), [...bodiesBySchemaName(old)].sort(), `${label}: every column is the same body, whether the released code posted it by itself or this build put it in the change set`);assert.deepStrictEqual(posts(now).filter((r) => r.path === '/CreateCustomerRelationships').map((r) => JSON.stringify(r.body)), posts(old).filter((r) => r.path === '/CreateCustomerRelationships').map((r) => JSON.stringify(r.body)), `${label}: the Customer actions`);// `lookupLabels` is the one field of the result that is new since the previous release: the label each lookup column carries once the data model is done, which a later phase repairs forms from.const { lookupLabels, ...nowResult } = now.result;@@ -2284,6 +2297,7 @@ test('A/B with the previous release: the table request and every column body a sassert.strictEqual(now.dv.tables.get(name).primaryLength, table.primaryLength, `${label}: ${name}'s name column ends up the length the released code gave it`);assert.deepStrictEqual([...now.dv.tables.get(name).columns.keys()].sort(), [...table.columns.keys()].sort(), `${label}: ${name} has the same columns`);}+ assert.ok([...bodiesBySchemaName(old).values()].every((text) => JSON.parse(text).DateTimeBehavior === undefined), `${label}: the previous release stated no behaviour`);if (!spec.entities[0].columns.length) assert.deepStrictEqual(now.dv.log, old.dv.log, `${label}: for a table with no columns, every request is the released code's`);}}diff --git a/plugins/model-apps/scripts/tests/unreadable-table-list-callers.test.js b/plugins/model-apps/scripts/tests/unreadable-table-list-callers.test.jsindex f0f5c9359..02e52340a 100644--- a/plugins/model-apps/scripts/tests/unreadable-table-list-callers.test.js+++ b/plugins/model-apps/scripts/tests/unreadable-table-list-callers.test.js@@ -56,14 +56,16 @@ const definition = ({ logicalName, custom = true }) => ({});// `tables` are the tables the environment holds; `list` answers the table list instead of them (a raw answer); `narrow` answers the one-table definition read instead of the truth;-// `refuseDelete` answers a table delete instead of the platform's 204. `org.requests` is every request, in order, as `METHOD /path` below the API root.-function createOrg({ tables = [], list, narrow, deleteAnswer } = {}) {- const org = { tables: new Map(tables.map((table) => [table.logicalName, table])), list, narrow, deleteAnswer, requests: [], unexpected: [] };+// `refuseDelete` answers a table delete instead of the platform's 204; `nextPage` answers the read of a continuation link of the table list (`…$skiptoken=…`).+// `org.requests` is every request, in order, as `METHOD /path` below the API root.+function createOrg({ tables = [], list, narrow, deleteAnswer, nextPage } = {}) {+ const org = { tables: new Map(tables.map((table) => [table.logicalName, table])), list, narrow, deleteAnswer, nextPage, requests: [], unexpected: [] };org.request = async ({ url, method }) => {const parsed = new URL(url);const apiPath = decodeURIComponent(parsed.pathname + parsed.search).replace(/^\/api\/data\/v9\.\d/, '');org.requests.push(`${method} ${apiPath}`);const one = /^\/EntityDefinitions\(LogicalName='([^']+)'\)/.exec(apiPath);+ if (method === 'GET' && /^\/EntityDefinitions\?.*\$skiptoken=/.test(apiPath) && org.nextPage) return org.nextPage;if (method === 'GET' && /^\/EntityDefinitions\?/.test(apiPath)) return org.list || json(200, { value: [...org.tables.values()].map(definition) });if (method === 'GET' && one && /\/Attributes/.test(apiPath)) return json(200, { value: [] });if (method === 'GET' && one) {@@ -110,7 +112,7 @@ test('TEARDOWN: a custom table is deleted — one read of the table list, then tassert.deepStrictEqual(result, unguarded);});-test('TEARDOWN: a system table is left alone, and `{ "value": [] }` and a refused read keep the handling they always had — the delete goes on', async (t) => {+test('TEARDOWN: a system table is left alone, `{ "value": [] }` goes on to the delete, and a refused read fails the step with nothing deleted', async (t) => {const system = createOrg({ tables: [{ logicalName: 'new_widget', custom: false }] });const left = await tearDown(t, system);assert.deepStrictEqual([left.ok, left.deleted, system.requests], [true, {}, [TABLE_LIST]]);@@ -119,12 +121,42 @@ test('TEARDOWN: a system table is left alone, and `{ "value": [] }` and a refuseconst empty = createOrg({ list: json(200, { value: [] }) });const goneAlready = await tearDown(t, empty);assert.deepStrictEqual([goneAlready.ok, empty.requests], [true, [TABLE_LIST, DELETE_TABLE('new_widget')]]);- // A refusal of the read is a failure of the read — as before, the step goes on to the delete.+ // A refusal of the read says nothing about the table — not that it is gone, not that it is not a system table — so the step fails+ // with the reason and no delete is sent; a re-run once the read answers finishes it.const refused = createOrg({ tables: [WIDGET], list: json(403, { error: { message: 'The user is not a member of the organization.' } }) });const afterRefusal = await tearDown(t, refused);- assert.deepStrictEqual([afterRefusal.ok, refused.requests], [true, [TABLE_LIST, DELETE_TABLE('new_widget')]]);+ assert.deepStrictEqual([afterRefusal.ok, afterRefusal.deleted, refused.writes()], [false, {}, []]);+ assert.match(afterRefusal.errors[0].message, /^table 'new_widget' was not deleted: the environment's tables could not be read, so whether it is there, and whether it is a system table, is unknown \(HTTP 403 .*The user is not a member of the organization\./);+ assert.ok(refused.tables.has('new_widget'));});+// The bundled SDK refuses a table list that says it holds more rows than it gave (`@Microsoft.Dynamics.CRM.morerecords` with no link to+// them), and one whose next page could not be read: neither is the whole list, so the table the step is about — here a SYSTEM table,+// listed on the page that was read — is unknown. The step fails closed: no DELETE is sent from half an answer.+const SYSTEM_WIDGET = { ...definition({ logicalName: 'new_widget', custom: false }) };+const INCOMPLETE = {+ 'a page that says more rows exist and gives no link to them': { list: json(200, { value: [SYSTEM_WIDGET], '@Microsoft.Dynamics.CRM.morerecords': true }), reason: /more rows exist/ },+ 'a page whose next page answers 503': {+ list: json(200, { value: [SYSTEM_WIDGET], '@odata.nextLink': `${ORIGIN}/api/data/v9.0/EntityDefinitions?$select=LogicalName&$skiptoken=2` }),+ nextPage: json(503, { error: { code: '0x80000001', message: 'Service Unavailable' } }),+ reason: /HTTP 503/,+ },+};+for (const [shape, { list, nextPage, reason }] of Object.entries(INCOMPLETE)) {+ test(`TEARDOWN: a table list that is ${shape} fails the step — no DELETE is sent from half an answer`, async (t) => {+ const org = createOrg({ tables: [{ logicalName: 'new_widget', custom: false }], list, nextPage });+ const result = await tearDown(t, org);+ assert.deepStrictEqual([result.ok, result.deleted, org.writes()], [false, {}, []]);+ assert.strictEqual(result.errors[0].step, 'table new_widget');+ assert.match(result.errors[0].message, /^table 'new_widget' was not deleted: the environment's tables could not be read, so whether it is there, and whether it is a system table, is unknown \(/);+ assert.match(result.errors[0].message, reason);+ // The same list read whole lists the table as a system table, which the step leaves alone.+ const whole = createOrg({ tables: [{ logicalName: 'new_widget', custom: false }], list: json(200, { value: [SYSTEM_WIDGET] }) });+ const left = await tearDown(t, whole);+ assert.deepStrictEqual([left.ok, whole.writes()], [true, []]);+ });+}+for (const [shape, answer] of Object.entries(NOT_A_LIST)) {test(`TEARDOWN: a table list that is ${shape} is a failed step — nothing is deleted, and nothing is reported deleted`, async (t) => {const org = createOrg({ tables: [WIDGET], list: answer });diff --git a/plugins/model-apps/scripts/tests/workspace-projection-real-bundle.test.js b/plugins/model-apps/scripts/tests/workspace-projection-real-bundle.test.jsindex 98787fee9..2926efce2 100644--- a/plugins/model-apps/scripts/tests/workspace-projection-real-bundle.test.js+++ b/plugins/model-apps/scripts/tests/workspace-projection-real-bundle.test.js@@ -168,3 +168,29 @@ test('the runner adds no remedy to an SDK error it has none for', async () => {});}});++// REAL BUNDLE: two refusals the bundled SDK raises before anything is written, each ending with an SDK call an operator cannot make. The halt+// keeps the SDK's words and code, adds the maker's step, and is never run again (a run again meets the same refusal).+test('REAL BUNDLE: a Date and Time column with no behaviour, and a command row whose location or type changed, halt with the maker\u2019s step and are never run again', async () => {+ const bundle = require(BUNDLE);+ const { isTransientHalt } = require('../build-model-app.js');+ const runner = makeRunner({ emit: () => {}, total: 1 });+ const dateTime = new bundle.DateTimeBehaviorMissingError('contoso_project', ['contoso_due']);+ assert.strictEqual(dateTime.code, 'DATETIME_BEHAVIOR_MISSING');+ await assert.rejects(() => runner.run('data-model', 'column contoso_project.contoso_notes', async () => { throw dateTime; }), (err) => {+ assert.ok(err instanceof BuildHalt);+ assert.strictEqual(err.code, 'DATETIME_BEHAVIOR_MISSING');+ assert.ok(err.message.includes(dateTime.message), 'the SDK names the table and its columns');+ assert.match(err.message, /nothing was created by the refused request\. .*Set the behaviour of each to User local .* in the column's advanced options in Power Apps, then run the build again\.$/);+ assert.strictEqual(isTransientHalt(err), false, 'never run again');+ return true;+ });+ const command = new bundle.SdkError(bundle.COMMAND_IMMUTABLE_COLUMN_CHANGED_CODE, "Refusing to push command 'contoso_project': app action 'x' changed its location.");+ assert.strictEqual(command.code, 'COMMAND_IMMUTABLE_COLUMN_CHANGED');+ await assert.rejects(() => runner.run('commands', 'command bar for contoso_project', async () => { throw command; }), (err) => {+ assert.strictEqual(err.code, 'COMMAND_IMMUTABLE_COLUMN_CHANGED');+ assert.match(err.message, /^commands failed: Refusing to push command .* — nothing was written\. .*Remove the command in Power Apps, then run the build again to create it as the spec says\.$/);+ assert.strictEqual(isTransientHalt(err), false, 'never run again');+ return true;+ });+});diff --git a/plugins/model-apps/scripts/tests/workspace-upgrade-entry-real-bundle.test.js b/plugins/model-apps/scripts/tests/workspace-upgrade-entry-real-bundle.test.jsnew file mode 100644index 000000000..681ec612b--- /dev/null+++ b/plugins/model-apps/scripts/tests/workspace-upgrade-entry-real-bundle.test.js@@ -0,0 +1,67 @@+'use strict';+// REAL BUNDLES: a `.maker-workspace` the PREVIOUS release wrote, and a download or a teardown as the FIRST thing this release does+// with it — no build of this release has re-read a copy first. Each path starts from the state the previous release's bundle left+// (helpers/workspace-upgrade.js) and is compared with the same step on a workspace this release's bundle wrote. See+// workspace-upgrade-real-bundle.test.js for why every copy is "old" after the upgrade, and for the rebuilds.+// DOWNLOAD reads the environment through a throwaway workspace and writes the spec and its baseline into the app folder that holds+// the old workspace: it writes nothing to the environment and gives the spec a current workspace gives+// TEARDOWN fences the old workspace while it deletes: it deletes what it deletes after a current build, and leaves the environment+// as it was before the build (but the build's publisher)+const test = require('node:test');+const assert = require('node:assert/strict');+const fs = require('node:fs');+const path = require('node:path');+const { diffContents } = require('./helpers/lifecycle-harness.js');+const { skipWithoutPrevious } = require('./helpers/previous-bundle.js');+const { startFrom, stage, withoutIds, appUniqueName, kitchenSinkSpec } = require('./helpers/workspace-upgrade.js');++const SKIP = skipWithoutPrevious();++let downloadP;+const downloadPaths = () => downloadP || (downloadP = (async () => {+ const run = async (which) => {+ const s = await startFrom(which);+ // Into the app folder itself, beside the old workspace: the download's baseline goes into that workspace.+ s.download = await s.next.measure(() => s.next.download(appUniqueName(kitchenSinkSpec()), s.next.appDir));+ s.afterDownload = s.org.inventory();+ return s;+ };+ return { upgrade: await run('previous'), control: await run('current') };+})());++test('upgrade: a first download beside the old workspace writes nothing to the environment and gives the spec a current workspace gives', { skip: SKIP }, async () => {+ const { upgrade, control } = await downloadPaths();+ stage(upgrade.build, 'previous release\'s build');+ const download = stage(upgrade.download, 'download').value;+ const current = stage(control.download, 'control download').value;+ assert.equal(download.emitted.ok, true, download.stderr);+ assert.deepEqual(upgrade.download.writes, {}, 'a download writes nothing');+ assert.deepEqual(upgrade.afterDownload, upgrade.afterBuild);+ assert.equal(withoutIds(download.spec), withoutIds(current.spec), 'the same spec, but for the ids the fake mints at random');+ assert.deepEqual(download.stderr.split('\n').sort(), current.stderr.split('\n').sort(), 'and the same warnings');+ assert.ok(fs.existsSync(path.join(upgrade.next.workspaceDir, 'last-applied.json')), 'its baseline is written into the old workspace');+});++let teardownP;+const teardownPaths = () => teardownP || (teardownP = (async () => {+ const run = async (which) => {+ const s = await startFrom(which);+ s.teardown = await s.next.measure(() => s.next.teardown(kitchenSinkSpec()));+ s.afterTeardown = s.org.inventory();+ s.afterTeardownContents = s.org.contents();+ return s;+ };+ return { upgrade: await run('previous'), control: await run('current') };+})());++test('upgrade: a first teardown over the old workspace deletes what it deletes after a current build, and leaves the environment as it was', { skip: SKIP }, async () => {+ const { upgrade, control } = await teardownPaths();+ stage(upgrade.build, 'previous release\'s build');+ const { value: { result } } = stage(upgrade.teardown, 'teardown');+ assert.equal(result.ok, true, JSON.stringify(result));+ assert.deepEqual(upgrade.teardown.writes, stage(control.teardown, 'control teardown').writes, 'the same deletes as after a current build');+ const builtPublisher = upgrade.afterBuild.rows.publishers.filter((p) => !upgrade.seed.rows.publishers.includes(p));+ const now = upgrade.afterTeardown;+ assert.deepEqual({ ...now, rows: { ...now.rows, publishers: now.rows.publishers.filter((p) => !builtPublisher.includes(p)) } }, upgrade.seed, 'every row but the build\'s publisher is as it was before the build');+ assert.deepEqual(diffContents(upgrade.seedContents, upgrade.afterTeardownContents, { added: false }), [], 'and holds exactly what it held');+});diff --git a/plugins/model-apps/scripts/tests/workspace-upgrade-real-bundle.test.js b/plugins/model-apps/scripts/tests/workspace-upgrade-real-bundle.test.jsnew file mode 100644index 000000000..ff9aec402--- /dev/null+++ b/plugins/model-apps/scripts/tests/workspace-upgrade-real-bundle.test.js@@ -0,0 +1,111 @@+'use strict';+// REAL BUNDLES: a `.maker-workspace` the PREVIOUS release wrote, rebuilt by this one — unchanged, and edited.+//+// The SDK stamps every workspace copy with the version of the parsers that projected it and refuses to push a copy stamped with+// another version (ARTIFACT_PROJECTION_STALE, nothing written): after a parser change an untouched part of an old copy can read as+// edited. The bundled SDK raised that version (a Quick Find marker below a view's top-level filter, and a multi-value condition, are+// now kept verbatim), so EVERY copy a maker's workspace holds — the app, its forms, views, charts, dashboard and command bars — is+// "old" the first time this release runs in it. workspace-projection-real-bundle.test.js pins the mechanism on one stamped app copy;+// this file and workspace-upgrade-entry-real-bundle.test.js pin the upgrade a maker makes, end to end, over the stateful fake+// (helpers/lifecycle-harness.js, helpers/workspace-upgrade.js). Each path starts from the state the previous release's bundle left+// — never from one this release has touched — and its first step with this release is compared with the same step on a workspace+// this release's bundle wrote: every step succeeds, sends the same writes, and leaves the same features.+// UNCHANGED REBUILD the first build of this release changes nothing, and re-reads every copy it edits+// EDITED REBUILD the first build of this release applies a maker's edits — and keeps, by content, a view filter the typed view+// model does not hold, added in Maker and read into the old copy by the previous release+// The previous release's bundle comes from helpers/previous-bundle.js: CI fetches it; elsewhere it is read from git history.+const test = require('node:test');+const assert = require('node:assert/strict');+const { deployedFeatures } = require('./helpers/lifecycle-harness.js');+const { skipWithoutPrevious } = require('./helpers/previous-bundle.js');+const { projections, versions, editedSpec, residualView, RESIDUAL_FILTER, startFrom, stage, kitchenSinkSpec } = require('./helpers/workspace-upgrade.js');++const SKIP = skipWithoutPrevious();+const sorted = (list) => [...list].sort();++// --- the unchanged rebuild ---------------------------------------------------------------------------------------------------++let rebuildP;+const rebuildPaths = () => rebuildP || (rebuildP = (async () => {+ const run = async (which) => {+ const s = await startFrom(which);+ s.rebuild = await s.next.measure(() => s.next.build(kitchenSinkSpec()));+ s.afterRebuild = s.org.inventory();+ s.rebuildProjections = projections(s.next.workspaceDir);+ return s;+ };+ return { upgrade: await run('previous'), control: await run('current') };+})());++test('upgrade: the previous release builds the app and leaves copies of every kind at its own, older projection', { skip: SKIP }, async () => {+ const { upgrade, control } = await rebuildPaths();+ assert.equal(stage(upgrade.build, 'previous release\'s build').value.result.ok, true, JSON.stringify(upgrade.build.value.result.errors));+ for (const kind of ['apps', 'forms', 'views', 'charts', 'dashboards', 'commands']) {+ assert.ok(upgrade.firstProjections[kind], `the previous build kept ${kind} copies (${Object.keys(upgrade.firstProjections)})`);+ }+ const [old] = versions(upgrade.firstProjections);+ const [current] = versions(control.firstProjections);+ assert.deepEqual(versions(upgrade.firstProjections), [old], 'one projection version in the old workspace');+ assert.ok(old < current, `this bundle projects at a newer version (${current}) than the previous one (${old}): the workspace is an old one`);+ // The two builds leave the same environment, so every later step starts from the same place on both paths.+ assert.deepEqual(deployedFeatures(upgrade.org), deployedFeatures(control.org));+});++test('upgrade: an unchanged first rebuild over the old workspace succeeds and sends exactly what it sends over a current one', { skip: SKIP }, async () => {+ const { upgrade, control } = await rebuildPaths();+ const { value: { result, warnings } } = stage(upgrade.rebuild, 'rebuild');+ assert.equal(result.ok, true, JSON.stringify(result.errors));+ // The build reconciles views side by side, so its warnings are compared in any order.+ assert.deepEqual(sorted(warnings), sorted(stage(control.rebuild, 'control rebuild').value.warnings), 'no warning the current workspace does not give');+ assert.deepEqual(upgrade.afterRebuild, upgrade.afterBuild, 'nothing created or deleted');+ assert.deepEqual(upgrade.rebuild.writes, control.rebuild.writes, 'the same writes as over a current workspace');+ // Every copy the rebuild edits is re-read and stamped current, so no later push meets the refusal. A command bar is never+ // re-pushed by a build (sdk-build.js: an existing bar is reused), so its old copy is left as it was — and is never pushed.+ const [current] = versions(control.firstProjections);+ for (const kind of ['apps', 'forms', 'views', 'charts', 'dashboards']) {+ assert.deepEqual([...new Set(upgrade.rebuildProjections[kind])], [current], `the ${kind} copies are re-read at the current projection`);+ }+});++// --- the edited rebuild, first ------------------------------------------------------------------------------------------------++let editP;+const editPaths = () => editP || (editP = (async () => {+ const run = async (which) => {+ const s = await startFrom(which, { residualFilter: true });+ s.heldBefore = residualView(s.org).fetchxml;+ s.edit = await s.next.measure(() => s.next.build(editedSpec()));+ s.edited = deployedFeatures(s.org);+ s.heldAfter = residualView(s.org).fetchxml;+ s.verify = await s.next.measure(() => s.next.verify(editedSpec()));+ return s;+ };+ return { upgrade: await run('previous'), control: await run('current') };+})());++test('upgrade: an edited first rebuild over the old workspace applies the edits as over a current one, and verify passes', { skip: SKIP }, async () => {+ const { upgrade, control } = await editPaths();+ stage(upgrade.reread, 'previous release\'s rebuild after the maker\'s edit');+ const { value: { result, warnings } } = stage(upgrade.edit, 'edited rebuild');+ assert.equal(result.ok, true, JSON.stringify(result.errors));+ assert.deepEqual(sorted(warnings), sorted(stage(control.edit, 'control edited rebuild').value.warnings), 'no warning the current workspace does not give');+ assert.deepEqual(upgrade.edit.writes, control.edit.writes, 'the same writes as over a current workspace');+ assert.deepEqual(upgrade.edited, control.edited, 'the environment ends with the same features');+ const verify = stage(upgrade.verify, 'verify').value;+ assert.equal(verify.ok, true, JSON.stringify(verify));+ // The checks run side by side, so they are compared as a set.+ const checks = (report) => report.checks.map((c) => JSON.stringify(c)).sort();+ const current = stage(control.verify, 'control verify').value;+ assert.deepEqual({ ...verify, checks: checks(verify) }, { ...current, checks: checks(current) }, 'verify reports what it reports over a current workspace');+});++test('upgrade: a view filter the typed model does not hold — a nested Quick Find marker, a multi-value condition — survives the edit by content', { skip: SKIP }, async () => {+ const { upgrade, control } = await editPaths();+ stage(upgrade.edit, 'edited rebuild');+ assert.ok(upgrade.heldBefore.includes(RESIDUAL_FILTER), 'the previous release\'s rebuild left the maker\'s filter in place');+ // The edit reached the view: its new column is saved.+ assert.match(upgrade.heldAfter, /<attribute name="contoso_done" ?\/>/, 'the view\'s column edit is saved');+ // And the filter is the maker's, byte for byte, where the maker put it: inside the view's top-level filter.+ assert.ok(upgrade.heldAfter.includes(`<filter type="and">${RESIDUAL_FILTER}`), `the nested Quick Find filter and its multi-value condition are kept verbatim: ${upgrade.heldAfter}`);+ assert.equal(upgrade.heldAfter, control.heldAfter, 'exactly as over a current workspace');+});diff --git a/plugins/model-apps/scripts/vendor/PROVENANCE.json b/plugins/model-apps/scripts/vendor/PROVENANCE.jsonindex 8e3124815..a8c449117 100644--- a/plugins/model-apps/scripts/vendor/PROVENANCE.json+++ b/plugins/model-apps/scripts/vendor/PROVENANCE.json@@ -1,13 +1,13 @@{- "commit": "a3443479b88ec538be2e74293fa92230c4ef1aab",+ "commit": "59ae2d72e2a88da53f34430608d7afe3ee05503a","dirtySdkPackage": 0,- "libBuiltAt": "2026-10-20T20:18:04.982Z",- "newestSrcAt": "2026-10-20T19:21:12.668Z",+ "libBuiltAt": "2026-10-28T21:30:20.191Z",+ "newestSrcAt": "2026-10-28T21:07:03.627Z","libIsStale": false,"nostub": false,"esbuildVersion": "0.28.1","nodeVersion": "v24.21.0",- "builtAt": "2026-10-20T20:20:30.581Z",- "bundleSha256": "eebd70a2a7f6e12e45d18744640fd803479a738bc936b8e0dce1a9f97a0a4f8c",- "bundleBytes": 1029451+ "builtAt": "2026-10-28T21:31:21.536Z",+ "bundleSha256": "a7f59f9683114f30ed8252c1e84824bc81e282dc3b7fa2653153be2398125f3f",+ "bundleBytes": 1471508}diff --git a/plugins/model-apps/scripts/vendor/cds-maker-sdk.cjs b/plugins/model-apps/scripts/vendor/cds-maker-sdk.cjsindex 6f798fd8d..4669c311a 100644--- a/plugins/model-apps/scripts/vendor/cds-maker-sdk.cjs+++ b/plugins/model-apps/scripts/vendor/cds-maker-sdk.cjs@@ -25,61 +25,78 @@}globalThis.document=globalThis.document||globalThis.window.document;})();-var kU=Object.create;var Nc=Object.defineProperty;var LU=Object.getOwnPropertyDescriptor;var $U=Object.getOwnPropertyNames;var xU=Object.getPrototypeOf,FU=Object.prototype.hasOwnProperty;var L=(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)Nc(e,r,{get:t[r],enumerable:!0})},Sc=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of $U(t))!FU.call(e,i)&&i!==r&&Nc(e,i,{get:()=>t[i],enumerable:!(n=LU(t,i))||n.enumerable});return e},Yi=(e,t,r)=>(Sc(e,t,"default"),r&&Sc(r,t,"default")),Ae=(e,t,r)=>(r=e!=null?kU(xU(e)):{},Sc(t||!e||!e.__esModule?Nc(r,"default",{value:e,enumerable:!0}):r,e)),Br=e=>Sc(Nc({},"__esModule",{value:!0}),e);var Qi=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 ow;(function(e){e.None="None",e.UserOwned="UserOwned",e.TeamOwned="TeamOwned",e.BusinessOwned="BusinessOwned",e.OrganizationOwned="OrganizationOwned",e.BusinessParented="BusinessParented",e.Filtered="Filtered"})(ow||(T.OwnershipTypes=ow={}));var aw;(function(e){e.User="Microsoft.Dynamics.CRM.systemuser",e.Team="Microsoft.Dynamics.CRM.team"})(aw||(T.PrincipalType=aw={}));var sw;(function(e){e[e.DoNotDisplayInActivityMenus=0]="DoNotDisplayInActivityMenus",e[e.DisplayInActivityMenus=1]="DisplayInActivityMenus"})(sw||(T.ActivityTypeMask=sw={}));var lw;(function(e){e.Activity="Activity",e.Virtual="Virtual",e.Standard="Standard",e.Elastic="Elastic"})(lw||(T.TableTypes=lw={}));var uw;(function(e){e.Standard="Standard",e.Virtual="Virtual",e.Elastic="Elastic"})(uw||(T.TableTypeCode=uw={}));var cw;(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"})(cw||(T.FormType=cw={}));var dw;(function(e){e[e.ClassicForm=0]="ClassicForm",e[e.AirForm=1]="AirForm",e[e.ConvertedICForm=2]="ConvertedICForm"})(dw||(T.FormPresentation=dw={}));var fw;(function(e){e[e.Inactive=0]="Inactive",e[e.Active=1]="Active"})(fw||(T.ActivationState=fw={}));var pw;(function(e){e[e.String=0]="String",e[e.Number=1]="Number",e[e.Picklist=2]="Picklist"})(pw||(T.AttributeType=pw={}));var mw;(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"})(mw||(T.ViewType=mw={}));var hw;(function(e){e[e.ASPChart=0]="ASPChart",e[e.PowerBI=1]="PowerBI"})(hw||(T.ChartsType=hw={}));var gw;(function(e){e[e.DataAndInteractionCentric=0]="DataAndInteractionCentric",e[e.InteractionCentric=1]="InteractionCentric"})(gw||(T.ChartType=gw={}));var yw;(function(e){e[e.Published=0]="Published",e[e.Unpublished=1]="Unpublished",e[e.Deleted=2]="Deleted",e[e.DeletedUnpublished=3]="DeletedUnpublished"})(yw||(T.ComponentState=yw={}));var bw;(function(e){e[e.None=1]="None",e[e.Sandbox=2]="Sandbox",e[e.External=3]="External"})(bw||(T.PluginIsolationMode=bw={}));var vw;(function(e){e[e.BasicAuth=0]="BasicAuth"})(vw||(T.AuthType=vw={}));var ww;(function(e){e[e.Database=0]="Database",e[e.Disk=1]="Disk",e[e.Normal=2]="Normal",e[e.AzureWebApp=3]="AzureWebApp"})(ww||(T.PluginSourceType=ww={}));var Cw;(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"})(Cw||(T.AttributeTypeCode=Cw={}));var Ew;(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"})(Ew||(T.AttributeTypeName=Ew={}));var Aw;(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"})(Aw||(T.AttributeFormatCode=Aw={}));var Sw;(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"})(Sw||(T.AttributeFormatName=Sw={}));var Nw;(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"})(Nw||(T.AttributeTypeCodeNum=Nw={}));var _w;(function(e){e.Picklist="Picklist",e.State="State",e.Status="Status",e.Boolean="Boolean"})(_w||(T.OptionSetType=_w={}));var Tw;(function(e){e[e.Draft=0]="Draft",e[e.Activated=1]="Activated"})(Tw||(T.StateCode=Tw={}));var Dw;(function(e){e[e.Draft=1]="Draft",e[e.Activated=2]="Activated"})(Dw||(T.StatusCode=Dw={}));var Iw;(function(e){e[e.Enabled=0]="Enabled",e[e.Disabled=1]="Disabled"})(Iw||(T.StateCodeEnabledDisabled=Iw={}));var Ow;(function(e){e[e.Enabled=1]="Enabled",e[e.Disabled=2]="Disabled"})(Ow||(T.StatusCodeEnabledDisabled=Ow={}));var Pw;(function(e){e[e.Definition=1]="Definition",e[e.Activation=2]="Activation",e[e.Template=3]="Template"})(Pw||(T.WorkflowTypeCode=Pw={}));var Rw;(function(e){e[e.User=1]="User",e[e.BusinessUnit=2]="BusinessUnit",e[e.ParentChildBusinessUnit=3]="ParentChildBusinessUnit",e[e.Organization=4]="Organization"})(Rw||(T.WorkflowScope=Rw={}));var kw;(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"})(kw||(T.WorkflowCategory=kw={}));var Lw;(function(e){e[e.None=-1]="None",e[e.BusinessFlow=0]="BusinessFlow",e[e.TaskFlow=1]="TaskFlow"})(Lw||(T.BusinessProcessType=Lw={}));var $w;(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"})($w||(T.AppSubType=$w={}));var xw;(function(e){e.OneToManyRelationship="OneToManyRelationship",e.ManyToManyRelationship="ManyToManyRelationship"})(xw||(T.RelationshipType=xw={}));var Fw;(function(e){e.ManyToOneRelationship="ManyToOneRelationship",e.OneToManyRelationship="OneToManyRelationship",e.ManyToManyRelationship="ManyToManyRelationship"})(Fw||(T.RelationshipTypeExt=Fw={}));var Mw;(function(e){e.NoCascade="NoCascade",e.Cascade="Cascade",e.Active="Active",e.UserOwned="UserOwned",e.RemoveLink="RemoveLink",e.Restrict="Restrict"})(Mw||(T.CascadeType=Mw={}));var Uw;(function(e){e.None="None",e.Append="Append",e.ParentChild="ParentChild",e.Pointer="Pointer",e.Inheritance="Inheritance"})(Uw||(T.RelationshipSecurityTypes=Uw={}));var Bw;(function(e){e[e.Active=1]="Active",e[e.Inactive=2]="Inactive"})(Bw||(T.ViewStatusCode=Bw={}));var qw;(function(e){e[e.Active=0]="Active",e[e.Inactive=1]="Inactive"})(qw||(T.ViewStateCode=qw={}));var Vw;(function(e){e.Active="Active",e.Failed="Failed",e.InProgress="InProgress",e.Pending="Pending"})(Vw||(T.EntityKeyIndexStatus=Vw={}));var Gw;(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"})(Gw||(T.SolutionComponentTypeCode=Gw={}));var Ww;(function(e){e[e.IncludeSubcomponents=0]="IncludeSubcomponents",e[e.DoNotIncludeSubcomponents=1]="DoNotIncludeSubcomponents",e[e.IncludeAsShellOnly=2]="IncludeAsShellOnly"})(Ww||(T.RootComponentBehavior=Ww={}));var _c;(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"})(_c||(T.SolutionComponentTypeCodeExt=_c={}));var Tc;(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"})(Tc||(T.EntityTypeCode=Tc={}));var zw;(function(e){e.MultiSelectPicklist="MultiSelectPicklist",e.File="File",e.Image="Image"})(zw||(T.SolutionComponentVirtualAttributeSubtype=zw={}));function MU(e){let t=_c[e];return Tc[t]}T.SolutionComponentTypeCodeToEntityTypeCodeExt=MU;function UU(e){let t=Tc[e];return _c[t]}T.SolutionEntityTypeCodeExtToComponentTypeCode=UU;var jw;(function(e){e.Active="Active",e.Auto="Auto",e.Disabled="Disabled",e.Inactive="Inactive"})(jw||(T.ImeMode=jw={}));var Hw;(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"})(Hw||(T.SourceType=Hw={}));var Kw;(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"})(Kw||(T.StringFormatName=Kw={}));var Jw;(function(e){e[e.PrecisionProperty=0]="PrecisionProperty",e[e.Organization=1]="Organization",e[e.TransactionCurrency=2]="TransactionCurrency"})(Jw||(T.PrecisionSource=Jw={}));var Yw;(function(e){e.UserLocal="UserLocal",e.DateOnly="DateOnly",e.TimeZoneIndependent="TimeZoneIndependent"})(Yw||(T.DateTimeBehavior=Yw={}));var Qw;(function(e){e.DateOnly="DateOnly",e.DateAndTime="DateAndTime"})(Qw||(T.DateTimeFormat=Qw={}));var Xw;(function(e){e.None="None",e.Duration="Duration",e.TimeZone="TimeZone",e.Language="Language",e.Locale="Locale"})(Xw||(T.IntegerFormat=Xw={}));var Zw;(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"})(Zw||(T.WebResourceTypeCode=Zw={}));var eC;(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"})(eC||(T.SdkMessageProcessingStage=eC={}));var tC;(function(e){e[e.ServerOnly=0]="ServerOnly",e[e.OutlookClientOnly=1]="OutlookClientOnly",e[e.Both=2]="Both"})(tC||(T.SupportedDeployment=tC={}));var rC;(function(e){e[e.Synchronous=0]="Synchronous",e[e.Asynchronous=1]="Asynchronous"})(rC||(T.SdkMessageProcessingMode=rC={}));var nC;(function(e){e[e.ReportingServicesReport=1]="ReportingServicesReport",e[e.OtherReport=2]="OtherReport",e[e.LinkedReport=3]="LinkedReport"})(nC||(T.ReportTypeCode=nC={}));var iC;(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"})(iC||(T.ConnectionRoleCategory=iC={}));var oC;(function(e){e[e.Name=1]="Name",e[e.Address=2]="Address"})(oC||(T.ServiceNamespaceFormat=oC={}));var aC;(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"})(aC||(T.ServiceEndpointContract=aC={}));var sC;(function(e){e[e.Normal=1]="Normal",e[e.Federated=2]="Federated"})(sC||(T.ServiceEndpointConnectionMode=sC={}));var lC;(function(e){e.CannotDeleteInUseComponent="0x8004f01f",e.CannotDeleteInUseAttribute="0x80048418",e.CannotDeleteInUseOptionSet="0x80048417",e.CannotDeleteInUseEntity="0x80048420",e.CannotUninstallWithDependencies="0x8004F01D"})(lC||(T.DeleteDependencyErrorCode=lC={}));var uC;(function(e){e.SystemAdministrator="627090FF-40A3-4053-8790-584EDC5BE201",e.SystemCustomizer="119F245C-3CC8-4B62-B31C-D1A046CED15D"})(uC||(T.DefaultRoleTemplates=uC={}));var cC;(function(e){e[e.DefaultTeamPrivilege=0]="DefaultTeamPrivilege",e[e.DirectUserAndTeamPrivilege=1]="DirectUserAndTeamPrivilege"})(cC||(T.RoleInheritance=cC={}));var dC;(function(e){e[e.NotSpecified=0]="NotSpecified",e[e.CustomConnector=1]="CustomConnector"})(dC||(T.ConnectorTypeEnum=dC={}));var fC;(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"})(fC||(T.EnvironmentVariableDefinitionTypeEnum=fC={}));var pC;(function(e){e[e.Owner=0]="Owner",e[e.Access=1]="Access",e[e.AADSecurityGroup=2]="AADSecurityGroup",e[e.AADOfficeGroup=3]="AADOfficeGroup"})(pC||(T.TeamTypeEnum=pC={}));var mC;(function(e){e.Bots="bots"})(mC||(T.KnownCustomSolutionComponentEntitySetName=mC={}));var hC;(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"})(hC||(T.QueryType=hC={}))});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.WebResourceUnverifiedError=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 dt=class extends Error{constructor(t,r){super(r),this.code=t,Object.setPrototypeOf(this,new.target.prototype),this.name=new.target.name}};X.SdkError=dt;var gC=Symbol.for("cds-maker-sdk.partialWriteTokens");function BU(e,t){return typeof e=="object"&&e!==null&&(e[gC]=t),e}X.withPartialTokens=BU;function qU(e){return Dm(e,gC)}X.readPartialTokens=qU;function Dm(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 yC=Symbol.for("cds-maker-sdk.partialDefaultViewEnrichment");function VU(e,t){return typeof e=="object"&&e!==null&&(e[yC]=t),e}X.withPartialEnrichment=VU;function GU(e){return Dm(e,yC)}X.readPartialEnrichment=GU;var dm=Symbol.for("cds-maker-sdk.cleanupWarnings");function WU(e,t){if(typeof e=="object"&&e!==null&&t.length>0){let r=e,n=r[dm];r[dm]=[...Array.isArray(n)?n:[],...t]}return e}X.withCleanupWarnings=WU;function zU(e){let t=Dm(e,dm);return t?[...t]:void 0}X.readCleanupWarnings=zU;var fm=class extends dt{constructor(t,r){super("ARTIFACT_NOT_FOUND",`Artifact ${t}/${r} not found in workspace`),this.type=t,this.id=r}};X.ArtifactNotFoundError=fm;var pm=class extends dt{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=pm;var mm=class extends dt{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=mm;var hm=class extends dt{constructor(t){super("INVALID_ARGUMENT",t)}};X.InvalidArgumentError=hm;var gm=class extends dt{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=gm;var ym=class extends dt{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=ym;var bm=class extends dt{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=bm;var vm=class extends dt{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=vm;var wm=class extends dt{constructor(t,r,n){super("WEB_RESOURCE_UNVERIFIED",n),this.id=t,this.webResourceName=r}};X.WebResourceUnverifiedError=wm;function jU(e,t){return typeof e=="object"&&e!==null&&Object.defineProperty(e,"cause",{value:t,enumerable:!1,writable:!0,configurable:!0}),e}X.attachCause=jU;var Cm=class extends dt{constructor(t){super("WORKSPACE_NOT_INITIALIZED",`Workspace not initialized at ${t}. Call initWorkspace() first.`),this.workspacePath=t}};X.WorkspaceNotInitializedError=Cm;var Em=class extends dt{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=Em;var Am=class extends dt{constructor(t,r){super("NOT_IMPLEMENTED",`Operation '${t}' is not implemented yet${r?`: ${r}`:""}.`),this.operation=t}};X.NotImplementedError=Am;var Sm=class extends dt{constructor(t,r){super("INVALID_JSON_POINTER",`Invalid JSON Pointer '${t}': ${r}`),this.pointer=t}};X.JsonPointerError=Sm;var Nm=class extends dt{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=Nm;var _m=class extends dt{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=_m;var Tm=class extends dt{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=Tm});var le=v(nt=>{"use strict";Object.defineProperty(nt,"__esModule",{value:!0});nt.odataQuery=nt.normalizeGuid=nt.createSafeXmlElement=nt.assertNoControlChars=nt.assertODataName=nt.assertXmlName=nt.xmlText=nt.odataPathLiteral=nt.odataLiteral=void 0;var Dc=Q();function bC(e){return String(e??"").replace(/'/g,"''")}nt.odataLiteral=bC;function HU(e){return encodeURIComponent(bC(e))}nt.odataPathLiteral=HU;function KU(e){return String(e??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}nt.xmlText=KU;function vC(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 Dc.InvalidArgumentError(`${t} must be a valid XML element name (got '${e}')`);return e}nt.assertXmlName=vC;function JU(e,t){let r=String(e??"");if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(r))throw new Dc.InvalidArgumentError(`${t} must be a valid OData identifier (letters, digits, underscore): got '${e}'`);return e}nt.assertODataName=JU;function YU(e,t){if(/[\u0000-\u001F\u007F]/.test(String(e??"")))throw new Dc.InvalidArgumentError(`${t} must not contain control characters (including CR/LF): they would inject additional lines into the request`);return e}nt.assertNoControlChars=YU;function QU(e,t,r){return e.createElement(vC(t,r))}nt.createSafeXmlElement=QU;var XU=/^[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 ZU(e,t){let r=String(e??""),n=r.length===38&&r.startsWith("{")&&r.endsWith("}")?r.slice(1,-1):r;if(!XU.test(n))throw new Dc.InvalidArgumentError(`${t} must be a valid GUID (got '${e}')`);return n.toLowerCase()}nt.normalizeGuid=ZU;function eB(e){let t=[];for(let[r,n]of e)n!=null&&n!==""&&t.push(`${r}=${encodeURIComponent(String(n))}`);return t.length>0?`?${t.join("&")}`:""}nt.odataQuery=eB});var ye=v(z=>{"use strict";Object.defineProperty(z,"__esModule",{value:!0});z.nowIso=z.isAlreadyDeleted=z.deleteRecord=z.resendAppSearchIndexRace=z.resendDeadlockVictim=z.resendWhile=z.isAppSearchIndexRace=z.namesAppSearchIndexRace=z.isTransactionNotStarted=z.TRANSACTION_NOT_STARTED_CODE=z.LOCK_BACKOFF_MS=z.isConcurrencyLockRefusalError=z.isConcurrencyLockRefusal=z.CONCURRENCY_LOCK_CODE=z.AMBIGUOUS_WRITE_STATUSES=z.DEADLOCK_BACKOFF_MS=z.isSqlDeadlockVictim=z.ensureSuccess=z.resolveCreatedId=z.requireCreatedId=z.withClientMintedId=z.readCreatedId=z.readRowEtag=z.readEtag=z.requireEtag=z.isVersionToken=z.echoWrite=z.UPDATE_NO_ETAG_CODE=z.VERSION_CONFLICT_CODE=void 0;var ko=Q(),$a=le();z.VERSION_CONFLICT_CODE="VERSION_CONFLICT";z.UPDATE_NO_ETAG_CODE="ARTIFACT_UPDATE_NO_ETAG";function tB(e,t){return{query:`?$select=${encodeURIComponent(e)}`,options:{headers:{...t??{},Prefer:"return=representation"}}}}z.echoWrite=tB;function wC(e){return typeof e=="string"&&e.trim()!==""&&e.trim()!=="*"}z.isVersionToken=wC;function rB(e,t,r){if(!wC(e))throw new ko.SdkError(z.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}z.requireEtag=rB;function CC(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}z.readEtag=CC;async function nB(e,t,r,n){let i=`/${t}(${n})${(0,$a.odataQuery)([["$select",r]])}`;return CC(Om(await e.get(i),e.apiUrl(i)))}z.readRowEtag=nB;function Im(e,t){var r;let n=e.body;if(n&&typeof n[t]=="string")return(0,$a.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,$a.normalizeGuid)(a[1],t)}return null}z.readCreatedId=Im;function iB(e,t,r){return r?{...e,[t]:(0,$a.normalizeGuid)(r,t)}:e}z.withClientMintedId=iB;function oB(e,t,r){let n=Im(e,t);if(!n)throw new ko.InvalidArgumentError(`Dataverse did not return an id for the created ${r}`);return n}z.requireCreatedId=oB;function aB(e,t,r,n){let i=Im(e,t);if(i)return i;if(n)return(0,$a.normalizeGuid)(n,t);throw new ko.InvalidArgumentError(`Dataverse did not return an id for the created ${r}`)}z.resolveCreatedId=aB;function Om(e,t){if(e.status===412)throw new ko.SdkError(z.VERSION_CONFLICT_CODE,`Version conflict (412) from ${t}`);if(e.status<200||e.status>=300)throw new ko.ConnectionError(t,e.status,fB(e.body),e.body);return e}z.ensureSuccess=Om;function EC(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)}z.isSqlDeadlockVictim=EC;z.DEADLOCK_BACKOFF_MS=[1e3,2e3,4e3];z.AMBIGUOUS_WRITE_STATUSES=new Set([408,502,503,504]);z.CONCURRENCY_LOCK_CODE="0x80071151";function AC(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()===z.CONCURRENCY_LOCK_CODE}z.isConcurrencyLockRefusal=AC;function sB(e){return e instanceof ko.ConnectionError&&e.statusCode===429&&AC({status:429,headers:{},body:e.cause})}z.isConcurrencyLockRefusalError=sB;z.LOCK_BACKOFF_MS=[2e3,3e3,...Array.from({length:35},()=>5e3)];z.TRANSACTION_NOT_STARTED_CODE="0x80040251";function lB(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()===z.TRANSACTION_NOT_STARTED_CODE}z.isTransactionNotStarted=lB;var uB=/(?:^|[^a-z0-9_])AppModule_DVTableSearch_M365AppModuleId(?![a-z0-9_])/i;function SC(e){return uB.test(e)&&/\bSql Number:\s*547\b/i.test(e)}z.namesAppSearchIndexRace=SC;function NC(e){return e.status!==400||e.body===void 0||e.body===null?!1:SC(typeof e.body=="string"?e.body:JSON.stringify(e.body))}z.isAppSearchIndexRace=NC;async function Pm(e,t,r=z.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]))}}z.resendWhile=Pm;function cB(e){return Pm(EC,e,z.DEADLOCK_BACKOFF_MS)}z.resendDeadlockVictim=cB;function dB(e){return Pm(NC,e,z.DEADLOCK_BACKOFF_MS)}z.resendAppSearchIndexRace=dB;function fB(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 pB(e,t,r,n){let i=(0,$a.normalizeGuid)(r,"id"),o=`/${t}(${i})`;Om(await e.delete(o,n?{headers:{"If-Match":n}}:void 0),e.apiUrl(o))}z.deleteRecord=pB;function mB(e){return e instanceof ko.ConnectionError&&e.statusCode===404}z.isAlreadyDeleted=mB;function hB(){return new Date().toISOString()}z.nowIso=hB});var Lt=v(xa=>{"use strict";Object.defineProperty(xa,"__esModule",{value:!0});xa.describeMalformedValue=xa.collectPages=void 0;var _C=ye(),Rm=Q();async function gB(e,t,r,n,i){let o=[],a=new Set,s=e.apiUrl(t),l=(0,_C.ensureSuccess)(await e.get(t,i),s);for(n?.(l);;){let u=l.body,c=u?.value;if(!Array.isArray(c))throw new Rm.ConnectionError(s,l.status,`${r}: paginated read returned a malformed page \u2014 expected an OData 'value' array but got ${km(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 Rm.ConnectionError(s,l.status,`${r}: paginated read returned a malformed @odata.nextLink (${km(d)}); cannot follow it, and refusing to return partial results.`);if(a.has(d))throw new Rm.InvalidArgumentError(`${r}: aborting pagination \u2014 the server returned a repeated @odata.nextLink ('${d}'), which would loop indefinitely.`);a.add(d),s=d,l=(0,_C.ensureSuccess)(await e.getAbsolute(d,i),d)}return o}xa.collectPages=gB;function km(e){return e===null?"null":e===void 0?"undefined (missing)":`a ${typeof e}`}xa.describeMalformedValue=km});var Lm=v($o=>{"use strict";Object.defineProperty($o,"__esModule",{value:!0});$o.assertWorkflowKind=$o.WORKFLOW_KIND_MISMATCH_CODE=void 0;var Lo=Qi(),yB=Q(),TC=ye(),bB=le();$o.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 vB(e,t,r){var n,i;let o=`/workflows(${t})${(0,bB.odataQuery)([["$select","category"]])}`,a=await e.get(o);if(a.status===404)return null;(0,TC.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 yB.SdkError($o.WORKFLOW_KIND_MISMATCH_CODE,`Refusing to delete workflow '${t}' as a ${DC[r]}: it is ${u}. Nothing was changed. Check the id.`)}return(0,TC.readEtag)(a)}$o.assertWorkflowKind=vB});var xm=v(Yr=>{"use strict";Object.defineProperty(Yr,"__esModule",{value:!0});Yr.deleteWorkflowResending=Yr.isWorkflowDeleteUnsettled=Yr.failedAfterResend=Yr.WORKFLOW_DELETE_UNSETTLED_CODE=void 0;var bl=Q(),hi=ye(),OC=le();Yr.WORKFLOW_DELETE_UNSETTLED_CODE="WORKFLOW_DELETE_UNSETTLED";var PC=new WeakSet;function $m(e){return typeof e=="object"&&e!==null&&PC.add(e),e}function wB(e){return typeof e=="object"&&e!==null&&PC.has(e)}Yr.failedAfterResend=wB;function CB(e){return e instanceof bl.SdkError&&e.code===Yr.WORKFLOW_DELETE_UNSETTLED_CODE}Yr.isWorkflowDeleteUnsettled=CB;function EB(e,t){try{(0,hi.ensureSuccess)(e,t)}catch(r){return r}}function AB(e){return(0,hi.isSqlDeadlockVictim)(e)?"lost a SQL deadlock (HTTP 500, Sql Number 1205)":`lost its transaction (HTTP 500 ${hi.TRANSACTION_NOT_STARTED_CODE})`}async function IC(e,t){try{return(await e.get(`/workflows(${t})${(0,OC.odataQuery)([["$select","workflowid"]])}`)).status===404}catch{return!1}}async function SB(e,t,{bindingToken:r,kindName:n,deactivated:i=!1,resendDeadlockVictim:o=!1,ifMatchOnFirst:a=!1}){let s=(0,OC.normalizeGuid)(t,"id");if(a&&!r)throw new bl.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,hi.isTransactionNotStarted)(p)||o&&(0,hi.isSqlDeadlockVictim)(p),d=0,f,m;try{m=await(0,hi.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?hi.DEADLOCK_BACKOFF_MS:[])}catch(p){if(p instanceof bl.ConnectionError&&p.statusCode===0&&r&&await IC(e,s))return;throw d>1?$m(p):p}if(!(d>1&&m.status===404)){if(d>1&&m.status===412){let p=AB(f),h=new bl.SdkError(Yr.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 $m((0,bl.attachCause)(h,EB(f,u)))}if(!(r&&hi.AMBIGUOUS_WRITE_STATUSES.has(m.status)&&await IC(e,s)))try{(0,hi.ensureSuccess)(m,u)}catch(p){throw d>1?$m(p):p}}}Yr.deleteWorkflowResending=SB});var Fm=v(Bn=>{"use strict";Object.defineProperty(Bn,"__esModule",{value:!0});Bn.businessRuleApi=Bn.BUSINESS_RULE_LEFT_DEACTIVATED_CODE=Bn.WFOM_API_UNAVAILABLE_CODE=void 0;var Un=Qi(),NB=Lt(),_B=Lm(),TB=xm(),Gt=ye(),gi=le(),Oc=Q();Bn.WFOM_API_UNAVAILABLE_CODE="BUSINESS_RULE_API_UNAVAILABLE";Bn.BUSINESS_RULE_LEFT_DEACTIVATED_CODE="BUSINESS_RULE_LEFT_DEACTIVATED";async function RC(e,t,r,n){let i=`/workflows(${OB})/Microsoft.Dynamics.CRM.${t}`;try{return(0,Gt.ensureSuccess)(await e.post(i,{Entity:r.Entity,WfomJson:r.WfomJson},{headers:n}),e.apiUrl(i))}catch(o){throw o?.statusCode!==404?o:new Oc.SdkError(Bn.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 DB(e,t){let r=`/workflows(${t})${(0,gi.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,Gt.readEtag)(n),statecode:typeof i?.statecode=="number"?i.statecode:null,statuscode:typeof i?.statuscode=="number"?i.statuscode:null}}catch{return null}}async function IB(e,t,r){let n=await DB(e,t);if(n===null||n.etag===null)throw new Oc.SdkError(Gt.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 Oc.SdkError(Gt.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 OB="00000000-0000-0000-0000-000000000000",Ic={"Content-Type":"application/json",Accept:"application/json","OData-Version":"4.0","OData-MaxVersion":"4.0"},PB="workflowid,name,description,primaryentity,statecode,category,type",RB="category eq 2 and type eq 1";async function kC(e,t,r){var n;if(r==="Draft")return null;let i=(0,gi.normalizeGuid)(t,"workflowid"),o=r==="Active",a={statecode:o?Un.StateCode.Activated:Un.StateCode.Draft,statuscode:o?Un.StatusCode.Activated:Un.StatusCode.Draft},s=`/workflows(${i})`,l=(0,Gt.ensureSuccess)(await e.patch(s,a,{headers:Ic}),e.apiUrl(s));return(n=(0,Gt.readEtag)(l))!==null&&n!==void 0?n:await vl(e,i)}async function vl(e,t){let r=`/workflows(${t})${(0,gi.odataQuery)([["$select","workflowid"]])}`;try{let n=await e.get(r);return n.status>=200&&n.status<300?(0,Gt.readEtag)(n):null}catch{return null}}async function kB(e,t,r){let n=await vl(e,t),i=await r(),o=(0,Gt.readEtag)(i);if(o)return{response:i,etag:o};let a=await vl(e,t);return{response:i,etag:n!==null&&n===a?a:null}}Bn.businessRuleApi={async get(e,t){let r=(0,gi.normalizeGuid)(t,"id"),n=`/workflows(${r})/Microsoft.Dynamics.CRM.RetrieveProcessWithWfomJson`,{response:i,etag:o}=await kB(e,r,async()=>(0,Gt.ensureSuccess)(await e.get(n),e.apiUrl(n)));return{raw:i.body,etag:o}},async list(e,t){let r=[RB];t?.entityLogicalName&&r.push(`primaryentity eq '${(0,gi.odataLiteral)(t.entityLogicalName)}'`);let n=`/workflows${(0,gi.odataQuery)([["$select",PB],["$filter",r.join(" and ")]])}`;return(await(0,NB.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,gi.normalizeGuid)(n.Entity.workflowid,"workflowid"),o=await RC(e,"CreateProcessWithWfomJson",n,Ic),a=(0,Gt.resolveCreatedId)(o,"workflowid","business rule",i),s=null;try{s=await kC(e,a,n.status)}catch(l){try{await(0,Gt.deleteRecord)(e,"workflows",a)}catch{}throw l}return{id:a,etag:(r=s??(0,Gt.readEtag)(o))!==null&&r!==void 0?r:await vl(e,a)}},async update(e,t,r,n){var i,o;let a=r,s=(0,gi.normalizeGuid)(t,"id"),l=`/workflows(${s})`,u={...Ic,"If-Match":(0,Gt.requireEtag)(n,"business rule",s)},c=await IB(e,s,u["If-Match"]),d=c.statecode===Un.StateCode.Activated;d&&(0,Gt.ensureSuccess)(await e.patch(l,{statecode:Un.StateCode.Draft,statuscode:Un.StatusCode.Draft},{headers:u}),e.apiUrl(l));let f;try{f=await RC(e,"UpdateProcessWithWfomJson",a,u)}catch(p){if(d)try{(0,Gt.ensureSuccess)(await e.patch(l,{statecode:Un.StateCode.Activated,statuscode:(i=c.statuscode)!==null&&i!==void 0?i:Un.StatusCode.Activated},{headers:Ic}),e.apiUrl(l))}catch(h){throw new Oc.SdkError(Bn.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 kC(e,s,a.status);return{id:s,etag:(o=m??(0,Gt.readEtag)(f))!==null&&o!==void 0?o:await vl(e,s)}},async delete(e,t){let r=(0,gi.normalizeGuid)(t,"id"),n=await(0,_B.assertWorkflowKind)(e,r,Un.WorkflowCategory.BusinessRule);return(0,TB.deleteWorkflowResending)(e,r,{bindingToken:n,kindName:"business rule"})}}});var Qr=v(Et=>{"use strict";Object.defineProperty(Et,"__esModule",{value:!0});Et.publishBoundEntity=Et.boundEntityPublishScope=Et.publishGenPageById=Et.publishDashboardById=Et.publishWebResourceById=Et.publishEntity=Et.publishAppModule=Et.publishXml=void 0;var LC=ye(),wl=le(),$C="/PublishXml";async function Fa(e,t){(0,LC.ensureSuccess)(await(0,LC.resendDeadlockVictim)(()=>e.post($C,{ParameterXml:t})),e.apiUrl($C))}Et.publishXml=Fa;function LB(e,t){return Fa(e,`<importexportxml><appmodules><appmodule>${(0,wl.xmlText)(t)}</appmodule></appmodules></importexportxml>`)}Et.publishAppModule=LB;function xC(e,t){return Fa(e,`<importexportxml><entities><entity>${(0,wl.xmlText)(t)}</entity></entities></importexportxml>`)}Et.publishEntity=xC;function $B(e,t){return Fa(e,`<importexportxml><webresources><webresource>${(0,wl.xmlText)(t)}</webresource></webresources></importexportxml>`)}Et.publishWebResourceById=$B;function xB(e,t){return Fa(e,`<importexportxml><dashboards><dashboard>${(0,wl.xmlText)(t)}</dashboard></dashboards></importexportxml>`)}Et.publishDashboardById=xB;function FB(e,t){return Fa(e,`<importexportxml><uxagentprojects><uxagentproject>${(0,wl.xmlText)(t)}</uxagentproject></uxagentprojects></importexportxml>`)}Et.publishGenPageById=FB;function MB(e){let t=e?.entityLogicalName;return t?{envelope:"entity",entityLogicalName:t,blastRadiusWarning:"ENTITY_ENVELOPE_ALSO_SHIPS_UNRELATED_UNPUBLISHED_CHANGES"}:{envelope:"entity"}}Et.boundEntityPublishScope=MB;function UB(e,t){let r=t?.entityLogicalName;return r?xC(e,r):Promise.resolve()}Et.publishBoundEntity=UB});var Ma=v(Rc=>{"use strict";Object.defineProperty(Rc,"__esModule",{value:!0});Rc.JsonPointer=void 0;var qr=Q(),Pc=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 qr.JsonPointerError(t,'non-empty pointers must start with "/"');return t.substring(1).split("/").map(r=>{if(/~(?![01])/.test(r))throw new qr.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 qr.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 qr.JsonPointerError(r,`'${a}' is not a valid array index`);if(s>o.length)throw new qr.JsonPointerError(r,`array index '${a}' is out of range`);o[s]=n}else{if(e.isReservedToken(a))throw new qr.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 qr.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 qr.JsonPointerError(r,`array index '${o}' is out of range`);i.splice(a,1)}else{if(e.isReservedToken(o))throw new qr.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 qr.JsonPointerError(r,"add target must be an array");u.push(n);return}let a=e.resolve(t,r);if(!Array.isArray(a))throw new qr.JsonPointerError(r,"add target must be an array");let s=i===void 0?a.length:i;if(s<0||s>a.length)throw new qr.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 qr.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)}};Rc.JsonPointer=Pc;Pc.RESERVED_TOKENS=new Set(["__proto__","prototype","constructor"])});var MC=v(kc=>{"use strict";Object.defineProperty(kc,"__esModule",{value:!0});kc.findElements=void 0;var FC=Ma();function BB(e,t){let r=[];return Mm(e,"",t,r),r}kc.findElements=BB;function Mm(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)=>{Mm(i,FC.JsonPointer.append(t,o),r,n)});else for(let i of Object.keys(e))Mm(e[i],FC.JsonPointer.append(t,i),r,n)}});var Um=v(qn=>{"use strict";Object.defineProperty(qn,"__esModule",{value:!0});qn.assertMutationResult=qn.assertExistsResult=qn.assertReadResult=qn.assertStorageContract=void 0;var qB=["readText","writeTextAtomic","deleteFile","deleteByPrefix"],VB=["ensureContainer","exists"];function GB(e){if(typeof e!="object"||e===null)throw new Error("workspaceStorage must be an object implementing WorkspaceStorage.");for(let t of qB)if(typeof e[t]!="function")throw new Error(`workspaceStorage is missing the required method '${t}'.`);for(let t of VB){let r=e[t];if(r!==void 0&&typeof r!="function")throw new Error(`workspaceStorage.${t} must be a function when present.`)}return e}qn.assertStorageContract=GB;function WB(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.`)}qn.assertReadResult=WB;function zB(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.`)}qn.assertExistsResult=zB;function jB(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.`)}qn.assertMutationResult=jB});var Bm=v(Ua=>{"use strict";Object.defineProperty(Ua,"__esModule",{value:!0});Ua.retryTransientIoAsync=Ua.retryTransientIo=void 0;var HB=new Set(["EPERM","EACCES","EBUSY","UNKNOWN"]),KB=5,UC=10;function JB(e){for(let t=1;;t+=1)try{return e()}catch(r){if(!BC(r,t))throw r;QB(UC*t)}}Ua.retryTransientIo=JB;async function YB(e){for(let t=1;;t+=1)try{return await e()}catch(r){if(!BC(r,t))throw r;await new Promise(n=>setTimeout(n,UC*t))}}Ua.retryTransientIoAsync=YB;function BC(e,t){let r=e.code;return t<KB&&!!r&&HB.has(r)}function QB(e){try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)}catch{let t=Date.now()+e;for(;Date.now()<t;);}}});var zC=v(Vr=>{"use strict";Object.defineProperty(Vr,"__esModule",{value:!0});Vr.canonicalArtifactId=Vr.WorkspaceManager=Vr.WORKSPACE_SCHEMA_VERSION=Vr.retryTransientIo=void 0;var Wt=Um(),Vn=Q(),XB=Bm();Object.defineProperty(Vr,"retryTransientIo",{enumerable:!0,get:function(){return XB.retryTransientIo}});function qC(e){let t=e;return typeof t.pathFor=="function"&&typeof t.getRoot=="function"?e:null}Vr.WORKSPACE_SCHEMA_VERSION=1;var Xi={form:"forms",view:"views",businessRule:"business-rules",app:"apps",command:"commands",chart:"charts",dashboard:"dashboards",genPage:"gen-pages",bpf:"business-process-flows"},ZB="manifest.json",Ba=".metadata",qm="entities";function VC(e){try{return Promise.resolve(e())}catch(t){return Promise.reject(t)}}function Vm(e){if(e.schemaVersion!==void 0&&e.schemaVersion>Vr.WORKSPACE_SCHEMA_VERSION)throw new Vn.IncompatibleWorkspaceError(e.schemaVersion,Vr.WORKSPACE_SCHEMA_VERSION)}function GC(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Lc(e){return e.trim().toLowerCase().replace(/\/+$/,"")}var Gm=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),[Xi[t],`${Cl(r)}.json`]}metaKey(t,r){return this.assertSafeId(r),[Ba,Xi[t],`${Cl(r)}.meta.json`]}entityKey(t){return this.assertSafeId(t),[Ba,qm,`${t.toLowerCase()}.json`]}fsStore(){let t=qC(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=qC(this.storage);return t?t.getRoot():this.workspaceLabel}getArtifactDir(t){return this.fsStore().pathFor([Xi[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 Vn.PathTraversalError(String(t),this.workspaceLabel)}get manifestKey(){return[ZB]}assertDataKey(t,r){if(!Array.isArray(t)||t.length<2)throw new Vn.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,Wt.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=[[Ba,qm]];for(let i of Object.keys(Xi))r.push([Xi[i]],[Ba,Xi[i]]);let n=await Promise.allSettled(r.map(i=>VC(()=>t(i))));for(let i of n){if(i.status==="rejected")throw i.reason;(0,Wt.assertMutationResult)(i.value,"ensureContainer")}}async isInitialized(){return this.storage.exists?(0,Wt.assertExistsResult)(await this.storage.exists(this.manifestKey),"manifest.json"):(0,Wt.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 Vn.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 Vn.WorkspaceNotInitializedError(this.workspaceLabel);this.assertBoundHere(t.value),this.bound=!0}assertBoundHere(t){if(!GC(t))throw new Vn.WorkspaceOrgMismatchError("",this.instanceUrl);Vm(t);let r=typeof t.instanceUrl=="string"?t.instanceUrl.trim():"",n=Lc(r);if(!n||n!==Lc(this.instanceUrl))throw new Vn.WorkspaceOrgMismatchError(r,this.instanceUrl)}async clean(){let t=await this.readStoredManifest();if(!t.present||!GC(t.value))throw new Vn.WorkspaceNotInitializedError(this.workspaceLabel);let r=t.value;Vm(r);let n=Object.keys(Xi).map(o=>[Xi[o]]);n.push([Ba]);let i=await Promise.allSettled(n.map(o=>VC(()=>this.storage.deleteByPrefix(o))));for(let o of i){if(o.status==="rejected")throw o.reason;(0,Wt.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,Wt.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=WC(n);if(i!==void 0&&o===i){await this.upsertManifestEntry(t,r,n,{unlessCurrent:!0});return}(0,Wt.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,Wt.assertMutationResult)(await this.storage.deleteFile(this.artifactKey(t,r)),"deleteFile"),(0,Wt.assertMutationResult)(await this.storage.deleteFile(this.metaKey(t,r)),"deleteFile");let n=Cl(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,Wt.assertMutationResult)(await this.storage.deleteByPrefix([Ba,qm]),"deleteByPrefix");return}(0,Wt.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 Vn.WorkspaceNotInitializedError(this.workspaceLabel);return Vm(t),t}async writeManifest(t){await this.writeJsonUnchecked(this.manifestKey,{...t,schemaVersion:Vr.WORKSPACE_SCHEMA_VERSION})}async updateManifest(t){await this.withManifest(async()=>{let r=await this.getManifest();if(t.instanceUrl!==void 0&&Lc(String(t.instanceUrl))!==Lc(r.instanceUrl))throw new Vn.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=Cl(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,Wt.assertMutationResult)(await this.storage.deleteFile(t),"deleteFile")}async exists(t){return await this.ensureBound(),this.storage.exists?(0,Wt.assertExistsResult)(await this.storage.exists(t),t.join("/")):(0,Wt.assertReadResult)(await this.storage.readText(t),t.join("/"))!==null}async readJsonUnchecked(t){let r=(0,Wt.assertReadResult)(await this.storage.readText(t),t.join("/"));return r===null?null:JSON.parse(r)}async writeJsonUnchecked(t,r){(0,Wt.assertMutationResult)(await this.storage.writeTextAtomic(t,WC(r)),"writeTextAtomic")}};Vr.WorkspaceManager=Gm;function WC(e){return`${JSON.stringify(e,null,2)}-`}function Cl(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()}Vr.canonicalArtifactId=Cl});var Wm=v(qa=>{"use strict";Object.defineProperty(qa,"__esModule",{value:!0});qa.deepEqual=qa.deepDiff=void 0;var eq=Ma();function tq(e,t){let r=[];return HC(e,t,"",r,0),r}qa.deepDiff=tq;var $c=Symbol("missing"),xc=512;function HC(e,t,r,n,i){if(e===t)return;if(i>xc)throw new RangeError(`deepDiff exceeded the maximum supported depth of ${xc}`);let o=Fc(e),a=Fc(t);if(o&&a&&Array.isArray(e)===Array.isArray(t)){let s=rq(e,t);for(let l of s){let u=jC(e,l),c=jC(t,l),d=eq.JsonPointer.append(r,l);u===$c?n.push({pointer:d,type:"added",newValue:c}):c===$c?n.push({pointer:d,type:"removed",oldValue:u}):HC(u,c,d,n,i+1)}return}KC(e,t)||n.push({pointer:r,type:"modified",oldValue:e,newValue:t})}function Fc(e){return e!==null&&typeof e=="object"}function rq(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 jC(e,t){if(Array.isArray(e)){let r=Number(t);return r<e.length?e[r]:$c}return t in e?e[t]:$c}function KC(e,t){return JC(e,t,0)}qa.deepEqual=KC;function JC(e,t,r){if(e===t)return!0;if(r>xc)throw new RangeError(`deepEqual exceeded the maximum supported depth of ${xc}`);if(!Fc(e)||!Fc(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&&JC(e[o],t[o],r+1))}});var QC=v(Va=>{"use strict";Object.defineProperty(Va,"__esModule",{value:!0});Va.VersionManager=Va.PROJECTION_VERSION=void 0;var YC=Wm(),nq=ye();Va.PROJECTION_VERSION=8;var zm=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,YC.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,YC.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,nq.isVersionToken)(i.etag)?!0:i.etag!==n}};Va.VersionManager=zm});var ZC=v((jm,XC)=>{(function(e,t){typeof define=="function"&&define.amd?define([],t):typeof jm=="object"?XC.exports=t():e.compareVersions=t()})(jm,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 iE=v(He=>{"use strict";Object.defineProperty(He,"__esModule",{value:!0});He.EnvironmentFlowHostingType=He.EnvironmentDisableReasonCode=He.EnvironmentMigrationConstants=He.EnvironmentProvisioningStates=He.EnvironmentLocations=He.EnvironmentCreationTypeConstants=He.EnvironmentType=He.EnvironmentSkuConstants=He.environmentPermissions=He.DatabaseType=void 0;var eE;(function(e){e.CommonDataService="CommonDataService",e.None="None"})(eE||(He.DatabaseType=eE={}));He.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"};He.EnvironmentSkuConstants={NotSpecified:"NotSpecified",Standard:"Standard",Premium:"Premium",Developer:"Developer",Basic:"Basic",Production:"Production",Sandbox:"Sandbox",Trial:"Trial",Default:"Default",Teams:"Teams",Platform:"Platform"};var tE;(function(e){e[e.CDS2=0]="CDS2",e[e.CDS1=1]="CDS1",e[e.Empty=2]="Empty"})(tE||(He.EnvironmentType=tE={}));He.EnvironmentCreationTypeConstants={NotSpecified:"NotSpecified",Legacy:"Legacy",DefaultTenant:"DefaultTenant",User:"User",CommonDataModelLegacy:"CommonDataModelLegacy"};He.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"};He.EnvironmentProvisioningStates={NotSpecified:"NotSpecified",Succeeded:"Succeeded",Deleting:"Deleting",Deleted:"Deleted",FailedDeleting:"FailedDeleting",LinkedDatabaseProvisioning:"LinkedDatabaseProvisioning",LinkedDatabaseFailedProvisioning:"LinkedDatabaseFailedProvisioning",LinkedDatabaseFailedConfiguring:"LinkedDatabaseFailedConfiguring",LinkedDatabaseUnavailable:"LinkedDatabaseUnavailable",Creating:"Creating"};He.EnvironmentMigrationConstants={phases:{completed:"Completed"}};var rE;(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"})(rE||(He.EnvironmentDisableReasonCode=rE={}));var nE;(function(e){e.LogicApps="LogicApps",e.SelfHostSingleTenant="SelfHostSingleTenant",e.SelfHostMultiTenant="SelfHostMultiTenant"})(nE||(He.EnvironmentFlowHostingType=nE={}))});var fE=v(_=>{"use strict";var iq=_&&_.__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 oq=iq(ZC()),Pe=iE(),El=Km();function aq(e){let t=bi(e);return t&&t.version}_.getCrmVersion=aq;function bi(e){return e&&e.properties&&e.properties.linkedEnvironmentMetadata}_.getLinkedEnvironmentMetadata=bi;function yi(e,t){return e?!!e[t]:!1}_.doesUserHavePermission=yi;_.crmBapSolutionId="00000001-0000-0000-0001-00000000009b";_.DEFAULT_SOLUTION_ID="fd140aaf-4df4-11dd-bd17-0019b9312238";_.DEFAULT_SOLUTION_UNIQUE_NAME="Default";function xo(e){return!!bi(e)&&oE(e)}_.environmentHasCds2Database=xo;function sq(e){if(e&&xo(e)){let t=Zi(e);return(0,El.getCrmAdminSecurityRolesUrl)(t)}return""}_.getSecurityUsersUrl=sq;function lq(e){if(e&&xo(e)){let t=Zi(e);return(0,El.getCrmAdminSecurityUsersUrl)(t)}return""}_.getSecurityRolesUrl=lq;function uq(e){if(e&&xo(e)){let t=Zi(e);(0,El.getCrmAllSolutionsUrl)(t)}return""}_.getAllSolutionsUrl=uq;function cq(e){if(e&&xo(e)){let t=Zi(e);return(0,El.getCrmAllPublishersUrl)(t)}return""}_.getAllPublishersUrl=cq;function dq(e){return e&&xo(e)?Zi(e):""}_.getAllThemesUrl=dq;function oE(e){return!!e&&e.properties&&!!e.properties.provisioningState&&e.properties.provisioningState.toUpperCase()===Pe.EnvironmentProvisioningStates.Succeeded.toUpperCase()}_.isEnvironmentInSuccessfulState=oE;function fq(e){if(e&&xo(e)){let t=Zi(e);return(0,El.getCrmDevResourcesUrl)(t)}return""}_.getDevResourcesUrl=fq;function pq(e){return`${e}designer/app/{${_.crmBapSolutionId}}/CreateNewApp}}`}_.getCrmAppDesignerUrl=pq;function Zi(e){let t=bi(e);if(t){let r=t.instanceUrl;return r?r.endsWith("/")?r:r+"/":""}return""}_.getCrmInstanceUrl=Zi;function mq(e){let t=bi(e);return t?t.uniqueName:""}_.getCrmInstanceName=mq;function hq(e){return bi(e)?Pe.EnvironmentType.CDS2:e&&e.properties&&e.properties.namespace?Pe.EnvironmentType.CDS1:Pe.EnvironmentType.Empty}_.getEnvironmentType=hq;function gq(e){return e&&e.properties&&e.properties.environmentSku===Pe.EnvironmentSkuConstants.Developer}_.isDevEnvironment=gq;function yq(e){return e&&e.properties&&e.properties.environmentSku===Pe.EnvironmentSkuConstants.Production}_.isProdEnvironment=yq;function bq(e){return e&&e.properties&&e.properties.environmentSku===Pe.EnvironmentSkuConstants.Sandbox}_.isSandboxEnvironment=bq;function Al(e){return e&&e.properties&&e.properties.environmentSku===Pe.EnvironmentSkuConstants.Teams}_.isTeamsEnvironment=Al;function vq(e){return e&&e.properties&&e.properties.environmentSku===Pe.EnvironmentSkuConstants.Platform}_.isPlatformEnvironment=vq;var wq=e=>{var t;return((t=e.properties)===null||t===void 0?void 0:t.environmentSku)===Pe.EnvironmentSkuConstants.Trial};_.isTrialEnvironment=wq;function Cq(e){return e&&e.properties&&(e.properties.isDefault||e.properties.creationType===Pe.EnvironmentCreationTypeConstants.DefaultTenant)}_.isDefaultEnvironment=Cq;function Eq(e){return e&&e.properties&&!!e.properties.states&&!!e.properties.states.runtime&&e.properties.states.runtime.id==="Disabled"}_.isDisabledEnvironment=Eq;function Aq(e){return e&&e.properties&&yi(e.properties.permissions,Pe.environmentPermissions.CreateDatabase)}_.canUserCreateDatabase=Aq;function Sq(e){return!!(e&&e.properties&&e.properties.provisioningState&&dE(e.properties.provisioningState,Pe.EnvironmentProvisioningStates.LinkedDatabaseProvisioning))}_.isDatabaseInProvisioningState=Sq;function Nq(e){return!!e&&!!e.properties&&e.properties.provisioningState===Pe.EnvironmentProvisioningStates.Creating}_.isEnvironmentInCreatingState=Nq;function _q(e){return e&&e.properties&&(e.properties.provisioningState===Pe.EnvironmentProvisioningStates.Deleted||e.properties.provisioningState===Pe.EnvironmentProvisioningStates.Deleting||e.properties.provisioningState===Pe.EnvironmentProvisioningStates.FailedDeleting)}_.isEnvironmentInDeletedState=_q;function Tq(e){return!!e&&!!e.properties&&!!e.properties.expirationTime&&Date.parse(e.properties.expirationTime)<Date.now()}_.isEnvironmentExpired=Tq;function Dq(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=Dq;function Iq(e){return!!e&&!!e.properties&&!!e.properties.cluster&&e.properties.cluster.category==="Test"}_.isEnvironmentInTestCluster=Iq;function Oq(e){return!!e&&!!e.properties&&!!e.properties.cluster&&e.properties.cluster.category==="Preprod"}_.isEnvironmentInPreprodCluster=Oq;function Pq(e){return!!e&&!!e.properties&&!!e.properties.cluster&&e.properties.cluster.category==="FirstRelease"}_.isEnvironmentInFirstReleaseCluster=Pq;function Rq(e){return e&&e.name||""}_.getEnvironmentName=Rq;function kq(e){return e&&e.properties&&e.properties.displayName||""}_.getEnvironmentDisplayName=kq;var aE="9.1.0.8202";_.cdsVersionSupportingOSColorEdit="9.1.0000.20708";function Lq(e){return uE(e,aE)}_.doesCds2EnvironmentSupportApiVersion9_1=Lq;function $q(e){return Hm(e,aE)}_.doesCds2VersionSupportApiVersion9_1=$q;function sE(e){let t=bi(e);if(t)return t.securityGroupId}function lE(e){return e&&e.properties&&e.properties.connectedGroups}function xq(e,t){let r=lE(e);return!!r&&!!r.find(n=>n.id===t)||sE(e)===t}_.hasSecurityGroupId=xq;function Fq(e){let t=lE(e);return t&&t.length>0&&t[0].id?t[0].id:sE(e)}_.getSecurityOrConnectedGroupId=Fq;function uE(e,t){let r=e.version;return r?Hm(r,t):!1}_.isCds2EnvironmentVersionAtLeast=uE;function Hm(e,t){return t?e?(0,oq.default)(e,t)>=0:!1:!0}_.checkVersions=Hm;function Mq(e){return e&&e.properties&&e.properties.updateCadence&&e.properties.updateCadence.id||"NotSpecified"}_.getEnvironmentUpdateCadence=Mq;function Uq(e){let t=bi(e);return t?Number(t.baseLanguage):0}_.getEnvironmentLanguageCode=Uq;function cE(e){let t=bi(e);return t?t.instanceApiUrl:void 0}_.getEnvironmentInstanceApiUrl=cE;function Bq(e){let t=cE(e);return t?t+"/api/data/v9.2":""}_.getEnvironmentWebApiUrl=Bq;function qq(e){let t=Zi(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=qq;var Vq=e=>{var t;return((t=e.properties)===null||t===void 0?void 0:t.databaseType)===Pe.DatabaseType.CommonDataService};_.hasCommonDataServiceDatabase=Vq;var Gq=e=>{var t;return yi((t=e.properties)===null||t===void 0?void 0:t.permissions,Pe.environmentPermissions.AdminReadEnvironment)};_.doesUserHaveAdminPermission=Gq;var Wq=e=>{var t;return yi((t=e.properties)===null||t===void 0?void 0:t.permissions,Pe.environmentPermissions.CreatePowerApp)};_.doesUserHaveCreateAppPermission=Wq;var zq=e=>(0,_.doesUserHaveAdminPermission)(e)&&(0,_.hasCommonDataServiceDatabase)(e)?!0:(0,_.doesUserHaveCreateAppPermission)(e)?Al(e)||(0,_.doesUserHaveDatabaseTablePermissions)(e):!1;_.isUserMakerWithDataAccess=zq;var jq=e=>(0,_.doesUserHaveCreateAppPermission)(e)&&!Al(e)&&!(0,_.doesUserHaveDatabaseTablePermissions)(e)&&(!(0,_.doesUserHaveAdminPermission)(e)||!(0,_.hasCommonDataServiceDatabase)(e));_.isUserMakerWithoutDataAccess=jq;var Hq=e=>[Pe.environmentPermissions.CreateDatabaseEntities,Pe.environmentPermissions.ListDatabaseEntities,Pe.environmentPermissions.UpdateDatabaseEntities,Pe.environmentPermissions.DeleteDatabaseEntities].every(t=>{var r;return yi((r=e.properties)===null||r===void 0?void 0:r.permissions,t)});_.doesUserHaveDatabaseTablePermissions=Hq;var Kq=e=>{var t;return yi((t=e.properties)===null||t===void 0?void 0:t.permissions,Pe.environmentPermissions.CreateDatabase)};_.doesUserHaveCreateDatabasePermission=Kq;function dE(e,t){return!e&&!t?!0:!e||!t?!1:e.toUpperCase()===t.toUpperCase()}_.equalsIgnoreCase=dE;var Jq=e=>{var t;return yi((t=e.properties)===null||t===void 0?void 0:t.permissions,Pe.environmentPermissions.CreateFlow)};_.doesUserHaveCreateFlowPermission=Jq;var Yq=e=>(0,_.doesUserHaveAdminPermission)(e)&&(0,_.hasCommonDataServiceDatabase)(e)?!0:(0,_.doesUserHaveCreateFlowPermission)(e)?Al(e)||(0,_.doesUserHaveDatabaseTablePermissions)(e):!1;_.isUserPautoMakerWithDataAccess=Yq;var Qq=e=>(0,_.doesUserHaveCreateFlowPermission)(e)&&!Al(e)&&!(0,_.doesUserHaveDatabaseTablePermissions)(e)&&(!(0,_.doesUserHaveAdminPermission)(e)||!(0,_.hasCommonDataServiceDatabase)(e));_.isUserPautoMakerWithoutDataAccess=Qq;var Xq=e=>{var t,r;return!yi((t=e.properties)===null||t===void 0?void 0:t.permissions,Pe.environmentPermissions.CreateFlow)&&yi((r=e.properties)===null||r===void 0?void 0:r.permissions,Pe.environmentPermissions.ReadEnvironment)};_.doesUserHaveFlowRunOnlyPermission=Xq});var Km=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 pE=fE();A.ODATA_MAX_PAGE_SIZE="odata.maxpagesize";A.ODATA_NEXT_LINK="@odata.nextLink";A.cdsServiceUrl="https://cds-org/";var Nl;(function(e){e.AllSolutions="11",e.AllPublishers="10",e.DevResources="05"})(Nl||(Nl={}));function Zq(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=Zq;function e3(e,t){let r=`dType=1&isproactivecheck=true&objecttype=7100&operationtype=dependenciesforuninstall&objectid=${t}`;return`${e}tools/dependency/dependencyviewdialog.aspx?${r}`}A.getShowSolutionDependenciesUrl=e3;function t3(e,t){return`${e}tools/muiProvisioning/Dialogs/LangTranslationsImport.aspx?dType=1&appSolutionId=${t}`}A.getImportSolutionTranslationUrl=t3;function r3(e,t){return`${e}_grid/cmds/dlg_exportsolution.aspx?command=exporttranslation&appSolutionId=${t}`}A.getExportSolutionTranslationUrl=r3;function n3(e,t){return e!==void 0&&t!==void 0&&`CrmTranslations_${e}_${t.replace(/[.]/g,"_")}.zip`||""}A.getExportTranslationFileName=n3;function i3(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=i3;function Jm(e,t){return`${e}tools/systemcustomization/systemCustomization.aspx?pid=${t}`}function o3(e){return Jm(e,Nl.AllSolutions)}A.getCrmAllSolutionsUrl=o3;function a3(e){return Jm(e,Nl.AllPublishers)}A.getCrmAllPublishersUrl=a3;function s3(e){return Jm(e,Nl.DevResources)}A.getCrmDevResourcesUrl=s3;function l3(e,t=pE.crmBapSolutionId){return`${e}designer/app/${t}#/CreateNewApp`}A.getCrmAppDesignerUrl=l3;function u3(e){return`${e}apps`}A.getCrmMyAppsUrl=u3;function c3(e){return mE(e,"role")+"&forceUCI=0"}A.getCrmAdminSecurityRolesUrl=c3;function d3(e){return`${mE(e,"systemuser")}&forceclassic=1`}A.getCrmAdminSecurityUsersUrl=d3;function mE(e,t){return`${e}main.aspx?pagetype=entitylist&etn=${t}`}function f3(e,t){return`${e}main.aspx?appid=${t}`}A.getPlayAppModuleUrl=f3;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 p3(e,t,r=pE.crmBapSolutionId){return`${e}designer/app/${r}/${t}/AppDesignerCanvas/${t}`}A.getAppModuleDesignerUrl=p3;function m3(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=m3;function h3(e,t,r){return`/e/${e}/s/${t}/dashboard/${r}`}A.getOpenModernDashboardUrl=h3;function g3(e,t,r){let n=r!==void 0?r.toString():void 0;return`/e/${e}/s/${t}/dashboard/new${n?`/${n}`:""}`}A.getNewModernDashboardUrl=g3;function y3(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=y3;function b3(e,t,r,n){return`/e/${e}/s/${t}/n/${r}/dashboard/${n}`}A.getOpenModernEntityDashboardUrl=b3;function v3(e,t,r,n){return`${e}main.aspx?appSolutionId=%7b${t}%7d&extraqs=etc=${r||""}`+(n?`%26id=${n}`:"")+"&pagetype=vizdesigner"}A.getChartDesignerUrl=v3;function w3(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=w3;function C3(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=C3;function E3(e,t){return`${e}Tools/ProcessControl/UnifiedProcessDesigner.aspx?id=${t}`}A.getBusinessProcessFlowDesignerUrl=E3;function A3(e,t,r){return`${e}CRMReports/reportproperty.aspx?appSolutionId=%7b${r}%7d&disablePersonal=true&id=%7b${t}%7d`}A.getReportDesignerUrl=A3;function S3(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=S3;function N3(e,t){return`${e}WebResources/${t}`}A.getWebResourceFileUrl=N3;function _3(e,t,r){return`${e}designer/sitemap/${r}/${t}/SiteMapHome/${t}`}A.getSiteMapDesignerUrl=_3;function T3(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=T3;function D3(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=D3;function I3(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=I3;function O3(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=O3;function P3(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=P3;function R3(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=R3;function k3(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=k3;function L3(e){return`${e}tools/publisher/edit.aspx`}A.getCreateNewPublisherUrl=L3;function $3(e,t){return`${e}tools/kbtemplateeditor/kbtemplateeditor.aspx?appSolutionId=${t}`}A.getCreateNewArticleTemplateUrl=$3;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 x3(e,t){return`${A.xrmApiUrl}/RetrieveRequiredComponents(ObjectId=${e},ComponentType=${t})`}A.getRequiredComponentsQueryUrl=x3;function F3(e,t){return`${A.cdsServiceUrl}${A.xrmApiUrl}/RetrieveDependentComponentsWithMetadata(ObjectId=${e},ComponentType=${t})`}A.getDependentComponentsWithMetadataQueryUrl=F3;A.solutionsQueryUrl="/api/data/v9.0/solutions?$expand=publisherid&$filter=(isvisible eq true)";function M3(e){return`/api/data/v9.0/solutions?$expand=publisherid&$filter=(uniquename eq '${e}')`}A.getSolutionsByUniqueNameQueryUrl=M3;function U3(e){return`/api/data/v9.0/solutions(${e})?$expand=publisherid`}A.getSolutionQueryUrl=U3;function B3(e){return`${e}api/data/v9.1/ProvisionLanguageForUser`}A.getProvisionLanguageUrl=B3;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 q3(e,t,r,n=!1,i=!1,o=!1,a=!1,s=!1,l=!1,u=!1){return`/api/data/v9.1/deploymentstageruns- ?$select=artifactname,artifactversion,deploymentstagerunid,devenvironmentid,endtime,errormessage,${s?"_artifactid_value,isredeployment,":""}${n?"deploymentnotes,":""}operation,operationdetails,operationstatus,${l?"retrycount,":""}${i?"scheduledtime,":""}${u?"solutionid,":""}stagerunstatus,starttime,suboperation,targetenvironmentid,${o?"predeploymentstepnotes,":""}validationresults,${a?"approvalcomments,":""}_devdeploymentenvironment_value,_targetdeploymentenvironment_value- &$expand=deploymentstageid($select=deploymentstageid,name,_deploymentpipelineid_value),targetdeploymentenvironment($select=deploymentenvironmentid,environmentid,name),createdby($select=azureactivedirectoryobjectid,fullname,ownerid,systemuserid)${l?",RetryUser($select=azureactivedirectoryobjectid,fullname,ownerid,systemuserid)":""}- &$filter=deploymentstageid/_deploymentpipelineid_value eq ${e} and devenvironmentid eq '${t}' and artifactname eq '${r}' and ((operation ne 200000201) or (operation eq 200000201 and operationstatus eq 200000003))- &$orderby=starttime desc`}A.getDeploymentStageRunsUrl=q3;function V3(e,t,r){return`/api/data/v9.1/RetrieveDeploymentPipelineInfo(DeploymentPipelineId=${e},SourceEnvironmentId='${t}',ArtifactName='${r}')`}A.retrieveDeploymentPipelineInfoUrl=V3;function G3(e){return`/api/data/v9.0/deploymentenvironments+var p6=Object.create;var lh=Object.defineProperty;var m6=Object.getOwnPropertyDescriptor;var h6=Object.getOwnPropertyNames;var g6=Object.getPrototypeOf,y6=Object.prototype.hasOwnProperty;var B=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(r){throw n=[r],r}};var C=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(n){throw t=0,n}},Fi=(e,t)=>{for(var n in t)lh(e,n,{get:t[n],enumerable:!0})},uh=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of h6(t))!y6.call(e,i)&&i!==n&&lh(e,i,{get:()=>t[i],enumerable:!(r=m6(t,i))||r.enumerable});return e},Os=(e,t,n)=>(uh(e,t,"default"),n&&uh(n,t,"default")),Xe=(e,t,n)=>(n=e!=null?p6(g6(e)):{},uh(t||!e||!e.__esModule?lh(n,"default",{value:e,enumerable:!0}):n,e)),_i=e=>uh(lh({},"__esModule",{value:!0}),e);var Ds=C(L=>{"use strict";Object.defineProperty(L,"__esModule",{value:!0});L.DateTimeBehavior=L.PrecisionSource=L.StringFormatName=L.SourceType=L.ImeMode=L.SolutionEntityTypeCodeExtToComponentTypeCode=L.SolutionComponentTypeCodeToEntityTypeCodeExt=L.SolutionComponentVirtualAttributeSubtype=L.EntityTypeCode=L.SolutionComponentTypeCodeExt=L.RootComponentBehavior=L.SolutionComponentTypeCode=L.EntityKeyIndexStatus=L.ViewStateCode=L.ViewStatusCode=L.RelationshipSecurityTypes=L.CascadeType=L.RelationshipTypeExt=L.RelationshipType=L.AppSubType=L.BusinessProcessType=L.WorkflowCategory=L.WorkflowScope=L.WorkflowTypeCode=L.StatusCodeEnabledDisabled=L.StateCodeEnabledDisabled=L.StatusCode=L.StateCode=L.OptionSetType=L.AttributeTypeCodeNum=L.AttributeFormatName=L.AttributeFormatCode=L.AttributeTypeName=L.AttributeTypeCode=L.PluginSourceType=L.AuthType=L.PluginIsolationMode=L.ComponentState=L.ChartType=L.ChartsType=L.ViewType=L.AttributeType=L.ActivationState=L.FormPresentation=L.FormType=L.TableTypeCode=L.TableTypes=L.ActivityTypeMask=L.PrincipalType=L.OwnershipTypes=void 0;L.QueryType=L.KnownCustomSolutionComponentEntitySetName=L.TeamTypeEnum=L.EnvironmentVariableDefinitionTypeEnum=L.ConnectorTypeEnum=L.RoleInheritance=L.DefaultRoleTemplates=L.DeleteDependencyErrorCode=L.ServiceEndpointConnectionMode=L.ServiceEndpointContract=L.ServiceNamespaceFormat=L.ConnectionRoleCategory=L.ReportTypeCode=L.SdkMessageProcessingMode=L.SupportedDeployment=L.SdkMessageProcessingStage=L.WebResourceTypeCode=L.IntegerFormat=L.DateTimeFormat=void 0;var fT;(function(e){e.None="None",e.UserOwned="UserOwned",e.TeamOwned="TeamOwned",e.BusinessOwned="BusinessOwned",e.OrganizationOwned="OrganizationOwned",e.BusinessParented="BusinessParented",e.Filtered="Filtered"})(fT||(L.OwnershipTypes=fT={}));var pT;(function(e){e.User="Microsoft.Dynamics.CRM.systemuser",e.Team="Microsoft.Dynamics.CRM.team"})(pT||(L.PrincipalType=pT={}));var mT;(function(e){e[e.DoNotDisplayInActivityMenus=0]="DoNotDisplayInActivityMenus",e[e.DisplayInActivityMenus=1]="DisplayInActivityMenus"})(mT||(L.ActivityTypeMask=mT={}));var hT;(function(e){e.Activity="Activity",e.Virtual="Virtual",e.Standard="Standard",e.Elastic="Elastic"})(hT||(L.TableTypes=hT={}));var gT;(function(e){e.Standard="Standard",e.Virtual="Virtual",e.Elastic="Elastic"})(gT||(L.TableTypeCode=gT={}));var yT;(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"})(yT||(L.FormType=yT={}));var bT;(function(e){e[e.ClassicForm=0]="ClassicForm",e[e.AirForm=1]="AirForm",e[e.ConvertedICForm=2]="ConvertedICForm"})(bT||(L.FormPresentation=bT={}));var vT;(function(e){e[e.Inactive=0]="Inactive",e[e.Active=1]="Active"})(vT||(L.ActivationState=vT={}));var wT;(function(e){e[e.String=0]="String",e[e.Number=1]="Number",e[e.Picklist=2]="Picklist"})(wT||(L.AttributeType=wT={}));var ET;(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"})(ET||(L.ViewType=ET={}));var AT;(function(e){e[e.ASPChart=0]="ASPChart",e[e.PowerBI=1]="PowerBI"})(AT||(L.ChartsType=AT={}));var CT;(function(e){e[e.DataAndInteractionCentric=0]="DataAndInteractionCentric",e[e.InteractionCentric=1]="InteractionCentric"})(CT||(L.ChartType=CT={}));var ST;(function(e){e[e.Published=0]="Published",e[e.Unpublished=1]="Unpublished",e[e.Deleted=2]="Deleted",e[e.DeletedUnpublished=3]="DeletedUnpublished"})(ST||(L.ComponentState=ST={}));var NT;(function(e){e[e.None=1]="None",e[e.Sandbox=2]="Sandbox",e[e.External=3]="External"})(NT||(L.PluginIsolationMode=NT={}));var _T;(function(e){e[e.BasicAuth=0]="BasicAuth"})(_T||(L.AuthType=_T={}));var IT;(function(e){e[e.Database=0]="Database",e[e.Disk=1]="Disk",e[e.Normal=2]="Normal",e[e.AzureWebApp=3]="AzureWebApp"})(IT||(L.PluginSourceType=IT={}));var TT;(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"})(TT||(L.AttributeTypeCode=TT={}));var OT;(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"})(OT||(L.AttributeTypeName=OT={}));var DT;(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"})(DT||(L.AttributeFormatCode=DT={}));var PT;(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"})(PT||(L.AttributeFormatName=PT={}));var RT;(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"})(RT||(L.AttributeTypeCodeNum=RT={}));var kT;(function(e){e.Picklist="Picklist",e.State="State",e.Status="Status",e.Boolean="Boolean"})(kT||(L.OptionSetType=kT={}));var $T;(function(e){e[e.Draft=0]="Draft",e[e.Activated=1]="Activated"})($T||(L.StateCode=$T={}));var LT;(function(e){e[e.Draft=1]="Draft",e[e.Activated=2]="Activated"})(LT||(L.StatusCode=LT={}));var MT;(function(e){e[e.Enabled=0]="Enabled",e[e.Disabled=1]="Disabled"})(MT||(L.StateCodeEnabledDisabled=MT={}));var xT;(function(e){e[e.Enabled=1]="Enabled",e[e.Disabled=2]="Disabled"})(xT||(L.StatusCodeEnabledDisabled=xT={}));var FT;(function(e){e[e.Definition=1]="Definition",e[e.Activation=2]="Activation",e[e.Template=3]="Template"})(FT||(L.WorkflowTypeCode=FT={}));var UT;(function(e){e[e.User=1]="User",e[e.BusinessUnit=2]="BusinessUnit",e[e.ParentChildBusinessUnit=3]="ParentChildBusinessUnit",e[e.Organization=4]="Organization"})(UT||(L.WorkflowScope=UT={}));var qT;(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"})(qT||(L.WorkflowCategory=qT={}));var BT;(function(e){e[e.None=-1]="None",e[e.BusinessFlow=0]="BusinessFlow",e[e.TaskFlow=1]="TaskFlow"})(BT||(L.BusinessProcessType=BT={}));var VT;(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"})(VT||(L.AppSubType=VT={}));var GT;(function(e){e.OneToManyRelationship="OneToManyRelationship",e.ManyToManyRelationship="ManyToManyRelationship"})(GT||(L.RelationshipType=GT={}));var jT;(function(e){e.ManyToOneRelationship="ManyToOneRelationship",e.OneToManyRelationship="OneToManyRelationship",e.ManyToManyRelationship="ManyToManyRelationship"})(jT||(L.RelationshipTypeExt=jT={}));var WT;(function(e){e.NoCascade="NoCascade",e.Cascade="Cascade",e.Active="Active",e.UserOwned="UserOwned",e.RemoveLink="RemoveLink",e.Restrict="Restrict"})(WT||(L.CascadeType=WT={}));var zT;(function(e){e.None="None",e.Append="Append",e.ParentChild="ParentChild",e.Pointer="Pointer",e.Inheritance="Inheritance"})(zT||(L.RelationshipSecurityTypes=zT={}));var HT;(function(e){e[e.Active=1]="Active",e[e.Inactive=2]="Inactive"})(HT||(L.ViewStatusCode=HT={}));var KT;(function(e){e[e.Active=0]="Active",e[e.Inactive=1]="Inactive"})(KT||(L.ViewStateCode=KT={}));var JT;(function(e){e.Active="Active",e.Failed="Failed",e.InProgress="InProgress",e.Pending="Pending"})(JT||(L.EntityKeyIndexStatus=JT={}));var YT;(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"})(YT||(L.SolutionComponentTypeCode=YT={}));var QT;(function(e){e[e.IncludeSubcomponents=0]="IncludeSubcomponents",e[e.DoNotIncludeSubcomponents=1]="DoNotIncludeSubcomponents",e[e.IncludeAsShellOnly=2]="IncludeAsShellOnly"})(QT||(L.RootComponentBehavior=QT={}));var ch;(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"})(ch||(L.SolutionComponentTypeCodeExt=ch={}));var dh;(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"})(dh||(L.EntityTypeCode=dh={}));var XT;(function(e){e.MultiSelectPicklist="MultiSelectPicklist",e.File="File",e.Image="Image"})(XT||(L.SolutionComponentVirtualAttributeSubtype=XT={}));function b6(e){let t=ch[e];return dh[t]}L.SolutionComponentTypeCodeToEntityTypeCodeExt=b6;function v6(e){let t=dh[e];return ch[t]}L.SolutionEntityTypeCodeExtToComponentTypeCode=v6;var ZT;(function(e){e.Active="Active",e.Auto="Auto",e.Disabled="Disabled",e.Inactive="Inactive"})(ZT||(L.ImeMode=ZT={}));var eO;(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"})(eO||(L.SourceType=eO={}));var tO;(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"})(tO||(L.StringFormatName=tO={}));var nO;(function(e){e[e.PrecisionProperty=0]="PrecisionProperty",e[e.Organization=1]="Organization",e[e.TransactionCurrency=2]="TransactionCurrency"})(nO||(L.PrecisionSource=nO={}));var rO;(function(e){e.UserLocal="UserLocal",e.DateOnly="DateOnly",e.TimeZoneIndependent="TimeZoneIndependent"})(rO||(L.DateTimeBehavior=rO={}));var iO;(function(e){e.DateOnly="DateOnly",e.DateAndTime="DateAndTime"})(iO||(L.DateTimeFormat=iO={}));var oO;(function(e){e.None="None",e.Duration="Duration",e.TimeZone="TimeZone",e.Language="Language",e.Locale="Locale"})(oO||(L.IntegerFormat=oO={}));var aO;(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"})(aO||(L.WebResourceTypeCode=aO={}));var sO;(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"})(sO||(L.SdkMessageProcessingStage=sO={}));var uO;(function(e){e[e.ServerOnly=0]="ServerOnly",e[e.OutlookClientOnly=1]="OutlookClientOnly",e[e.Both=2]="Both"})(uO||(L.SupportedDeployment=uO={}));var lO;(function(e){e[e.Synchronous=0]="Synchronous",e[e.Asynchronous=1]="Asynchronous"})(lO||(L.SdkMessageProcessingMode=lO={}));var cO;(function(e){e[e.ReportingServicesReport=1]="ReportingServicesReport",e[e.OtherReport=2]="OtherReport",e[e.LinkedReport=3]="LinkedReport"})(cO||(L.ReportTypeCode=cO={}));var dO;(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"})(dO||(L.ConnectionRoleCategory=dO={}));var fO;(function(e){e[e.Name=1]="Name",e[e.Address=2]="Address"})(fO||(L.ServiceNamespaceFormat=fO={}));var pO;(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"})(pO||(L.ServiceEndpointContract=pO={}));var mO;(function(e){e[e.Normal=1]="Normal",e[e.Federated=2]="Federated"})(mO||(L.ServiceEndpointConnectionMode=mO={}));var hO;(function(e){e.CannotDeleteInUseComponent="0x8004f01f",e.CannotDeleteInUseAttribute="0x80048418",e.CannotDeleteInUseOptionSet="0x80048417",e.CannotDeleteInUseEntity="0x80048420",e.CannotUninstallWithDependencies="0x8004F01D"})(hO||(L.DeleteDependencyErrorCode=hO={}));var gO;(function(e){e.SystemAdministrator="627090FF-40A3-4053-8790-584EDC5BE201",e.SystemCustomizer="119F245C-3CC8-4B62-B31C-D1A046CED15D"})(gO||(L.DefaultRoleTemplates=gO={}));var yO;(function(e){e[e.DefaultTeamPrivilege=0]="DefaultTeamPrivilege",e[e.DirectUserAndTeamPrivilege=1]="DirectUserAndTeamPrivilege"})(yO||(L.RoleInheritance=yO={}));var bO;(function(e){e[e.NotSpecified=0]="NotSpecified",e[e.CustomConnector=1]="CustomConnector"})(bO||(L.ConnectorTypeEnum=bO={}));var vO;(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"})(vO||(L.EnvironmentVariableDefinitionTypeEnum=vO={}));var wO;(function(e){e[e.Owner=0]="Owner",e[e.Access=1]="Access",e[e.AADSecurityGroup=2]="AADSecurityGroup",e[e.AADOfficeGroup=3]="AADOfficeGroup"})(wO||(L.TeamTypeEnum=wO={}));var EO;(function(e){e.Bots="bots"})(EO||(L.KnownCustomSolutionComponentEntitySetName=EO={}));var AO;(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"})(AO||(L.QueryType=AO={}))});var Y=C(Z=>{"use strict";Object.defineProperty(Z,"__esModule",{value:!0});Z.PromotionError=Z.UpsertOutcomeUnknownError=Z.DataFixColumnsInvalidError=Z.DataFixError=Z.DateTimeBehaviorMissingError=Z.TableSearchNotAllowedError=Z.InspectionUnreadableError=Z.COMMAND_IMMUTABLE_COLUMN_CHANGED_CODE=Z.INSPECTION_UNREADABLE_CODE=Z.INSPECTION_NOT_SUPPORTED_CODE=Z.ArtifactInUseError=Z.AppThemeError=Z.IncompatibleWorkspaceError=Z.PathTraversalError=Z.AmbiguousArtifactError=Z.JsonPointerError=Z.NotImplementedError=Z.WorkspaceOrgMismatchError=Z.WorkspaceNotInitializedError=Z.attachCause=Z.WebResourceUnverifiedError=Z.ConnectionError=Z.VersionConflictError=Z.LocalEditsWouldBeLostError=Z.StaleArtifactError=Z.InvalidArgumentError=Z.ValidationError=Z.PathNotFoundError=Z.ArtifactNotFoundError=Z.readCleanupWarnings=Z.withCleanupWarnings=Z.readPartialEnrichment=Z.withPartialEnrichment=Z.readPartialTokens=Z.withPartialTokens=Z.SdkError=void 0;var yt=class extends Error{constructor(t,n){super(n),this.code=t,Object.setPrototypeOf(this,new.target.prototype),this.name=new.target.name}};Z.SdkError=yt;var CO=Symbol.for("cds-maker-sdk.partialWriteTokens");function w6(e,t){return typeof e=="object"&&e!==null&&(e[CO]=t),e}Z.withPartialTokens=w6;function E6(e){return Sv(e,CO)}Z.readPartialTokens=E6;function Sv(e,t){let n=e;for(let r=0;n&&typeof n=="object"&&r<8;r++){let i=n[t];if(i&&typeof i=="object")return i;n=n.cause}}var SO=Symbol.for("cds-maker-sdk.partialDefaultViewEnrichment");function A6(e,t){return typeof e=="object"&&e!==null&&(e[SO]=t),e}Z.withPartialEnrichment=A6;function C6(e){return Sv(e,SO)}Z.readPartialEnrichment=C6;var Zb=Symbol.for("cds-maker-sdk.cleanupWarnings");function S6(e,t){if(typeof e=="object"&&e!==null&&t.length>0){let n=e,r=n[Zb];n[Zb]=[...Array.isArray(r)?r:[],...t]}return e}Z.withCleanupWarnings=S6;function N6(e){let t=Sv(e,Zb);return t?[...t]:void 0}Z.readCleanupWarnings=N6;var ev=class extends yt{constructor(t,n){super("ARTIFACT_NOT_FOUND",`Artifact ${t}/${n} not found in workspace`),this.type=t,this.id=n}};Z.ArtifactNotFoundError=ev;var tv=class extends yt{constructor(t,n,r){super("PATH_NOT_FOUND",`Path ${r} not found in ${t}/${n}`),this.type=t,this.id=n,this.pointer=r}};Z.PathNotFoundError=tv;var nv=class extends yt{constructor(t,n,r,i){var o,a,s,u;let l=Array.isArray(r)?r:[{pointer:r,rule:i??"invalid",message:i??"invalid"}];super("VALIDATION_ERROR",`Validation failed for ${t}/${n}:+`+l.map(c=>` \u2022 ${c.pointer}: ${c.message} [${c.rule}]`).join(`+`)),this.type=t,this.id=n,this.issues=l,this.pointer=(a=(o=l[0])===null||o===void 0?void 0:o.pointer)!==null&&a!==void 0?a:"",this.rule=(u=(s=l[0])===null||s===void 0?void 0:s.rule)!==null&&u!==void 0?u:"invalid"}};Z.ValidationError=nv;var rv=class extends yt{constructor(t){super("INVALID_ARGUMENT",t)}};Z.InvalidArgumentError=rv;var iv=class extends yt{constructor(t,n,r,i="revalidated"){super("STALE_ARTIFACT",i==="pushed"?`Cannot apply the edit at ${r} to ${t}/${n}: 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 ${r} to ${t}/${n}: 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=n,this.pointer=r,this.reason=i}};Z.StaleArtifactError=iv;var ov=class extends yt{constructor(t,n,r,i){super("LOCAL_EDITS_WOULD_BE_LOST",`Refusing to fetch ${t}/${n}: the local copy has unpushed edits AND the server has moved since it was fetched (local=${r??"(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=n,this.localEtag=r,this.serverEtag=i}};Z.LocalEditsWouldBeLostError=ov;var av=class extends yt{constructor(t,n,r,i,o){super("VERSION_CONFLICT",`Version conflict for ${t}/${n}: local=${r??"(none)"}, server=${i??"(none)"}. Re-fetch and reapply changes.${o?` ${o}`:""}`),this.type=t,this.id=n,this.localEtag=r,this.serverEtag=i,this.detail=o}};Z.VersionConflictError=av;var sv=class extends yt{constructor(t,n,r,i){super("CONNECTION_ERROR",n>0?`HTTP ${n} from ${t}: ${r}`:`Transport failure reaching ${t}: ${r}`),this.url=t,this.statusCode=n,Object.defineProperty(this,"cause",{value:i,enumerable:!1,writable:!1,configurable:!0})}};Z.ConnectionError=sv;var uv=class extends yt{constructor(t,n,r){super("WEB_RESOURCE_UNVERIFIED",r),this.id=t,this.webResourceName=n}};Z.WebResourceUnverifiedError=uv;function NO(e,t){return typeof e=="object"&&e!==null&&Object.defineProperty(e,"cause",{value:t,enumerable:!1,writable:!0,configurable:!0}),e}Z.attachCause=NO;var lv=class extends yt{constructor(t){super("WORKSPACE_NOT_INITIALIZED",`Workspace not initialized at ${t}. Call initWorkspace() first.`),this.workspacePath=t}};Z.WorkspaceNotInitializedError=lv;var cv=class extends yt{constructor(t,n){super("WORKSPACE_ORG_MISMATCH",`This workspace belongs to ${t?`'${t}'`:"no recorded org"}, but this SDK targets '${n}'. 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 '${n}'.`),this.workspaceInstanceUrl=t,this.instanceUrl=n}};Z.WorkspaceOrgMismatchError=cv;var dv=class extends yt{constructor(t,n){super("NOT_IMPLEMENTED",`Operation '${t}' is not implemented yet${n?`: ${n}`:""}.`),this.operation=t}};Z.NotImplementedError=dv;var fv=class extends yt{constructor(t,n){super("INVALID_JSON_POINTER",`Invalid JSON Pointer '${t}': ${n}`),this.pointer=t}};Z.JsonPointerError=fv;var pv=class extends yt{constructor(t,n,r){super("AMBIGUOUS_ARTIFACT",`Found ${r} ${t} rows matching '${n}'; a name is not a unique key. Resolve by id / alternate key instead of relying on name-based idempotency.`),this.kind=t,this.identity=n,this.matchCount=r}};Z.AmbiguousArtifactError=pv;var mv=class extends yt{constructor(t,n){super("PATH_TRAVERSAL",`Refusing to resolve a path outside the workspace root: '${t}' is not within '${n}'.`),this.target=t,this.root=n}};Z.PathTraversalError=mv;var hv=class extends yt{constructor(t,n){super("INCOMPATIBLE_WORKSPACE",`Workspace schema version ${t} is newer than this SDK supports (v${n}). Upgrade the SDK, or re-create the workspace with this version.`),this.workspaceVersion=t,this.supportedVersion=n}};Z.IncompatibleWorkspaceError=hv;var gv=class extends yt{constructor(t,n,r,i){super(t,r),this.appId=n,this.webResourceName=i}};Z.AppThemeError=gv;var yv=class extends yt{constructor(t,n,r,i){super("ARTIFACT_IN_USE",r),this.type=t,this.id=n,this.dependents=i}};Z.ArtifactInUseError=yv;Z.INSPECTION_NOT_SUPPORTED_CODE="INSPECTION_NOT_SUPPORTED";Z.INSPECTION_UNREADABLE_CODE="INSPECTION_UNREADABLE";Z.COMMAND_IMMUTABLE_COLUMN_CHANGED_CODE="COMMAND_IMMUTABLE_COLUMN_CHANGED";var bv=class extends yt{constructor(t,n,r,i){super(Z.INSPECTION_UNREADABLE_CODE,`Cannot inspect ${t} '${n}': ${i} Nothing is reported \u2014 re-run the inspection; a partial read is never returned.`),this.type=t,this.id=n,this.statusCode=r}};Z.InspectionUnreadableError=bv;var vv=class extends yt{constructor(t){super("TABLE_SEARCH_NOT_ALLOWED",`Table '${t}' cannot be included in Dataverse search: its managed property CanEnableSyncToExternalSearchIndex is false (a solution-layer decision). Nothing was written.`),this.entityLogicalName=t}};Z.TableSearchNotAllowedError=vv;var wv=class extends yt{constructor(t,n){let r=n.map(o=>`'${o}'`).join(", "),i=n.map(o=>`updateColumn('${t}', '${o}', { dateTimeBehavior: 'UserLocal' })`).join(", then ");super("DATETIME_BEHAVIOR_MISSING",`Dataverse refused a new column or lookup on '${t}' (0x80048550) because its Date and Time column(s) ${r} have no DateTimeBehavior \u2014 an earlier createTable created them that way. Repair each with ${i} \u2014 UserLocal is how their values are already stored \u2014 then retry. Nothing was created by the refused request.`),this.table=t,this.columns=[...n]}};Z.DateTimeBehaviorMissingError=wv;var fh=class extends yt{constructor(t,n,r,i,o){super(t,n),this.httpStatus=r,this.path=i,this.maxRows=o}};Z.DataFixError=fh;var Ev=class extends fh{constructor(t){super("DATA_FIX_COLUMNS_INVALID",`The data fix cannot write ${t.length} column issue(s): `+t.map(n=>`${n.column} (${n.reason})`).join(", ")),this.issues=t}};Z.DataFixColumnsInvalidError=Ev;var Av=class extends yt{constructor(t,n,r,i,o,a){super("UPSERT_OUTCOME_UNKNOWN",o),this.entityLogicalName=t,this.key=n,this.statusCode=r,this.serverCode=i,NO(this,a)}};Z.UpsertOutcomeUnknownError=Av;var Cv=class extends yt{constructor(t){super(t.code,t.message),this.problem=t}};Z.PromotionError=Cv});var ae=C(pn=>{"use strict";Object.defineProperty(pn,"__esModule",{value:!0});pn.odataQuery=pn.normalizeGuid=pn.createSafeXmlElement=pn.assertNoControlChars=pn.assertODataName=pn.assertXmlName=pn.xmlText=pn.odataPathLiteral=pn.odataLiteral=void 0;var ph=Y();function _O(e){return String(e??"").replace(/'/g,"''")}pn.odataLiteral=_O;function _6(e){return encodeURIComponent(_O(e))}pn.odataPathLiteral=_6;function I6(e){return String(e??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}pn.xmlText=I6;function IO(e,t){let n=String(e??""),r=/^[A-Za-z_][0-9A-Za-z_.-]*$/,i=n.split(":");if(!(i.length<=2&&i.every(a=>r.test(a))&&!/^xmlns/i.test(n)))throw new ph.InvalidArgumentError(`${t} must be a valid XML element name (got '${e}')`);return e}pn.assertXmlName=IO;function T6(e,t){let n=String(e??"");if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(n))throw new ph.InvalidArgumentError(`${t} must be a valid OData identifier (letters, digits, underscore): got '${e}'`);return e}pn.assertODataName=T6;function O6(e,t){if(/[\u0000-\u001F\u007F]/.test(String(e??"")))throw new ph.InvalidArgumentError(`${t} must not contain control characters (including CR/LF): they would inject additional lines into the request`);return e}pn.assertNoControlChars=O6;function D6(e,t,n){return e.createElement(IO(t,n))}pn.createSafeXmlElement=D6;var P6=/^[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 R6(e,t){let n=String(e??""),r=n.length===38&&n.startsWith("{")&&n.endsWith("}")?n.slice(1,-1):n;if(!P6.test(r))throw new ph.InvalidArgumentError(`${t} must be a valid GUID (got '${e}')`);return r.toLowerCase()}pn.normalizeGuid=R6;function k6(e){let t=[];for(let[n,r]of e)r!=null&&r!==""&&t.push(`${n}=${encodeURIComponent(String(r))}`);return t.length>0?`?${t.join("&")}`:""}pn.odataQuery=k6});var pe=C(K=>{"use strict";Object.defineProperty(K,"__esModule",{value:!0});K.throttleDelayMs=K.THROTTLE_FALLBACK_DELAY_MS=K.isServiceProtectionRefusal=K.SERVICE_PROTECTION_CODES=K.nowIso=K.isAlreadyDeleted=K.deleteRecord=K.extractErrorMessage=K.resendAppSearchIndexRace=K.resendDeadlockVictim=K.resendWhile=K.sleep=K.isAppSearchIndexRace=K.namesAppSearchIndexRace=K.isTransactionNotStarted=K.TRANSACTION_NOT_STARTED_CODE=K.LOCK_BACKOFF_MS=K.isConcurrencyLockRefusalError=K.isConcurrencyLockRefusal=K.CONCURRENCY_LOCK_CODE=K.AMBIGUOUS_WRITE_STATUSES=K.DEADLOCK_BACKOFF_MS=K.isSqlDeadlockVictim=K.ensureSuccess=K.resolveCreatedId=K.requireCreatedId=K.withClientMintedId=K.readCreatedId=K.readRowEtag=K.readEtag=K.requireEtag=K.isVersionToken=K.echoWrite=K.DELETE_NO_ETAG_CODE=K.UPDATE_NO_ETAG_CODE=K.VERSION_CONFLICT_CODE=void 0;var Mu=Y(),Xl=ae();K.VERSION_CONFLICT_CODE="VERSION_CONFLICT";K.UPDATE_NO_ETAG_CODE="ARTIFACT_UPDATE_NO_ETAG";K.DELETE_NO_ETAG_CODE="ARTIFACT_DELETE_NO_ETAG";function $6(e,t){return{query:`?$select=${encodeURIComponent(e)}`,options:{headers:{...t??{},Prefer:"return=representation"}}}}K.echoWrite=$6;function TO(e){return typeof e=="string"&&e.trim()!==""&&e.trim()!=="*"}K.isVersionToken=TO;function L6(e,t,n){if(!TO(e))throw new Mu.SdkError(K.UPDATE_NO_ETAG_CODE,`Refusing to push ${t} '${n}': ${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}K.requireEtag=L6;function OO(e){var t;let n=(t=e.headers)!==null&&t!==void 0?t:{};for(let i of Object.keys(n))if(i.toLowerCase()==="etag")return n[i];let r=e.body;return r&&typeof r["@odata.etag"]=="string"?r["@odata.etag"]:null}K.readEtag=OO;async function M6(e,t,n,r){let i=`/${t}(${r})${(0,Xl.odataQuery)([["$select",n]])}`;return OO(_v(await e.get(i),e.apiUrl(i)))}K.readRowEtag=M6;function Nv(e,t){var n;let r=e.body;if(r&&typeof r[t]=="string")return(0,Xl.normalizeGuid)(r[t],t);let i=(n=e.headers)!==null&&n!==void 0?n:{};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,Xl.normalizeGuid)(a[1],t)}return null}K.readCreatedId=Nv;function x6(e,t,n){return n?{...e,[t]:(0,Xl.normalizeGuid)(n,t)}:e}K.withClientMintedId=x6;function F6(e,t,n){let r=Nv(e,t);if(!r)throw new Mu.InvalidArgumentError(`Dataverse did not return an id for the created ${n}`);return r}K.requireCreatedId=F6;function U6(e,t,n,r){let i=Nv(e,t);if(i)return i;if(r)return(0,Xl.normalizeGuid)(r,t);throw new Mu.InvalidArgumentError(`Dataverse did not return an id for the created ${n}`)}K.resolveCreatedId=U6;function _v(e,t){if(e.status===412)throw new Mu.SdkError(K.VERSION_CONFLICT_CODE,`Version conflict (412) from ${t}`);if(e.status<200||e.status>=300)throw new Mu.ConnectionError(t,e.status,LO(e.body),e.body);return e}K.ensureSuccess=_v;function DO(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)}K.isSqlDeadlockVictim=DO;K.DEADLOCK_BACKOFF_MS=[1e3,2e3,4e3];K.AMBIGUOUS_WRITE_STATUSES=new Set([408,502,503,504]);K.CONCURRENCY_LOCK_CODE="0x80071151";function PO(e){var t,n;if(e.status!==429)return!1;let r=(n=(t=e.body)===null||t===void 0?void 0:t.error)===null||n===void 0?void 0:n.code;return typeof r=="string"&&r.toLowerCase()===K.CONCURRENCY_LOCK_CODE}K.isConcurrencyLockRefusal=PO;function q6(e){return e instanceof Mu.ConnectionError&&e.statusCode===429&&PO({status:429,headers:{},body:e.cause})}K.isConcurrencyLockRefusalError=q6;K.LOCK_BACKOFF_MS=[2e3,3e3,...Array.from({length:35},()=>5e3)];K.TRANSACTION_NOT_STARTED_CODE="0x80040251";function B6(e){var t,n;if(e.status!==500)return!1;let r=(n=(t=e.body)===null||t===void 0?void 0:t.error)===null||n===void 0?void 0:n.code;return typeof r=="string"&&r.toLowerCase()===K.TRANSACTION_NOT_STARTED_CODE}K.isTransactionNotStarted=B6;var V6=/(?:^|[^a-z0-9_])AppModule_DVTableSearch_M365AppModuleId(?![a-z0-9_])/i;function RO(e){return V6.test(e)&&/\bSql Number:\s*547\b/i.test(e)}K.namesAppSearchIndexRace=RO;function kO(e){return e.status!==400||e.body===void 0||e.body===null?!1:RO(typeof e.body=="string"?e.body:JSON.stringify(e.body))}K.isAppSearchIndexRace=kO;function $O(e){return new Promise(t=>setTimeout(t,e))}K.sleep=$O;async function Iv(e,t,n=K.DEADLOCK_BACKOFF_MS){for(let r=0;;r+=1){let i=await t();if(r>=n.length||!e(i))return i;await $O(n[r])}}K.resendWhile=Iv;function G6(e){return Iv(DO,e,K.DEADLOCK_BACKOFF_MS)}K.resendDeadlockVictim=G6;function j6(e){return Iv(kO,e,K.DEADLOCK_BACKOFF_MS)}K.resendAppSearchIndexRace=j6;function LO(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"}K.extractErrorMessage=LO;async function W6(e,t,n,r){let i=(0,Xl.normalizeGuid)(n,"id"),o=`/${t}(${i})`;_v(await e.delete(o,r?{headers:{"If-Match":r}}:void 0),e.apiUrl(o))}K.deleteRecord=W6;function z6(e){return e instanceof Mu.ConnectionError&&e.statusCode===404}K.isAlreadyDeleted=z6;function H6(){return new Date().toISOString()}K.nowIso=H6;K.SERVICE_PROTECTION_CODES=new Set(["0x80072322","0x80072321","0x80072326"]);function K6(e){var t,n;if(e.status!==429)return!1;let r=(n=(t=e.body)===null||t===void 0?void 0:t.error)===null||n===void 0?void 0:n.code;return typeof r=="string"&&K.SERVICE_PROTECTION_CODES.has(r.toLowerCase())}K.isServiceProtectionRefusal=K6;K.THROTTLE_FALLBACK_DELAY_MS=5e3;function J6(e){var t;let n=(t=e.headers)!==null&&t!==void 0?t:{},r=Object.keys(n).find(o=>o.toLowerCase()==="retry-after"),i=r===void 0?"":String(n[r]).trim();return/^\d+$/.test(i)?Math.max(Number(i),1)*1e3:K.THROTTLE_FALLBACK_DELAY_MS}K.throttleDelayMs=J6});var Ke=C(Un=>{"use strict";Object.defineProperty(Un,"__esModule",{value:!0});Un.describeMalformedValue=Un.boundedPageComplete=Un.pageEnd=Un.moreRecordsClaim=Un.MORE_RECORDS_ANNOTATION=Un.continuePages=Un.collectPages=void 0;var MO=pe(),Tv=Y();async function Y6(e,t,n,r,i){let o=e.apiUrl(t),a=(0,MO.ensureSuccess)(await e.get(t,i),o);return r?.(a),xO(e,a,o,n,i)}Un.collectPages=Y6;async function xO(e,t,n,r,i){let o=[],a=new Set,s=n,u=t;for(;;){let l=u.body,c=l?.value;if(!Array.isArray(c))throw new Tv.ConnectionError(s,u.status,`${r}: paginated read returned a malformed page \u2014 expected an OData 'value' array but got ${mh(c)}; refusing to return partial results.`);for(let p of c)o.push(p);let d=Ov(l);if(d.kind==="end")break;if(d.kind==="incomplete")throw new Tv.ConnectionError(s,u.status,`${r}: paginated read returned ${d.why}; cannot read the rest, and refusing to return partial results.`);let f=d.link;if(a.has(f))throw new Tv.InvalidArgumentError(`${r}: aborting pagination \u2014 the server returned a repeated @odata.nextLink ('${f}'), which would loop indefinitely.`);a.add(f),s=f,u=(0,MO.ensureSuccess)(await e.getAbsolute(f,i),f)}return o}Un.continuePages=xO;Un.MORE_RECORDS_ANNOTATION="@Microsoft.Dynamics.CRM.morerecords";function FO(e,t=""){let n=e!==null&&typeof e=="object"?e[`${t}${Un.MORE_RECORDS_ANNOTATION}`]:void 0;return n==null||n===!1?"none":n===!0?"more":"malformed"}Un.moreRecordsClaim=FO;function Ov(e,t=""){let n=e!==null&&typeof e=="object"?e:{},r=`${t}@odata.nextLink`,i=n[r];if(i!=null)return typeof i=="string"&&i.length>0?{kind:"next",link:i}:{kind:"incomplete",cause:"link",why:`a malformed ${r} (${mh(i)})`};let o=`${t}${Un.MORE_RECORDS_ANNOTATION}`,a=FO(n,t);return a==="none"?{kind:"end"}:{kind:"incomplete",cause:"claim",why:a==="more"?`a page that says more rows exist (${o}) but gives no ${r} to read them`:`a malformed ${o} (${mh(n[o])})`}}Un.pageEnd=Ov;function Q6(e,t,n=1){return t>=n||Ov(e).kind==="end"}Un.boundedPageComplete=Q6;function mh(e){return e===null?"null":e===void 0?"undefined (missing)":`a ${typeof e}`}Un.describeMalformedValue=mh});var Dv=C(Fu=>{"use strict";Object.defineProperty(Fu,"__esModule",{value:!0});Fu.assertWorkflowKind=Fu.WORKFLOW_KIND_MISMATCH_CODE=void 0;var xu=Ds(),X6=Y(),UO=pe(),Z6=ae();Fu.WORKFLOW_KIND_MISMATCH_CODE="WORKFLOW_KIND_MISMATCH";var qO={[xu.WorkflowCategory.Workflow]:"classic workflow",[xu.WorkflowCategory.Dialog]:"dialog",[xu.WorkflowCategory.BusinessRule]:"business rule",[xu.WorkflowCategory.Action]:"custom action",[xu.WorkflowCategory.BusinessProcessFlow]:"business process flow",[xu.WorkflowCategory.Flow]:"cloud flow",[xu.WorkflowCategory.UIFlow]:"desktop flow"};async function eH(e,t,n){var r,i;let o=`/workflows(${t})${(0,Z6.odataQuery)([["$select","category"]])}`,a=await e.get(o);if(a.status===404)return null;(0,UO.ensureSuccess)(a,e.apiUrl(o));let s=(r=a.body)===null||r===void 0?void 0:r.category,u=typeof s=="number"?s:typeof s=="string"&&s!==""?Number(s):NaN;if(u!==n){let l=Number.isFinite(u)?`a ${(i=qO[u])!==null&&i!==void 0?i:"process"} (category ${u})`:"a process whose category could not be read";throw new X6.SdkError(Fu.WORKFLOW_KIND_MISMATCH_CODE,`Refusing to delete workflow '${t}' as a ${qO[n]}: it is ${l}. Nothing was changed. Check the id.`)}return(0,UO.readEtag)(a)}Fu.assertWorkflowKind=eH});var Rv=C(Ui=>{"use strict";Object.defineProperty(Ui,"__esModule",{value:!0});Ui.deleteWorkflowResending=Ui.isWorkflowDeleteUnsettled=Ui.failedAfterResend=Ui.WORKFLOW_DELETE_UNSETTLED_CODE=void 0;var bf=Y(),ka=pe(),VO=ae();Ui.WORKFLOW_DELETE_UNSETTLED_CODE="WORKFLOW_DELETE_UNSETTLED";var GO=new WeakSet;function Pv(e){return typeof e=="object"&&e!==null&&GO.add(e),e}function tH(e){return typeof e=="object"&&e!==null&&GO.has(e)}Ui.failedAfterResend=tH;function nH(e){return e instanceof bf.SdkError&&e.code===Ui.WORKFLOW_DELETE_UNSETTLED_CODE}Ui.isWorkflowDeleteUnsettled=nH;function rH(e,t){try{(0,ka.ensureSuccess)(e,t)}catch(n){return n}}function iH(e){return(0,ka.isSqlDeadlockVictim)(e)?"lost a SQL deadlock (HTTP 500, Sql Number 1205)":`lost its transaction (HTTP 500 ${ka.TRANSACTION_NOT_STARTED_CODE})`}async function BO(e,t){try{return(await e.get(`/workflows(${t})${(0,VO.odataQuery)([["$select","workflowid"]])}`)).status===404}catch{return!1}}async function oH(e,t,{bindingToken:n,kindName:r,deactivated:i=!1,resendDeadlockVictim:o=!1,ifMatchOnFirst:a=!1}){let s=(0,VO.normalizeGuid)(t,"id");if(a&&!n)throw new bf.InvalidArgumentError(`Refusing to delete ${r} '${s}': its delete must be conditional on a token this operation holds, and it holds none.`);let u=`/workflows(${s})`,l=e.apiUrl(u),c=m=>(0,ka.isTransactionNotStarted)(m)||o&&(0,ka.isSqlDeadlockVictim)(m),d=0,f,p;try{p=await(0,ka.resendWhile)(c,async()=>{d+=1;let m=d>1||a,h=await e.delete(u,m?{headers:{"If-Match":n}}:void 0);return f=f??h,h},n?ka.DEADLOCK_BACKOFF_MS:[])}catch(m){if(m instanceof bf.ConnectionError&&m.statusCode===0&&n&&await BO(e,s))return;throw d>1?Pv(m):m}if(!(d>1&&p.status===404)){if(d>1&&p.status===412){let m=iH(f),h=new bf.SdkError(Ui.WORKFLOW_DELETE_UNSETTLED_CODE,`Deleting ${r} '${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 Pv((0,bf.attachCause)(h,rH(f,l)))}if(!(n&&ka.AMBIGUOUS_WRITE_STATUSES.has(p.status)&&await BO(e,s)))try{(0,ka.ensureSuccess)(p,l)}catch(m){throw d>1?Pv(m):m}}}Ui.deleteWorkflowResending=oH});var qi=C(fr=>{"use strict";Object.defineProperty(fr,"__esModule",{value:!0});fr.existsByKey=fr.observeIfMatch=fr.readRowToken=fr.compareTokens=fr.failedReadStatus=fr.failureDetail=fr.planPushThrough=void 0;var hh=Y(),jO=pe(),kv=ae(),$v=class{constructor(t){this.sink=t,this.warnings=[]}observe(t){this.sink(t)}warn(t,n){this.warnings.push({code:t,message:n})}async reached(t,n){let r=n?await n():void 0;return this.projection={...t,...r!==void 0?{existence:r}:{}},{id:"",etag:null}}};async function aH(e,t,n,r){let i=new $v(r);if(n.held?await e.update(t,n.id,n.payload,n.held.etag,n.held.memberEtags,n.held.siblingEtags,i):await e.create(t,n.payload,n.id,i),!i.projection)throw new hh.SdkError("PREVIEW_PLAN_INCOMPLETE","A pre-push check ran a write path that returned without reaching its first write. This is a defect in the SDK.");return i.warnings.length>0?{...i.projection,warnings:i.warnings}:i.projection}fr.planPushThrough=aH;function Lv(e){return e instanceof hh.ConnectionError?`HTTP ${e.statusCode}: ${e.message}`:e instanceof hh.SdkError?`${e.code}: ${e.message}`:e instanceof Error?e.message:String(e)}fr.failureDetail=Lv;function sH(e){return e instanceof hh.ConnectionError&&e.statusCode===404?"goneOnServer":"readFailed"}fr.failedReadStatus=sH;function WO(e,t){return(0,jO.isVersionToken)(e)?typeof t!="string"||t===""?"missingServer":e===t?"equal":"different":"missingHeld"}fr.compareTokens=WO;async function zO(e,t){let n=`/${t.entitySet}(${t.id})${(0,kv.odataQuery)([["$select",t.idColumn]])}`,r;try{r=await e.get(n,t.headers?{headers:{...t.headers}}:void 0)}catch(i){return{kind:"failed",detail:Lv(i)}}return r.status===404?{kind:"notFound"}:r.status<200||r.status>=300?{kind:"failed",detail:`HTTP ${r.status}`}:{kind:"token",token:(0,jO.readEtag)(r)}}fr.readRowToken=zO;async function uH(e,t,n){var r;let i=await zO(e,n),o={guard:"ifMatch",componentName:n.componentName,componentId:n.id,held:(r=n.held)!==null&&r!==void 0?r:null};return i.kind==="notFound"?t.observe({...o,status:"goneOnServer",detail:"HTTP 404"}):i.kind==="failed"?t.observe({...o,status:"readFailed",detail:i.detail}):t.observe({...o,server:i.token,status:WO(n.held,i.token)}),i}fr.observeIfMatch=uH;async function lH(e,t,n){var r;let i=(0,kv.normalizeGuid)(n.id,n.key),o=`${n.collection}${(0,kv.odataQuery)([["$select",n.key],["$filter",`${n.key} eq ${i}`]])}`,a={guard:"existence",componentName:n.componentName,componentId:i};try{let s=await e.get(o,n.headers?{headers:{...n.headers}}:void 0),u=(r=s.body)===null||r===void 0?void 0:r.value;if(s.status>=200&&s.status<300&&Array.isArray(u))return t.observe({...a,status:u.length===0?"absent":"present"}),u.length===0?"absent":"present";t.observe({...a,status:"readFailed",detail:`HTTP ${s.status}`})}catch(s){t.observe({...a,status:"readFailed",detail:Lv(s)})}return"unread"}fr.existsByKey=lH});var Mv=C(po=>{"use strict";Object.defineProperty(po,"__esModule",{value:!0});po.businessRuleApi=po.BUSINESS_RULE_LEFT_DEACTIVATED_CODE=po.WFOM_API_UNAVAILABLE_CODE=void 0;var jo=Ds(),cH=Ke(),dH=Dv(),fH=Rv(),yh=qi(),er=pe(),$a=ae(),bh=Y();po.WFOM_API_UNAVAILABLE_CODE="BUSINESS_RULE_API_UNAVAILABLE";po.BUSINESS_RULE_LEFT_DEACTIVATED_CODE="BUSINESS_RULE_LEFT_DEACTIVATED";async function HO(e,t,n,r){let i=`/workflows(${hH})/Microsoft.Dynamics.CRM.${t}`;try{return(0,er.ensureSuccess)(await e.post(i,{Entity:n.Entity,WfomJson:n.WfomJson},{headers:r}),e.apiUrl(i))}catch(o){throw o?.statusCode!==404?o:new bh.SdkError(po.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 pH(e,t,n){let r=`/workflows(${t})${(0,$a.odataQuery)([["$select","workflowid,statecode,statuscode"]])}`;try{let i=await e.get(r);if(i.status<200||i.status>=300)return n?.(`HTTP ${i.status}`,i.status===404),null;let o=i.body;return{etag:(0,er.readEtag)(i),statecode:typeof o?.statecode=="number"?o.statecode:null,statuscode:typeof o?.statuscode=="number"?o.statuscode:null}}catch(i){return n?.((0,yh.failureDetail)(i),!1),null}}async function mH(e,t,n,r){let i={guard:"rowToken",componentName:"Workflow",componentId:t,held:n},o=await pH(e,t,r?(a,s)=>r.observe({...i,status:s?"goneOnServer":"readFailed",detail:a}):void 0);if(o!==null&&r?.observe({...i,server:o.etag,status:(0,yh.compareTokens)(n,o.etag)}),o===null||o.etag===null)throw new bh.SdkError(er.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(o.etag!==n)throw new bh.SdkError(er.VERSION_CONFLICT_CODE,`Version conflict updating business rule '${t}': it changed on the server since it was fetched (held ${n}, server ${o.etag}). Re-fetch the rule and re-apply the change.`);return{statecode:o.statecode,statuscode:o.statuscode}}var hH="00000000-0000-0000-0000-000000000000",gh={"Content-Type":"application/json",Accept:"application/json","OData-Version":"4.0","OData-MaxVersion":"4.0"},gH="workflowid,name,description,primaryentity,statecode,category,type",yH="category eq 2 and type eq 1";async function KO(e,t,n){var r;if(n==="Draft")return null;let i=(0,$a.normalizeGuid)(t,"workflowid"),o=n==="Active",a={statecode:o?jo.StateCode.Activated:jo.StateCode.Draft,statuscode:o?jo.StatusCode.Activated:jo.StatusCode.Draft},s=`/workflows(${i})`,u=(0,er.ensureSuccess)(await e.patch(s,a,{headers:gh}),e.apiUrl(s));return(r=(0,er.readEtag)(u))!==null&&r!==void 0?r:await vf(e,i)}async function vf(e,t){let n=`/workflows(${t})${(0,$a.odataQuery)([["$select","workflowid"]])}`;try{let r=await e.get(n);return r.status>=200&&r.status<300?(0,er.readEtag)(r):null}catch{return null}}async function bH(e,t,n){let r=await vf(e,t),i=await n(),o=(0,er.readEtag)(i);if(o)return{response:i,etag:o};let a=await vf(e,t);return{response:i,etag:r!==null&&r===a?a:null}}po.businessRuleApi={async get(e,t){let n=(0,$a.normalizeGuid)(t,"id"),r=`/workflows(${n})/Microsoft.Dynamics.CRM.RetrieveProcessWithWfomJson`,{response:i,etag:o}=await bH(e,n,async()=>(0,er.ensureSuccess)(await e.get(r),e.apiUrl(r)));return{raw:i.body,etag:o}},async list(e,t){let n=[yH];t?.entityLogicalName&&n.push(`primaryentity eq '${(0,$a.odataLiteral)(t.entityLogicalName)}'`);let r=`/workflows${(0,$a.odataQuery)([["$select",gH],["$filter",n.join(" and ")]])}`;return(await(0,cH.collectPages)(e,r,"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,n=void 0,r){var i;let o=t,a=(0,$a.normalizeGuid)(o.Entity.workflowid,"workflowid");if(r)return r.reached({effects:[{componentName:"Workflow",componentId:a,identity:"known",operation:"create"}],attemptsWrite:!0},()=>(0,yh.existsByKey)(e,r,{collection:"/workflows",key:"workflowid",id:a,componentName:"Workflow"}));let s=await HO(e,"CreateProcessWithWfomJson",o,gh),u=(0,er.resolveCreatedId)(s,"workflowid","business rule",a),l=null;try{l=await KO(e,u,o.status)}catch(c){try{await(0,er.deleteRecord)(e,"workflows",u)}catch{}throw c}return{id:u,etag:(i=l??(0,er.readEtag)(s))!==null&&i!==void 0?i:await vf(e,u)}},async update(e,t,n,r,i=void 0,o,a){var s,u;let l=n,c=(0,$a.normalizeGuid)(t,"id"),d=`/workflows(${c})`;a&&!(0,er.isVersionToken)(r)&&a.observe({guard:"rowToken",componentName:"Workflow",componentId:c,held:r,status:"missingHeld"});let f={...gh,"If-Match":(0,er.requireEtag)(r,"business rule",c)},p=await mH(e,c,f["If-Match"],a);if(a)return a.reached({effects:[{componentName:"Workflow",componentId:c,identity:"known",operation:"update"}],attemptsWrite:!0});let m=p.statecode===jo.StateCode.Activated;m&&(0,er.ensureSuccess)(await e.patch(d,{statecode:jo.StateCode.Draft,statuscode:jo.StatusCode.Draft},{headers:f}),e.apiUrl(d));let h;try{h=await HO(e,"UpdateProcessWithWfomJson",l,f)}catch(y){if(m)try{(0,er.ensureSuccess)(await e.patch(d,{statecode:jo.StateCode.Activated,statuscode:(s=p.statuscode)!==null&&s!==void 0?s:jo.StatusCode.Activated},{headers:gh}),e.apiUrl(d))}catch(b){throw new bh.SdkError(po.BUSINESS_RULE_LEFT_DEACTIVATED_CODE,`The business-rule write failed AND the rule could not be re-activated, so '${c}' is left DEACTIVATED (Draft) on the server. Re-activate it before relying on it. Original write failure: ${y instanceof Error?y.message:String(y)}. Restore failure: ${b instanceof Error?b.message:String(b)}`)}throw y}let g=await KO(e,c,l.status);return{id:c,etag:(u=g??(0,er.readEtag)(h))!==null&&u!==void 0?u:await vf(e,c)}},planPush(e,t,n){return(0,yh.planPushThrough)(po.businessRuleApi,e,t,n)},async delete(e,t){let n=(0,$a.normalizeGuid)(t,"id"),r=await(0,dH.assertWorkflowKind)(e,n,jo.WorkflowCategory.BusinessRule);return(0,fH.deleteWorkflowResending)(e,n,{bindingToken:r,kindName:"business rule"})}}});var mo=C(mn=>{"use strict";Object.defineProperty(mn,"__esModule",{value:!0});mn.publishBoundEntity=mn.boundEntityPublishScope=mn.publishGenPageById=mn.publishDashboardById=mn.publishWebResourceById=mn.publishEntity=mn.appModulePublishParameterXml=mn.publishAppModule=mn.publishXml=void 0;var JO=pe(),wf=ae(),YO="/PublishXml";async function Zl(e,t){(0,JO.ensureSuccess)(await(0,JO.resendDeadlockVictim)(()=>e.post(YO,{ParameterXml:t})),e.apiUrl(YO))}mn.publishXml=Zl;function vH(e,t){return Zl(e,QO(t))}mn.publishAppModule=vH;function QO(e){return`<importexportxml><appmodules><appmodule>${(0,wf.xmlText)(e)}</appmodule></appmodules></importexportxml>`}mn.appModulePublishParameterXml=QO;function XO(e,t){return Zl(e,`<importexportxml><entities><entity>${(0,wf.xmlText)(t)}</entity></entities></importexportxml>`)}mn.publishEntity=XO;function wH(e,t){return Zl(e,`<importexportxml><webresources><webresource>${(0,wf.xmlText)(t)}</webresource></webresources></importexportxml>`)}mn.publishWebResourceById=wH;function EH(e,t){return Zl(e,`<importexportxml><dashboards><dashboard>${(0,wf.xmlText)(t)}</dashboard></dashboards></importexportxml>`)}mn.publishDashboardById=EH;function AH(e,t){return Zl(e,`<importexportxml><uxagentprojects><uxagentproject>${(0,wf.xmlText)(t)}</uxagentproject></uxagentprojects></importexportxml>`)}mn.publishGenPageById=AH;function CH(e){let t=e?.entityLogicalName;return t?{envelope:"entity",entityLogicalName:t,blastRadiusWarning:"ENTITY_ENVELOPE_ALSO_SHIPS_UNRELATED_UNPUBLISHED_CHANGES"}:{envelope:"entity"}}mn.boundEntityPublishScope=CH;function SH(e,t){let n=t?.entityLogicalName;return n?XO(e,n):Promise.resolve()}mn.publishBoundEntity=SH});var ec=C(wh=>{"use strict";Object.defineProperty(wh,"__esModule",{value:!0});wh.JsonPointer=void 0;var Ii=Y(),vh=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 Ii.JsonPointerError(t,'non-empty pointers must start with "/"');return t.substring(1).split("/").map(n=>{if(/~(?![01])/.test(n))throw new Ii.JsonPointerError(t,`invalid '~' escape in token '${n}' (expected ~0 or ~1)`);return e.decodeToken(n)})}static compile(t){return t.length===0?"":"/"+t.map(n=>e.encodeToken(n)).join("/")}static resolve(t,n){let r=e.parse(n),i=t;for(let o of r)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,n,r){let i=e.parse(n);if(i.length===0)throw new Ii.JsonPointerError(n,"cannot set the document root");let{parent:o,lastToken:a}=e.resolveParent(t,i,n);if(Array.isArray(o)){let s=e.toArrayIndex(a,o.length);if(s===void 0)throw new Ii.JsonPointerError(n,`'${a}' is not a valid array index`);if(s>o.length)throw new Ii.JsonPointerError(n,`array index '${a}' is out of range`);o[s]=r}else{if(e.isReservedToken(a))throw new Ii.JsonPointerError(n,`refusing to write reserved property '${a}'`);o[a]=r}}static remove(t,n){let r=e.parse(n);if(r.length===0)throw new Ii.JsonPointerError(n,"cannot remove the document root");let{parent:i,lastToken:o}=e.resolveParent(t,r,n);if(Array.isArray(i)){let a=e.toArrayIndex(o,i.length);if(a===void 0||a>=i.length)throw new Ii.JsonPointerError(n,`array index '${o}' is out of range`);i.splice(a,1)}else{if(e.isReservedToken(o))throw new Ii.JsonPointerError(n,`refusing to remove reserved property '${o}'`);delete i[o]}}static add(t,n,r,i){let o=e.parse(n);if(o.length>0&&o[o.length-1]==="-"){let u=e.compile(o.slice(0,-1)),l=e.resolve(t,u);if(!Array.isArray(l))throw new Ii.JsonPointerError(n,"add target must be an array");l.push(r);return}let a=e.resolve(t,n);if(!Array.isArray(a))throw new Ii.JsonPointerError(n,"add target must be an array");let s=i===void 0?a.length:i;if(s<0||s>a.length)throw new Ii.JsonPointerError(n,`insert index ${s} is out of range`);a.splice(s,0,r)}static parent(t){let n=e.parse(t);return n.pop(),e.compile(n)}static lastToken(t){let n=e.parse(t);return n.length===0?"":n[n.length-1]}static append(t,n){return`${t}/${e.encodeToken(String(n))}`}static resolveParent(t,n,r){let i=n[n.length-1],o=e.compile(n.slice(0,-1)),a=e.resolve(t,o);if(a===null||typeof a!="object")throw new Ii.JsonPointerError(r,"parent path does not resolve to an object or array");return{parent:a,lastToken:i}}static toArrayIndex(t,n){if(t==="-")return n;if(/^(0|[1-9][0-9]*)$/.test(t))return Number(t)}};wh.JsonPointer=vh;vh.RESERVED_TOKENS=new Set(["__proto__","prototype","constructor"])});var eD=C(Eh=>{"use strict";Object.defineProperty(Eh,"__esModule",{value:!0});Eh.findElements=void 0;var ZO=ec();function NH(e,t){let n=[];return xv(e,"",t,n),n}Eh.findElements=NH;function xv(e,t,n,r){if(!(e===null||typeof e!="object"))if(n(e,t)&&r.push({pointer:t,value:e}),Array.isArray(e))e.forEach((i,o)=>{xv(i,ZO.JsonPointer.append(t,o),n,r)});else for(let i of Object.keys(e))xv(e[i],ZO.JsonPointer.append(t,i),n,r)}});var Fv=C(Wo=>{"use strict";Object.defineProperty(Wo,"__esModule",{value:!0});Wo.assertMutationResult=Wo.assertExistsResult=Wo.assertReadResult=Wo.assertStorageContract=void 0;var _H=["readText","writeTextAtomic","deleteFile","deleteByPrefix"],IH=["ensureContainer","exists"];function TH(e){if(typeof e!="object"||e===null)throw new Error("workspaceStorage must be an object implementing WorkspaceStorage.");for(let t of _H)if(typeof e[t]!="function")throw new Error(`workspaceStorage is missing the required method '${t}'.`);for(let t of IH){let n=e[t];if(n!==void 0&&typeof n!="function")throw new Error(`workspaceStorage.${t} must be a function when present.`)}return e}Wo.assertStorageContract=TH;function OH(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.`)}Wo.assertReadResult=OH;function DH(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.`)}Wo.assertExistsResult=DH;function PH(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.`)}Wo.assertMutationResult=PH});var Uv=C(tc=>{"use strict";Object.defineProperty(tc,"__esModule",{value:!0});tc.retryTransientIoAsync=tc.retryTransientIo=void 0;var RH=new Set(["EPERM","EACCES","EBUSY","UNKNOWN"]),kH=5,tD=10;function $H(e){for(let t=1;;t+=1)try{return e()}catch(n){if(!nD(n,t))throw n;MH(tD*t)}}tc.retryTransientIo=$H;async function LH(e){for(let t=1;;t+=1)try{return await e()}catch(n){if(!nD(n,t))throw n;await new Promise(r=>setTimeout(r,tD*t))}}tc.retryTransientIoAsync=LH;function nD(e,t){let n=e.code;return t<kH&&!!n&&RH.has(n)}function MH(e){try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)}catch{let t=Date.now()+e;for(;Date.now()<t;);}}});var sD=C(Ti=>{"use strict";Object.defineProperty(Ti,"__esModule",{value:!0});Ti.canonicalArtifactId=Ti.WorkspaceManager=Ti.WORKSPACE_SCHEMA_VERSION=Ti.retryTransientIo=void 0;var pr=Fv(),zo=Y(),xH=Uv();Object.defineProperty(Ti,"retryTransientIo",{enumerable:!0,get:function(){return xH.retryTransientIo}});function rD(e){let t=e;return typeof t.pathFor=="function"&&typeof t.getRoot=="function"?e:null}Ti.WORKSPACE_SCHEMA_VERSION=1;var Ps={form:"forms",view:"views",businessRule:"business-rules",app:"apps",command:"commands",chart:"charts",dashboard:"dashboards",genPage:"gen-pages",bpf:"business-process-flows",environmentVariable:"environment-variables",connectionReference:"connection-references",fieldSecurityProfile:"field-security-profiles",customApi:"custom-apis",duplicateRule:"duplicate-rules"},FH="manifest.json",nc=".metadata",qv="entities";function iD(e){try{return Promise.resolve(e())}catch(t){return Promise.reject(t)}}function Bv(e){if(e.schemaVersion!==void 0&&e.schemaVersion>Ti.WORKSPACE_SCHEMA_VERSION)throw new zo.IncompatibleWorkspaceError(e.schemaVersion,Ti.WORKSPACE_SCHEMA_VERSION)}function oD(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ah(e){return e.trim().toLowerCase().replace(/\/+$/,"")}var Vv=class{withManifest(t){let n=this.manifestQueue.then(t,t);return this.manifestQueue=n.then(()=>{},()=>{}),n}constructor(t,n,r){if(this.workspaceLabel=t,this.instanceUrl=n,this.manifestQueue=Promise.resolve(),this.bound=!1,r==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=r}artifactKey(t,n){return this.assertSafeId(n),[Ps[t],`${Ef(n)}.json`]}metaKey(t,n){return this.assertSafeId(n),[nc,Ps[t],`${Ef(n)}.meta.json`]}entityKey(t){return this.assertSafeId(t),[nc,qv,`${t.toLowerCase()}.json`]}fsStore(){let t=rD(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=rD(this.storage);return t?t.getRoot():this.workspaceLabel}getArtifactDir(t){return this.fsStore().pathFor([Ps[t]])}getArtifactFilePath(t,n){return this.fsStore().pathFor(this.artifactKey(t,n))}getMetaFilePath(t,n){return this.fsStore().pathFor(this.metaKey(t,n))}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 zo.PathTraversalError(String(t),this.workspaceLabel)}get manifestKey(){return[FH]}assertDataKey(t,n){if(!Array.isArray(t)||t.length<2)throw new zo.InvalidArgumentError(`${n} 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(r=>this.assertSafeId(r))}async init(){let t=await this.withManifest(async()=>{let n=await this.readStoredManifest();return n.present&&this.assertBoundHere(n.value),n.present});await this.ensureLayout(),t||await this.withManifest(async()=>{let n=await this.readStoredManifest();if(n.present){this.assertBoundHere(n.value);return}let r={instanceUrl:this.instanceUrl,createdAt:new Date().toISOString(),artifacts:[]};await this.writeManifest(r)}),this.bound=!0}async readStoredManifest(){let t=(0,pr.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),n=[[nc,qv]];for(let i of Object.keys(Ps))n.push([Ps[i]],[nc,Ps[i]]);let r=await Promise.allSettled(n.map(i=>iD(()=>t(i))));for(let i of r){if(i.status==="rejected")throw i.reason;(0,pr.assertMutationResult)(i.value,"ensureContainer")}}async isInitialized(){return this.storage.exists?(0,pr.assertExistsResult)(await this.storage.exists(this.manifestKey),"manifest.json"):(0,pr.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 zo.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,n=>{throw t(),n})}return this.verifying}async readAndCheckBinding(){let t=await this.readStoredManifest();if(!t.present)throw new zo.WorkspaceNotInitializedError(this.workspaceLabel);this.assertBoundHere(t.value),this.bound=!0}assertBoundHere(t){if(!oD(t))throw new zo.WorkspaceOrgMismatchError("",this.instanceUrl);Bv(t);let n=typeof t.instanceUrl=="string"?t.instanceUrl.trim():"",r=Ah(n);if(!r||r!==Ah(this.instanceUrl))throw new zo.WorkspaceOrgMismatchError(n,this.instanceUrl)}async clean(){let t=await this.readStoredManifest();if(!t.present||!oD(t.value))throw new zo.WorkspaceNotInitializedError(this.workspaceLabel);let n=t.value;Bv(n);let r=Object.keys(Ps).map(o=>[Ps[o]]);r.push([nc]);let i=await Promise.allSettled(r.map(o=>iD(()=>this.storage.deleteByPrefix(o))));for(let o of i){if(o.status==="rejected")throw o.reason;(0,pr.assertMutationResult)(o.value,"deleteByPrefix")}await this.ensureLayout(),await this.withManifest(()=>this.writeManifest({...n,instanceUrl:this.instanceUrl,artifacts:[],lastSyncAt:void 0})),this.bound=!0}async readArtifact(t,n){return await this.ensureInitialized(),this.readJsonUnchecked(this.artifactKey(t,n))}async readArtifactWithText(t,n){await this.ensureInitialized();let r=this.artifactKey(t,n),i=(0,pr.assertReadResult)(await this.storage.readText(r),r.join("/"));return i===null?null:{artifact:JSON.parse(i),text:i}}async writeArtifact(t,n,r,i){await this.ensureInitialized();let o=aD(r);if(i!==void 0&&o===i){await this.upsertManifestEntry(t,n,r,{unlessCurrent:!0});return}(0,pr.assertMutationResult)(await this.storage.writeTextAtomic(this.artifactKey(t,n),o),"writeTextAtomic"),await this.upsertManifestEntry(t,n,r)}async deleteArtifact(t,n){await this.ensureInitialized(),(0,pr.assertMutationResult)(await this.storage.deleteFile(this.artifactKey(t,n)),"deleteFile"),(0,pr.assertMutationResult)(await this.storage.deleteFile(this.metaKey(t,n)),"deleteFile");let r=Ef(n);await this.withManifest(async()=>{let i=await this.getManifest();i.artifacts=i.artifacts.filter(o=>!(o.type===t&&o.id===r)),await this.writeManifest(i)})}async readMeta(t,n){return await this.ensureBound(),this.readJsonUnchecked(this.metaKey(t,n))}async writeMeta(t,n,r){await this.ensureBound(),await this.writeJsonUnchecked(this.metaKey(t,n),r)}async listArtifacts(t,n){return await this.ensureInitialized(),(await this.getManifest()).artifacts.filter(r=>!(t&&r.type!==t||n?.entityLogicalName&&r.entityLogicalName!==n.entityLogicalName))}async readEntityMetadata(t){await this.ensureInitialized();let n=await this.readJsonUnchecked(this.entityKey(t));return!n||typeof n.schemaName!="string"||typeof n.primaryNameAttribute!="string"||typeof n.primaryIdAttribute!="string"||typeof n.isCustomEntity!="boolean"?null:n}async writeEntityMetadata(t,n){await this.ensureInitialized(),await this.writeJsonUnchecked(this.entityKey(t),n)}async dropEntityMetadata(t){if(await this.ensureInitialized(),t===void 0){(0,pr.assertMutationResult)(await this.storage.deleteByPrefix([nc,qv]),"deleteByPrefix");return}(0,pr.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 zo.WorkspaceNotInitializedError(this.workspaceLabel);return Bv(t),t}async writeManifest(t){await this.writeJsonUnchecked(this.manifestKey,{...t,schemaVersion:Ti.WORKSPACE_SCHEMA_VERSION})}async updateManifest(t){await this.withManifest(async()=>{let n=await this.getManifest();if(t.instanceUrl!==void 0&&Ah(String(t.instanceUrl))!==Ah(n.instanceUrl))throw new zo.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({...n,...t,instanceUrl:n.instanceUrl})})}async upsertManifestEntry(t,n,r,i={}){await this.withManifest(async()=>{let o=await this.getManifest(),a=Ef(n),s=r,u=typeof s.name=="string"?s.name:`${t}:${a}`,l=typeof s.entityLogicalName=="string"?s.entityLogicalName:void 0,c=o.artifacts.find(d=>d.type===t&&d.id===a);i.unlessCurrent&&c?.name===u&&c.entityLogicalName===l||(c?(c.name=u,c.entityLogicalName=l):o.artifacts.push({type:t,id:a,name:u,entityLogicalName:l,isDirty:!1}),await this.writeManifest(o))})}async readJson(t){return await this.ensureBound(),this.readJsonUnchecked(t)}async writeJson(t,n){this.assertDataKey(t,"writeJson"),await this.ensureBound(),await this.writeJsonUnchecked(t,n)}async removeFile(t){this.assertDataKey(t,"removeFile"),await this.ensureBound(),(0,pr.assertMutationResult)(await this.storage.deleteFile(t),"deleteFile")}async exists(t){return await this.ensureBound(),this.storage.exists?(0,pr.assertExistsResult)(await this.storage.exists(t),t.join("/")):(0,pr.assertReadResult)(await this.storage.readText(t),t.join("/"))!==null}async readJsonUnchecked(t){let n=(0,pr.assertReadResult)(await this.storage.readText(t),t.join("/"));return n===null?null:JSON.parse(n)}async writeJsonUnchecked(t,n){(0,pr.assertMutationResult)(await this.storage.writeTextAtomic(t,aD(n)),"writeTextAtomic")}};Ti.WorkspaceManager=Vv;function aD(e){return`${JSON.stringify(e,null,2)}+`}function Ef(e){let n=/^\{?([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 n?n[1].toLowerCase():e.toLowerCase()}Ti.canonicalArtifactId=Ef});var Rs=C(rc=>{"use strict";Object.defineProperty(rc,"__esModule",{value:!0});rc.deepEqual=rc.deepDiff=void 0;var UH=ec();function qH(e,t){let n=[];return lD(e,t,"",n,0),n}rc.deepDiff=qH;var Ch=Symbol("missing"),Sh=512;function lD(e,t,n,r,i){if(e===t)return;if(i>Sh)throw new RangeError(`deepDiff exceeded the maximum supported depth of ${Sh}`);let o=Nh(e),a=Nh(t);if(o&&a&&Array.isArray(e)===Array.isArray(t)){let s=BH(e,t);for(let u of s){let l=uD(e,u),c=uD(t,u),d=UH.JsonPointer.append(n,u);l===Ch?r.push({pointer:d,type:"added",newValue:c}):c===Ch?r.push({pointer:d,type:"removed",oldValue:l}):lD(l,c,d,r,i+1)}return}cD(e,t)||r.push({pointer:n,type:"modified",oldValue:e,newValue:t})}function Nh(e){return e!==null&&typeof e=="object"}function BH(e,t){if(Array.isArray(e)&&Array.isArray(t)){let r=Math.max(e.length,t.length),i=[];for(let o=0;o<r;o++)i.push(String(o));return i}let n=new Set([...Object.keys(e),...Object.keys(t)]);return Array.from(n)}function uD(e,t){if(Array.isArray(e)){let n=Number(t);return n<e.length?e[n]:Ch}return t in e?e[t]:Ch}function cD(e,t){return dD(e,t,0)}rc.deepEqual=cD;function dD(e,t,n){if(e===t)return!0;if(n>Sh)throw new RangeError(`deepEqual exceeded the maximum supported depth of ${Sh}`);if(!Nh(e)||!Nh(t)||Array.isArray(e)!==Array.isArray(t))return!1;let r=Object.keys(e),i=Object.keys(t);return r.length!==i.length?!1:r.every(o=>o in t&&dD(e[o],t[o],n+1))}});var pD=C(ic=>{"use strict";Object.defineProperty(ic,"__esModule",{value:!0});ic.VersionManager=ic.PROJECTION_VERSION=void 0;var fD=Rs(),VH=pe();ic.PROJECTION_VERSION=9;var Gv=class{constructor(t){this.workspace=t}async storeMeta(t,n,r,i){var o;let a=i===void 0?await this.getMeta(t,n):i,s=((o=r.snapshot)===null||o===void 0?void 0:o.status)==="Active",u=a?.everActivated===!0||s;await this.workspace.writeMeta(t,n,u?{...r,everActivated:u}:r)}async getMeta(t,n){return this.workspace.readMeta(t,n)}async isDirty(t,n,r){let i=await this.workspace.readArtifact(t,n);if(i===null)return!1;let o=r===void 0?await this.getMeta(t,n):r;return o?!(0,fD.deepEqual)(o.snapshot,i):!0}async diff(t,n){let r=await this.workspace.readArtifact(t,n),i=await this.getMeta(t,n),o;return r===null?o=i?[{pointer:"",type:"removed",oldValue:i.snapshot}]:[]:i?o=(0,fD.deepDiff)(i.snapshot,r):o=[{pointer:"",type:"added",newValue:r}],{artifactType:t,artifactId:n,changes:o}}async checkConflict(t,n,r){let i=await this.getMeta(t,n);return!i||!(0,VH.isVersionToken)(i.etag)?!0:i.etag!==r}};ic.VersionManager=Gv});var hD=C((jv,mD)=>{(function(e,t){typeof define=="function"&&define.amd?define([],t):typeof jv=="object"?mD.exports=t():e.compareVersions=t()})(jv,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 n(o){var a=o.replace(/^v/,"").replace(/\+.*$/,""),s=t(a,"-"),u=a.substring(0,s).split(".");return u.push(a.substring(s+1)),u}function r(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 u=n(a),l=n(s),c=0;c<Math.max(u.length-1,l.length-1);c++){var d=parseInt(u[c]||0,10),f=parseInt(l[c]||0,10);if(d>f)return 1;if(f>d)return-1}var p=u[u.length-1],m=l[l.length-1];if(p&&m){var h=p.split(".").map(r),g=m.split(".").map(r);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 wD=C(Jt=>{"use strict";Object.defineProperty(Jt,"__esModule",{value:!0});Jt.EnvironmentFlowHostingType=Jt.EnvironmentDisableReasonCode=Jt.EnvironmentMigrationConstants=Jt.EnvironmentProvisioningStates=Jt.EnvironmentLocations=Jt.EnvironmentCreationTypeConstants=Jt.EnvironmentType=Jt.EnvironmentSkuConstants=Jt.environmentPermissions=Jt.DatabaseType=void 0;var gD;(function(e){e.CommonDataService="CommonDataService",e.None="None"})(gD||(Jt.DatabaseType=gD={}));Jt.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"};Jt.EnvironmentSkuConstants={NotSpecified:"NotSpecified",Standard:"Standard",Premium:"Premium",Developer:"Developer",Basic:"Basic",Production:"Production",Sandbox:"Sandbox",Trial:"Trial",Default:"Default",Teams:"Teams",Platform:"Platform"};var yD;(function(e){e[e.CDS2=0]="CDS2",e[e.CDS1=1]="CDS1",e[e.Empty=2]="Empty"})(yD||(Jt.EnvironmentType=yD={}));Jt.EnvironmentCreationTypeConstants={NotSpecified:"NotSpecified",Legacy:"Legacy",DefaultTenant:"DefaultTenant",User:"User",CommonDataModelLegacy:"CommonDataModelLegacy"};Jt.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"};Jt.EnvironmentProvisioningStates={NotSpecified:"NotSpecified",Succeeded:"Succeeded",Deleting:"Deleting",Deleted:"Deleted",FailedDeleting:"FailedDeleting",LinkedDatabaseProvisioning:"LinkedDatabaseProvisioning",LinkedDatabaseFailedProvisioning:"LinkedDatabaseFailedProvisioning",LinkedDatabaseFailedConfiguring:"LinkedDatabaseFailedConfiguring",LinkedDatabaseUnavailable:"LinkedDatabaseUnavailable",Creating:"Creating"};Jt.EnvironmentMigrationConstants={phases:{completed:"Completed"}};var bD;(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"})(bD||(Jt.EnvironmentDisableReasonCode=bD={}));var vD;(function(e){e.LogicApps="LogicApps",e.SelfHostSingleTenant="SelfHostSingleTenant",e.SelfHostMultiTenant="SelfHostMultiTenant"})(vD||(Jt.EnvironmentFlowHostingType=vD={}))});var TD=C($=>{"use strict";var GH=$&&$.__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 jH=GH(hD()),ct=wD(),Af=zv();function WH(e){let t=Ma(e);return t&&t.version}$.getCrmVersion=WH;function Ma(e){return e&&e.properties&&e.properties.linkedEnvironmentMetadata}$.getLinkedEnvironmentMetadata=Ma;function La(e,t){return e?!!e[t]:!1}$.doesUserHavePermission=La;$.crmBapSolutionId="00000001-0000-0000-0001-00000000009b";$.DEFAULT_SOLUTION_ID="fd140aaf-4df4-11dd-bd17-0019b9312238";$.DEFAULT_SOLUTION_UNIQUE_NAME="Default";function Uu(e){return!!Ma(e)&&ED(e)}$.environmentHasCds2Database=Uu;function zH(e){if(e&&Uu(e)){let t=ks(e);return(0,Af.getCrmAdminSecurityRolesUrl)(t)}return""}$.getSecurityUsersUrl=zH;function HH(e){if(e&&Uu(e)){let t=ks(e);return(0,Af.getCrmAdminSecurityUsersUrl)(t)}return""}$.getSecurityRolesUrl=HH;function KH(e){if(e&&Uu(e)){let t=ks(e);(0,Af.getCrmAllSolutionsUrl)(t)}return""}$.getAllSolutionsUrl=KH;function JH(e){if(e&&Uu(e)){let t=ks(e);return(0,Af.getCrmAllPublishersUrl)(t)}return""}$.getAllPublishersUrl=JH;function YH(e){return e&&Uu(e)?ks(e):""}$.getAllThemesUrl=YH;function ED(e){return!!e&&e.properties&&!!e.properties.provisioningState&&e.properties.provisioningState.toUpperCase()===ct.EnvironmentProvisioningStates.Succeeded.toUpperCase()}$.isEnvironmentInSuccessfulState=ED;function QH(e){if(e&&Uu(e)){let t=ks(e);return(0,Af.getCrmDevResourcesUrl)(t)}return""}$.getDevResourcesUrl=QH;function XH(e){return`${e}designer/app/{${$.crmBapSolutionId}}/CreateNewApp}}`}$.getCrmAppDesignerUrl=XH;function ks(e){let t=Ma(e);if(t){let n=t.instanceUrl;return n?n.endsWith("/")?n:n+"/":""}return""}$.getCrmInstanceUrl=ks;function ZH(e){let t=Ma(e);return t?t.uniqueName:""}$.getCrmInstanceName=ZH;function e7(e){return Ma(e)?ct.EnvironmentType.CDS2:e&&e.properties&&e.properties.namespace?ct.EnvironmentType.CDS1:ct.EnvironmentType.Empty}$.getEnvironmentType=e7;function t7(e){return e&&e.properties&&e.properties.environmentSku===ct.EnvironmentSkuConstants.Developer}$.isDevEnvironment=t7;function n7(e){return e&&e.properties&&e.properties.environmentSku===ct.EnvironmentSkuConstants.Production}$.isProdEnvironment=n7;function r7(e){return e&&e.properties&&e.properties.environmentSku===ct.EnvironmentSkuConstants.Sandbox}$.isSandboxEnvironment=r7;function Cf(e){return e&&e.properties&&e.properties.environmentSku===ct.EnvironmentSkuConstants.Teams}$.isTeamsEnvironment=Cf;function i7(e){return e&&e.properties&&e.properties.environmentSku===ct.EnvironmentSkuConstants.Platform}$.isPlatformEnvironment=i7;var o7=e=>{var t;return((t=e.properties)===null||t===void 0?void 0:t.environmentSku)===ct.EnvironmentSkuConstants.Trial};$.isTrialEnvironment=o7;function a7(e){return e&&e.properties&&(e.properties.isDefault||e.properties.creationType===ct.EnvironmentCreationTypeConstants.DefaultTenant)}$.isDefaultEnvironment=a7;function s7(e){return e&&e.properties&&!!e.properties.states&&!!e.properties.states.runtime&&e.properties.states.runtime.id==="Disabled"}$.isDisabledEnvironment=s7;function u7(e){return e&&e.properties&&La(e.properties.permissions,ct.environmentPermissions.CreateDatabase)}$.canUserCreateDatabase=u7;function l7(e){return!!(e&&e.properties&&e.properties.provisioningState&&ID(e.properties.provisioningState,ct.EnvironmentProvisioningStates.LinkedDatabaseProvisioning))}$.isDatabaseInProvisioningState=l7;function c7(e){return!!e&&!!e.properties&&e.properties.provisioningState===ct.EnvironmentProvisioningStates.Creating}$.isEnvironmentInCreatingState=c7;function d7(e){return e&&e.properties&&(e.properties.provisioningState===ct.EnvironmentProvisioningStates.Deleted||e.properties.provisioningState===ct.EnvironmentProvisioningStates.Deleting||e.properties.provisioningState===ct.EnvironmentProvisioningStates.FailedDeleting)}$.isEnvironmentInDeletedState=d7;function f7(e){return!!e&&!!e.properties&&!!e.properties.expirationTime&&Date.parse(e.properties.expirationTime)<Date.now()}$.isEnvironmentExpired=f7;function p7(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=p7;function m7(e){return!!e&&!!e.properties&&!!e.properties.cluster&&e.properties.cluster.category==="Test"}$.isEnvironmentInTestCluster=m7;function h7(e){return!!e&&!!e.properties&&!!e.properties.cluster&&e.properties.cluster.category==="Preprod"}$.isEnvironmentInPreprodCluster=h7;function g7(e){return!!e&&!!e.properties&&!!e.properties.cluster&&e.properties.cluster.category==="FirstRelease"}$.isEnvironmentInFirstReleaseCluster=g7;function y7(e){return e&&e.name||""}$.getEnvironmentName=y7;function b7(e){return e&&e.properties&&e.properties.displayName||""}$.getEnvironmentDisplayName=b7;var AD="9.1.0.8202";$.cdsVersionSupportingOSColorEdit="9.1.0000.20708";function v7(e){return ND(e,AD)}$.doesCds2EnvironmentSupportApiVersion9_1=v7;function w7(e){return Wv(e,AD)}$.doesCds2VersionSupportApiVersion9_1=w7;function CD(e){let t=Ma(e);if(t)return t.securityGroupId}function SD(e){return e&&e.properties&&e.properties.connectedGroups}function E7(e,t){let n=SD(e);return!!n&&!!n.find(r=>r.id===t)||CD(e)===t}$.hasSecurityGroupId=E7;function A7(e){let t=SD(e);return t&&t.length>0&&t[0].id?t[0].id:CD(e)}$.getSecurityOrConnectedGroupId=A7;function ND(e,t){let n=e.version;return n?Wv(n,t):!1}$.isCds2EnvironmentVersionAtLeast=ND;function Wv(e,t){return t?e?(0,jH.default)(e,t)>=0:!1:!0}$.checkVersions=Wv;function C7(e){return e&&e.properties&&e.properties.updateCadence&&e.properties.updateCadence.id||"NotSpecified"}$.getEnvironmentUpdateCadence=C7;function S7(e){let t=Ma(e);return t?Number(t.baseLanguage):0}$.getEnvironmentLanguageCode=S7;function _D(e){let t=Ma(e);return t?t.instanceApiUrl:void 0}$.getEnvironmentInstanceApiUrl=_D;function N7(e){let t=_D(e);return t?t+"/api/data/v9.2":""}$.getEnvironmentWebApiUrl=N7;function _7(e){let t=ks(e);if(t==="")return"";let n=t.split("/");if(n.length!==4)return"";let r=n[2].split(".");return r[0]="globaldisco",n[2]=r.join("."),n.join("/")+"api/discovery/v2.0/Instances"}$.getEnvironmentDiscoveryUrl=_7;var I7=e=>{var t;return((t=e.properties)===null||t===void 0?void 0:t.databaseType)===ct.DatabaseType.CommonDataService};$.hasCommonDataServiceDatabase=I7;var T7=e=>{var t;return La((t=e.properties)===null||t===void 0?void 0:t.permissions,ct.environmentPermissions.AdminReadEnvironment)};$.doesUserHaveAdminPermission=T7;var O7=e=>{var t;return La((t=e.properties)===null||t===void 0?void 0:t.permissions,ct.environmentPermissions.CreatePowerApp)};$.doesUserHaveCreateAppPermission=O7;var D7=e=>(0,$.doesUserHaveAdminPermission)(e)&&(0,$.hasCommonDataServiceDatabase)(e)?!0:(0,$.doesUserHaveCreateAppPermission)(e)?Cf(e)||(0,$.doesUserHaveDatabaseTablePermissions)(e):!1;$.isUserMakerWithDataAccess=D7;var P7=e=>(0,$.doesUserHaveCreateAppPermission)(e)&&!Cf(e)&&!(0,$.doesUserHaveDatabaseTablePermissions)(e)&&(!(0,$.doesUserHaveAdminPermission)(e)||!(0,$.hasCommonDataServiceDatabase)(e));$.isUserMakerWithoutDataAccess=P7;var R7=e=>[ct.environmentPermissions.CreateDatabaseEntities,ct.environmentPermissions.ListDatabaseEntities,ct.environmentPermissions.UpdateDatabaseEntities,ct.environmentPermissions.DeleteDatabaseEntities].every(t=>{var n;return La((n=e.properties)===null||n===void 0?void 0:n.permissions,t)});$.doesUserHaveDatabaseTablePermissions=R7;var k7=e=>{var t;return La((t=e.properties)===null||t===void 0?void 0:t.permissions,ct.environmentPermissions.CreateDatabase)};$.doesUserHaveCreateDatabasePermission=k7;function ID(e,t){return!e&&!t?!0:!e||!t?!1:e.toUpperCase()===t.toUpperCase()}$.equalsIgnoreCase=ID;var $7=e=>{var t;return La((t=e.properties)===null||t===void 0?void 0:t.permissions,ct.environmentPermissions.CreateFlow)};$.doesUserHaveCreateFlowPermission=$7;var L7=e=>(0,$.doesUserHaveAdminPermission)(e)&&(0,$.hasCommonDataServiceDatabase)(e)?!0:(0,$.doesUserHaveCreateFlowPermission)(e)?Cf(e)||(0,$.doesUserHaveDatabaseTablePermissions)(e):!1;$.isUserPautoMakerWithDataAccess=L7;var M7=e=>(0,$.doesUserHaveCreateFlowPermission)(e)&&!Cf(e)&&!(0,$.doesUserHaveDatabaseTablePermissions)(e)&&(!(0,$.doesUserHaveAdminPermission)(e)||!(0,$.hasCommonDataServiceDatabase)(e));$.isUserPautoMakerWithoutDataAccess=M7;var x7=e=>{var t,n;return!La((t=e.properties)===null||t===void 0?void 0:t.permissions,ct.environmentPermissions.CreateFlow)&&La((n=e.properties)===null||n===void 0?void 0:n.permissions,ct.environmentPermissions.ReadEnvironment)};$.doesUserHaveFlowRunOnlyPermission=x7});var zv=C(P=>{"use strict";Object.defineProperty(P,"__esModule",{value:!0});P.getRequiredComponentsQueryUrl=P.solutionComponentCountSummariesQueryUrl=P.solutionComponentSummariesQueryUrl=P.solutionComponentConfigurationsQueryUrl=P.chartsQueryUrl=P.workflowsQueryUrl=P.entityDefinitionsQueryUrl=P.solutionComponentDefinitionsQueryUrl=P.getCreateNewArticleTemplateUrl=P.getCreateNewPublisherUrl=P.getEnableSecurityRolesUrl=P.getArticleTemplateUrl=P.getFieldSecurityProfileDesignerUrl=P.getSecurityRoleDesignerUrl=P.getMailMergeTemplateDesignerUrl=P.getEmailTemplateDesignerUrl=P.getConnectionRoleDesignerUrl=P.getSiteMapDesignerUrl=P.getWebResourceFileUrl=P.getWebResourceDesignerUrl=P.getReportDesignerUrl=P.getBusinessProcessFlowDesignerUrl=P.getProcessShareUrl=P.getProcessDesignerUrl=P.getChartDesignerUrl=P.getOpenModernEntityDashboardUrl=P.getNewModernEntityDashboardUrl=P.getNewModernDashboardUrl=P.getOpenModernDashboardUrl=P.getDashboardDesignerUrl=P.getAppModuleDesignerUrl=P.privilegesQueryUrls=P.xrmApiUrl=P.getPlayAppModuleUrl=P.getCrmAdminSecurityUsersUrl=P.getCrmAdminSecurityRolesUrl=P.getCrmMyAppsUrl=P.getCrmAppDesignerUrl=P.getCrmDevResourcesUrl=P.getCrmAllPublishersUrl=P.getCrmAllSolutionsUrl=P.getSolutionPublisherUrl=P.getExportTranslationFileName=P.getExportSolutionTranslationUrl=P.getImportSolutionTranslationUrl=P.getShowSolutionDependenciesUrl=P.getShowComponentDependenciesUrl=P.cdsServiceUrl=P.ODATA_NEXT_LINK=P.ODATA_MAX_PAGE_SIZE=void 0;P.retrieveOrganizationResources=P.getUCIEntityRecordEditUrl=P.getUCIEntityRecordBaseUrl=P.getBusinessRuleDesignerUri=P.retrieveUnpublishedSuffix=P.getSavePowerSettingUri=P.getPowerSettingUri=P.getPowerSettingsUri=P.RetrievePlatform=P.getAppSettingOverrideUri=P.AppSettingOverrideName=P.getOrgSettingOverrideUri=P.OrgSettingOverrideName=P.getSettingDefinitionsUri=P.retrieveFeatureControlSettingsByNamespaceUrl=P.retrieveDeploymentPipelineConfigAppUrl=P.SPNPrincipalIdUrl=P.retrieveDeploymentEnvironmentInfoUrl=P.devSolutionInfoUrl=P.deployOperationStatusUrl=P.getAIGeneratedDeploymentNotesUrl=P.deploymentStageRunUrl=P.validatePackageAsyncUrl=P.deployPackageAsyncUrl=P.updateDeploymentStageRunUrl=P.createDeploymentStageRunUrl=P.retrieveDeploymentStagesUrl=P.retrievePipelinesUrl=P.retrieveDeploymentPipelineInfoUrl=P.getDeploymentStageRunsUrl=P.appDeploymentUrls=P.getProvisionLanguageUrl=P.getSolutionQueryUrl=P.getSolutionsByUniqueNameQueryUrl=P.solutionsQueryUrl=P.getDependentComponentsWithMetadataQueryUrl=void 0;var OD=TD();P.ODATA_MAX_PAGE_SIZE="odata.maxpagesize";P.ODATA_NEXT_LINK="@odata.nextLink";P.cdsServiceUrl="https://cds-org/";var Nf;(function(e){e.AllSolutions="11",e.AllPublishers="10",e.DevResources="05"})(Nf||(Nf={}));function F7(e,t,n,r){return`${e}tools/dependency/dependencyviewdialog.aspx?appSolutionId=%7b${t}%7d&dType=1&objectid=%7b${n}%7d&objecttype=${r}&operationtype=showdependency`}P.getShowComponentDependenciesUrl=F7;function U7(e,t){let n=`dType=1&isproactivecheck=true&objecttype=7100&operationtype=dependenciesforuninstall&objectid=${t}`;return`${e}tools/dependency/dependencyviewdialog.aspx?${n}`}P.getShowSolutionDependenciesUrl=U7;function q7(e,t){return`${e}tools/muiProvisioning/Dialogs/LangTranslationsImport.aspx?dType=1&appSolutionId=${t}`}P.getImportSolutionTranslationUrl=q7;function B7(e,t){return`${e}_grid/cmds/dlg_exportsolution.aspx?command=exporttranslation&appSolutionId=${t}`}P.getExportSolutionTranslationUrl=B7;function V7(e,t){return e!==void 0&&t!==void 0&&`CrmTranslations_${e}_${t.replace(/[.]/g,"_")}.zip`||""}P.getExportTranslationFileName=V7;function G7(e,t,n){return n?`${e}tools/publisher/edit.aspx?appSolutionId=%7b${n}%7d&id=%7b${t}%7d`:`${e}tools/publisher/edit.aspx?id=%7b${t}%7d`}P.getSolutionPublisherUrl=G7;function Hv(e,t){return`${e}tools/systemcustomization/systemCustomization.aspx?pid=${t}`}function j7(e){return Hv(e,Nf.AllSolutions)}P.getCrmAllSolutionsUrl=j7;function W7(e){return Hv(e,Nf.AllPublishers)}P.getCrmAllPublishersUrl=W7;function z7(e){return Hv(e,Nf.DevResources)}P.getCrmDevResourcesUrl=z7;function H7(e,t=OD.crmBapSolutionId){return`${e}designer/app/${t}#/CreateNewApp`}P.getCrmAppDesignerUrl=H7;function K7(e){return`${e}apps`}P.getCrmMyAppsUrl=K7;function J7(e){return DD(e,"role")+"&forceUCI=0"}P.getCrmAdminSecurityRolesUrl=J7;function Y7(e){return`${DD(e,"systemuser")}&forceclassic=1`}P.getCrmAdminSecurityUsersUrl=Y7;function DD(e,t){return`${e}main.aspx?pagetype=entitylist&etn=${t}`}function Q7(e,t){return`${e}main.aspx?appid=${t}`}P.getPlayAppModuleUrl=Q7;P.xrmApiUrl="api/data/v9.0";P.privilegesQueryUrls={systemUserInfo:e=>`${e}${P.xrmApiUrl}/WhoAmI`,userPrivileges:(e,t)=>`${e}${P.xrmApiUrl}/systemusers(${t})/Microsoft.Dynamics.CRM.RetrieveUserPrivileges`,systemPrivileges:e=>`${e}${P.xrmApiUrl}/privileges/Microsoft.Dynamics.CRM.RetrievePrivilegeSet`};function X7(e,t,n=OD.crmBapSolutionId){return`${e}designer/app/${n}/${t}/AppDesignerCanvas/${t}`}P.getAppModuleDesignerUrl=X7;function Z7(e,t,n,r){return`${e}main.aspx?appSolutionId=%7b${n}%7d&extraqs=%26formId%3d%7b${t}%7d%26dashboardType%3d1030&pagetype=${`${r?"ic":""}dashboardeditor`}`}P.getDashboardDesignerUrl=Z7;function eK(e,t,n){return`/e/${e}/s/${t}/dashboard/${n}`}P.getOpenModernDashboardUrl=eK;function tK(e,t,n){let r=n!==void 0?n.toString():void 0;return`/e/${e}/s/${t}/dashboard/new${r?`/${r}`:""}`}P.getNewModernDashboardUrl=tK;function nK(e,t,n,r){let i=r!==void 0?r.toString():void 0;return`/e/${e}/s/${t}/n/${n}/dashboard/new${i?`/${i}`:""}`}P.getNewModernEntityDashboardUrl=nK;function rK(e,t,n,r){return`/e/${e}/s/${t}/n/${n}/dashboard/${r}`}P.getOpenModernEntityDashboardUrl=rK;function iK(e,t,n,r){return`${e}main.aspx?appSolutionId=%7b${t}%7d&extraqs=etc=${n||""}`+(r?`%26id=${r}`:"")+"&pagetype=vizdesigner"}P.getChartDesignerUrl=iK;function oK(e,t,n){return`${e}sfa/workflow/edit.aspx?_CreateFromId=%7b${n}%7d&_CreateFromType=7100&appSolutionId=%7b${n}%7d&id=%7b${t}%7d`}P.getProcessDesignerUrl=oK;function aK(e,t,n){return`${e}sfa/workflow/edit.aspx?_CreateFromId=%7b${n}%7d&_CreateFromType=7100&appSolutionId=%7b${n}%7d&id=%7b${t}%7d`}P.getProcessShareUrl=aK;function sK(e,t){return`${e}Tools/ProcessControl/UnifiedProcessDesigner.aspx?id=${t}`}P.getBusinessProcessFlowDesignerUrl=sK;function uK(e,t,n){return`${e}CRMReports/reportproperty.aspx?appSolutionId=%7b${n}%7d&disablePersonal=true&id=%7b${t}%7d`}P.getReportDesignerUrl=uK;function lK(e,t,n){return`${e}main.aspx?_CreateFromId=%7b${n}%7d&_CreateFromType=7100&appSolutionId=%7b${n}%7d&etc=9333&id=%7b${t}%7d&pagetype=webresourceedit`}P.getWebResourceDesignerUrl=lK;function cK(e,t){return`${e}WebResources/${t}`}P.getWebResourceFileUrl=cK;function dK(e,t,n){return`${e}designer/sitemap/${n}/${t}/SiteMapHome/${t}`}P.getSiteMapDesignerUrl=dK;function fK(e,t,n){return`${e}connections/connectionroles/edit.aspx?_CreateFromId=%7b${n}%7d&_CreateFromType=7100&appSolutionId=%7b${n}%7d&id=%7b${t}%7d`}P.getConnectionRoleDesignerUrl=fK;function pK(e,t,n){return`${e}tools/emailtemplateeditor/emailtemplateeditor.aspx?_CreateFromId=%7b${n}%7d&_CreateFromType=7100&appSolutionId=%7b${n}%7d&id=%7b${t}%7d`}P.getEmailTemplateDesignerUrl=pK;function mK(e,t,n){return`${e}tools/mailmerge/edit.aspx?_CreateFromId=%7b${n}%7d&_CreateFromType=7100&appSolutionId=%7b${n}%7d&id=%7b${t}%7d`}P.getMailMergeTemplateDesignerUrl=mK;function hK(e,t,n){return`${e}biz/roles/edit.aspx?_CreateFromId=%7b${n}%7d&_CreateFromType=7100&appSolutionId=%7b${n}%7d&id=%7b${t}%7d`}P.getSecurityRoleDesignerUrl=hK;function gK(e,t,n){return`${e}biz/fieldsecurityprofiles/edit.aspx?_CreateFromId=%7b${n}%7d&_CreateFromType=7100&appSolutionId=%7b${n}%7d&id=%7b${t}%7d`}P.getFieldSecurityProfileDesignerUrl=gK;function yK(e,t,n){return`${e}tools/kbtemplateeditor/kbtemplateeditor.aspx?_CreateFromId=%7b${t}%7d&_CreateFromType=7100&appSolutionId=%7b${t}%7d&id=%7b${n}%7d`}P.getArticleTemplateUrl=yK;function bK(e,t,n,r){return`${e}tools/FormEditor/Dialogs/FormRoleAssignment.aspx?appSolutionId=%7b${t}%7d&dType=1&formId=%7b${n}%7d&objectTypeCode=0&type=${r}`}P.getEnableSecurityRolesUrl=bK;function vK(e){return`${e}tools/publisher/edit.aspx`}P.getCreateNewPublisherUrl=vK;function wK(e,t){return`${e}tools/kbtemplateeditor/kbtemplateeditor.aspx?appSolutionId=${t}`}P.getCreateNewArticleTemplateUrl=wK;P.solutionComponentDefinitionsQueryUrl="api/data/v9.0/solutioncomponentdefinitions";P.entityDefinitionsQueryUrl="api/data/v9.0/EntityDefinitions?$select=EntitySetName,DisplayName,LogicalName&$filter=";P.workflowsQueryUrl="api/data/v9.0/workflows";P.chartsQueryUrl="/api/data/v9.0/savedqueryvisualizations";P.solutionComponentConfigurationsQueryUrl="/api/data/v9.1/solutioncomponentconfigurations?$filter=isdisplayable eq true&$select=name";P.solutionComponentSummariesQueryUrl="/api/data/v9.0/msdyn_solutioncomponentsummaries";P.solutionComponentCountSummariesQueryUrl="/api/data/v9.0/msdyn_solutioncomponentcountsummaries";function EK(e,t){return`${P.xrmApiUrl}/RetrieveRequiredComponents(ObjectId=${e},ComponentType=${t})`}P.getRequiredComponentsQueryUrl=EK;function AK(e,t){return`${P.cdsServiceUrl}${P.xrmApiUrl}/RetrieveDependentComponentsWithMetadata(ObjectId=${e},ComponentType=${t})`}P.getDependentComponentsWithMetadataQueryUrl=AK;P.solutionsQueryUrl="/api/data/v9.0/solutions?$expand=publisherid&$filter=(isvisible eq true)";function CK(e){return`/api/data/v9.0/solutions?$expand=publisherid&$filter=(uniquename eq '${e}')`}P.getSolutionsByUniqueNameQueryUrl=CK;function SK(e){return`/api/data/v9.0/solutions(${e})?$expand=publisherid`}P.getSolutionQueryUrl=SK;function NK(e){return`${e}api/data/v9.1/ProvisionLanguageForUser`}P.getProvisionLanguageUrl=NK;P.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 _K(e,t,n,r=!1,i=!1,o=!1,a=!1,s=!1,u=!1,l=!1){return`/api/data/v9.1/deploymentstageruns+ ?$select=artifactname,artifactversion,deploymentstagerunid,devenvironmentid,endtime,errormessage,${s?"_artifactid_value,isredeployment,":""}${r?"deploymentnotes,":""}operation,operationdetails,operationstatus,${u?"retrycount,":""}${i?"scheduledtime,":""}${l?"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)${u?",RetryUser($select=azureactivedirectoryobjectid,fullname,ownerid,systemuserid)":""}+ &$filter=deploymentstageid/_deploymentpipelineid_value eq ${e} and devenvironmentid eq '${t}' and artifactname eq '${n}' and ((operation ne 200000201) or (operation eq 200000201 and operationstatus eq 200000003))+ &$orderby=starttime desc`}P.getDeploymentStageRunsUrl=_K;function IK(e,t,n){return`/api/data/v9.1/RetrieveDeploymentPipelineInfo(DeploymentPipelineId=${e},SourceEnvironmentId='${t}',ArtifactName='${n}')`}P.retrieveDeploymentPipelineInfoUrl=IK;function TK(e){return`/api/data/v9.0/deploymentenvironments?$select=deploymentenvironmentid,environmentid,environmenttype,name&$expand=deploymentpipeline_deploymentenvironment($select=name,description,deploymentpipelineid;$orderby=name asc)- &$filter=(environmentid eq '${e}')`}A.retrievePipelinesUrl=G3;function W3(e){return`/api/data/v9.0/deploymentstages+ &$filter=(environmentid eq '${e}')`}P.retrievePipelinesUrl=TK;function OK(e){return`/api/data/v9.0/deploymentstages?$filter=(_deploymentpipelineid_value eq ${e})&$select=name,description,deploymentstageid,_previousdeploymentstageid_value- &$expand=targetdeploymentenvironmentid($select=deploymentenvironmentid,environmentid,name)`}A.retrieveDeploymentStagesUrl=W3;function z3(){return"/api/data/v9.0/deploymentstageruns?$select=deploymentstagerunid"}A.createDeploymentStageRunUrl=z3;function j3(e){return`/api/data/v9.0/deploymentstageruns(${e})`}A.updateDeploymentStageRunUrl=j3;function H3(){return"/api/data/v9.0/DeployPackageAsync"}A.deployPackageAsyncUrl=H3;function K3(){return"/api/data/v9.0/ValidatePackageAsync"}A.validatePackageAsyncUrl=K3;function J3(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=J3;function Y3(e){return`/api/data/v9.0/deploymentstageruns(${e})- ?$select=aigenerateddeploymentnotes,deploymentstagerunid`}A.getAIGeneratedDeploymentNotesUrl=Y3;function Q3(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)`}P.retrieveDeploymentStagesUrl=OK;function DK(){return"/api/data/v9.0/deploymentstageruns?$select=deploymentstagerunid"}P.createDeploymentStageRunUrl=DK;function PK(e){return`/api/data/v9.0/deploymentstageruns(${e})`}P.updateDeploymentStageRunUrl=PK;function RK(){return"/api/data/v9.0/DeployPackageAsync"}P.deployPackageAsyncUrl=RK;function kK(){return"/api/data/v9.0/ValidatePackageAsync"}P.validatePackageAsyncUrl=kK;function $K(e,t=!1,n=!1){return`/api/data/v9.0/deploymentstageruns(${e})+ ?$select=deploymentstagerunid,stagerunstatus,errormessage,operation,operationdetails,operationstatus,${t?"scheduledtime,":""}targetenvironmentid,validationresults,artifactname,deploymentsettingsjson${n?"&$expand=createdby($select=azureactivedirectoryobjectid,fullname,ownerid,systemuserid)":""}`}P.deploymentStageRunUrl=$K;function LK(e){return`/api/data/v9.0/deploymentstageruns(${e})+ ?$select=aigenerateddeploymentnotes,deploymentstagerunid`}P.getAIGeneratedDeploymentNotesUrl=LK;function MK(e){let t="";for(let n=0;n<e.length;n++)n===e.length-1?t=t.concat(`deploymentstagerunid eq ${e[n]}`):t=t.concat(`deploymentstagerunid eq ${e[n]} or `);return`/api/data/v9.0/deploymentstageruns?$filter=(${t})- &$select=_deploymentstageid_value,deploymentstagerunid,stagerunstatus,operation,operationstatus,suboperation,artifactname`}A.deployOperationStatusUrl=Q3;function X3(e){return`/api/data/v9.0/solutions(${e})- ?$select=solutionid,uniquename,version`}A.devSolutionInfoUrl=X3;function Z3(e){return`/api/data/v9.0/deploymentenvironments+ &$select=_deploymentstageid_value,deploymentstagerunid,stagerunstatus,operation,operationstatus,suboperation,artifactname`}P.deployOperationStatusUrl=MK;function xK(e){return`/api/data/v9.0/solutions(${e})+ ?$select=solutionid,uniquename,version`}P.devSolutionInfoUrl=xK;function FK(e){return`/api/data/v9.0/deploymentenvironments?$select=deploymentenvironmentid,environmentid,environmenttype,name- &$filter=(environmentid eq '${e}')`}A.retrieveDeploymentEnvironmentInfoUrl=Z3;var eV=e=>`/api/data/v9.0/systemusers+ &$filter=(environmentid eq '${e}')`}P.retrieveDeploymentEnvironmentInfoUrl=FK;var UK=e=>`/api/data/v9.0/systemusers?$select=azureactivedirectoryobjectid- &$filter=(applicationid eq '${e}')`;A.SPNPrincipalIdUrl=eV;function tV(){return"/api/data/v9.0/appmodules?$filter=(uniquename eq 'AppDeploymentConfiguration')"}A.retrieveDeploymentPipelineConfigAppUrl=tV;A.retrieveFeatureControlSettingsByNamespaceUrl="/api/data/v9.1/RetrieveFeatureControlSettingsByNamespace";function rV(e){return`/api/data/v9.0/settingdefinitions${e}`}A.getSettingDefinitionsUri=rV;A.OrgSettingOverrideName="organizationsettings";function nV(e,t=!1){let r=`/api/data/v9.0/${A.OrgSettingOverrideName}${e}`;return t?`${A.cdsServiceUrl}${r}`:r}A.getOrgSettingOverrideUri=nV;A.AppSettingOverrideName="appsettings";function iV(e,t=!1){let r=`/api/data/v9.0/${A.AppSettingOverrideName}${e}`;return t?`${A.cdsServiceUrl.replace("/$","")}${r}`:r}A.getAppSettingOverrideUri=iV;var Sl;(function(e){e[e.All=0]="All",e[e.IsPlatformOnly=1]="IsPlatformOnly",e[e.NotPlatformOnly=2]="NotPlatformOnly"})(Sl||(A.RetrievePlatform=Sl={}));function oV(e,t,r,n=Sl.All,i=!1){let o=[];e&&o.push(`AppUniqueName='${e}'`),t!=null&&o.push(`ReleaseLevel=${t}`),r&&o.push(`RetrieveHiddenSettings=${r}`),n!==Sl.All&&o.push(`RetrievePlatformSettings=${n===Sl.IsPlatformOnly?1:0}`);let a="/api/data/v9.0/RetrieveUnpublishedOverridableSettingsInfo";return o.length&&(a=`${a}(${o.join(",")})`),i?`${A.cdsServiceUrl}${a}`:a}A.getPowerSettingsUri=oV;function aV(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=aV;function sV(e=!1){let t="/api/data/v9.0/SaveSettingValue()";return e?`${A.cdsServiceUrl}${t}`:t}A.getSavePowerSettingUri=sV;A.retrieveUnpublishedSuffix="Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()";function lV(e){return`tools/systemcustomization/businessrules/businessRulesDesigner.aspx?BRlaunchpoint=BRGrid&appSolutionId={${e}}`}A.getBusinessRuleDesignerUri=lV;function hE({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=hE;function uV({baseUrl:e,environmentInstanceUrl:t,entityLogicalName:r,recordId:n}){let i=e||hE({environmentInstanceUrl:t,entityLogicalName:r});return i&&n?`${i}&id=${n}`:void 0}A.getUCIEntityRecordEditUrl=uV;A.retrieveOrganizationResources=`${A.cdsServiceUrl}api/data/v9.0/RetrieveOrganizationResources`});var bE=v(Mc=>{"use strict";Object.defineProperty(Mc,"__esModule",{value:!0});Mc.DataverseClient=void 0;var cV=Km(),Fo=Q(),gE=ye(),dV=new Set(["entitydefinitions","relationshipdefinitions","globaloptionsetdefinitions"]);function fV(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 dV.has(s)}function pV(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 yE(e,t){var r;if(!fV(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 Ym=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}/${cV.xrmApiUrl}${n}`}async send(t,r){try{return await r()}catch(n){throw n instanceof Fo.SdkError?n:new Fo.ConnectionError(t,0,n instanceof Error?n.message:String(n),n)}}get(t,r){let n=this.apiUrl(t),i=yE(t,r);return(0,gE.resendDeadlockVictim)(()=>this.send(n,()=>this.httpClient.get(n,i)))}getAbsolute(t,r){this.assertSameOrigin(t);let n=yE(pV(t),r);return(0,gE.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 Fo.InvalidArgumentError(`Refusing to follow a malformed absolute URL: '${t}'`)}if(r.protocol!==n.protocol||r.host!==n.host)throw new Fo.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 Fo.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 Fo.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 Fo.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)))}};Mc.DataverseClient=Ym});var CE=v(or=>{"use strict";Object.defineProperty(or,"__esModule",{value:!0});or.findColumns=or.findTables=or.readCheckColumns=or.readColumnHints=or.fetchEntityMetadataFromApi=or.COLUMN_DETAIL_VERSION=void 0;var qc=ye(),br=le();function Xr(e){var t,r;return(r=(t=e?.UserLocalizedLabel)===null||t===void 0?void 0:t.Label)!==null&&r!==void 0?r:""}or.COLUMN_DETAIL_VERSION=2;function Qm(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 Mo(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 Uc(e,t){return(await Vc(e,t)).rows}async function Vc(e,t){var r,n;let i=await e.get(t);return i.status<200||i.status>=300?{rows:[],ok:!1}:{rows:(n=(r=i.body)===null||r===void 0?void 0:r.value)!==null&&n!==void 0?n:[],ok:!0}}function Gr(e){return`/EntityDefinitions(LogicalName='${(0,br.odataPathLiteral)(e)}')`}async function mV(e,t,r){let n=await Uc(e,`${Gr(t)}/Attributes/Microsoft.Dynamics.CRM.StringAttributeMetadata${(0,br.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 hV(e){return`${Gr(e)}/Attributes/Microsoft.Dynamics.CRM.PicklistAttributeMetadata${(0,br.odataQuery)([["$select","LogicalName"],["$expand","OptionSet($select=Options)"]])}`}async function gV(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:Xr(a.Label),...Mo(a.Label)?{localizedLabel:Mo(a.Label)}:{}}}))}}function Xm(e){var t;return{value:(t=e.Value)!==null&&t!==void 0?t:0,label:Xr(e.Label),...e.InvariantName?{invariantName:e.InvariantName}:{},...e.Color?{color:e.Color}:{}}}async function yV(e,t,r){var n;let i=c=>Vc(e,c).catch(()=>({rows:[],ok:!1})),o=["MultiSelectPicklistAttributeMetadata","StateAttributeMetadata","StatusAttributeMetadata"],a=await Promise.all([r.catch(()=>({rows:[],ok:!1})),...o.map(c=>i(`${Gr(t)}/Attributes/Microsoft.Dynamics.CRM.${c}${(0,br.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=>Qm(f.Label)),s.set(d.LogicalName,d.OptionSet.Options.map(Xm)));let u=await i(`${Gr(t)}/Attributes/Microsoft.Dynamics.CRM.BooleanAttributeMetadata${(0,br.odataQuery)([["$select","LogicalName"],["$expand","OptionSet($select=TrueOption,FalseOption)"]])}`);for(let c of u.rows){let d=c.OptionSet;d?.TrueOption&&d.FalseOption&&(l=l&&Qm(d.TrueOption.Label)&&Qm(d.FalseOption.Label),s.set(c.LogicalName,[Xm(d.FalseOption),Xm(d.TrueOption)]))}return{byColumn:s,complete:l&&u.ok&&a.every(c=>c.ok)}}async function bV(e,t,r){let{rows:n,ok:i}=await Vc(e,`${Gr(t)}/Attributes/Microsoft.Dynamics.CRM.LookupAttributeMetadata${(0,br.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 Bc(e,t){return e<t?-1:e>t?1:0}var vE={OneToMany:0,ManyToOne:1,ManyToMany:2};function vV(e,t){return vE[e.type]-vE[t.type]||Bc(e.schemaName,t.schemaName)||Bc(e.relatedEntity,t.relatedEntity)||Bc(e.relatedAttribute,t.relatedAttribute)}async function wV(e,t){var r,n,i,o;let a=[],s=await Uc(e,`${Gr(t)}/OneToManyRelationships${(0,br.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 Uc(e,`${Gr(t)}/ManyToOneRelationships${(0,br.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 Uc(e,`${Gr(t)}/ManyToManyRelationships${(0,br.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(vV)}async function CV(e,t){var r,n,i,o,a;let s=`${Gr(t)}`+(0,br.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,qc.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:Xr(g.DisplayName),...Mo(g.DisplayName)?{localizedDisplayName:Mo(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}:{},...Xr(g.Description)?{description:Xr(g.Description)}:{}}}).sort((g,b)=>Bc(g.logicalName,b.logicalName)),d=new Map(c.map(g=>[g.logicalName,g])),f=Vc(e,hV(t)),[,,m,p,h]=await Promise.all([mV(e,t,d),gV(f,d),yV(e,t,f),bV(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:Xr(u.DisplayName),...Mo(u.DisplayName)?{localizedDisplayName:Mo(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,...Xr(u.Description)?{description:Xr(u.Description)}:{},columnDetailComplete:m.complete&&p,columnDetailVersion:or.COLUMN_DETAIL_VERSION,attributes:c,relationships:h}}or.fetchEntityMetadataFromApi=CV;var wE=40;async function Zm(e,t,r,n){var i,o;let a=[...new Set(n.filter(l=>l!==""))],s=[];for(let l=0;l<a.length;l+=wE){let u=a.slice(l,l+wE).map(f=>`LogicalName eq '${(0,br.odataLiteral)(f)}'`).join(" or "),c=t+(0,br.odataQuery)([["$select",r],["$filter",u]]),d=(0,qc.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 EV(e,t,r){return(await Zm(e,`${Gr(t)}/Attributes`,"LogicalName,AttributeType,DisplayName",r)).map(i=>{var o;let a=Mo(i.DisplayName);return{logicalName:i.LogicalName,displayName:Xr(i.DisplayName),...a?{localizedDisplayName:a}:{},attributeType:(o=i.AttributeType)!==null&&o!==void 0?o:"Unknown"}})}or.readColumnHints=EV;async function AV(e,t,r){let i=(await Zm(e,`${Gr(t)}/Attributes`,"LogicalName,AttributeType,DisplayName,IsCustomAttribute",r)).map(s=>{var l;return{logicalName:s.LogicalName,displayName:Xr(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 Zm(e,`${Gr(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}or.readCheckColumns=AV;async function SV(e,t,r){var n,i;let o=`/EntityDefinitions${(0,br.odataQuery)([["$select","LogicalName,SchemaName,EntitySetName,DisplayName,IsCustomEntity"]])}`,s=(i=(n=(0,qc.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:Xr(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}or.findTables=SV;async function NV(e,t,r,n){var i,o;let a=`${Gr(t)}/Attributes`+(0,br.odataQuery)([["$select","LogicalName,SchemaName,DisplayName,AttributeType,IsCustomAttribute"]]),l=(o=(i=(0,qc.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:Xr(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}or.findColumns=NV});var rh=v(vr=>{"use strict";Object.defineProperty(vr,"__esModule",{value:!0});vr.renderTypeRegistrations=vr.buildGenPageLegacyEnums=vr.renderGenPageAuthoringTypes=vr.buildGenPageRuntimeTypes=vr.toDesignerEntity=vr.TABLE_LOGICAL_NAME=void 0;vr.TABLE_LOGICAL_NAME=/^[a-z_][a-z0-9_]*$/;function eh(e){return e.replace(/[\r\n\u2028\u2029]+/g," ")}var _V=new Set(["createdby","createdon","createdonbehalfby","importsequencenumber","modifiedby","modifiedon","modifiedonbehalfby","overriddencreatedon","ownerid","owningbusinessunit","owningteam","owninguser","timezoneruleversionnumber","utcconversiontimezonecode","versionnumber"]);function Gc(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=Gc(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 EE(e,t){return e.logicalName<t.logicalName?-1:e.logicalName>t.logicalName?1:0}function NE(e){return!_V.has(e.logicalName)&&(!e.attributeOf||Gc(e)==="image")&&e.isValidForRead!==!1}var AE=new Set(["boolean","picklist","multiselectpicklist","state","status"]);function _E(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(EE),i=e.attributes.filter(o=>!r.has(o.logicalName)).sort(EE);return[...n,...i]}function th(e){var t;let r=[],n=new Set,i=_E(e);for(let o of i){let a=Gc(o),s=a==="image";NE(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))}}vr.toDesignerEntity=th;function TE(e,t="None"){let r={};for(let n of e)r[n.logicalName]=th(n);return OE(r,t)}vr.buildGenPageRuntimeTypes=TE;var DE=`export interface TableRegistrations extends BaseTableRegistrations {-`,IE=`export interface EnumRegistrations extends BaseEnumRegistrations {-`;function TV(e,t){return e.length>0?TE(e,t).text:RE(`${DE}}-`,`${IE}}-`,"","")}vr.renderGenPageAuthoringTypes=TV;function DV(e){let t=new Set;for(let n of e)for(let i of th(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 _E(n)){let o=`${n.logicalName}_${i.logicalName}`,a=SE(i);if(NE(i)||!AE.has(Gc(i))||!a||t.has(o)||r.has(o))continue;let s={name:o,runtime:{},labels:new Map};r.set(o,{declaration:PE(o,a,!1,s),model:s})}return r}vr.buildGenPageLegacyEnums=DV;function OE(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=IE,c="",d="";for(let f of o){s&&f.Description&&(c+=`// ${eh(f.Description)}+ &$filter=(applicationid eq '${e}')`;P.SPNPrincipalIdUrl=UK;function qK(){return"/api/data/v9.0/appmodules?$filter=(uniquename eq 'AppDeploymentConfiguration')"}P.retrieveDeploymentPipelineConfigAppUrl=qK;P.retrieveFeatureControlSettingsByNamespaceUrl="/api/data/v9.1/RetrieveFeatureControlSettingsByNamespace";function BK(e){return`/api/data/v9.0/settingdefinitions${e}`}P.getSettingDefinitionsUri=BK;P.OrgSettingOverrideName="organizationsettings";function VK(e,t=!1){let n=`/api/data/v9.0/${P.OrgSettingOverrideName}${e}`;return t?`${P.cdsServiceUrl}${n}`:n}P.getOrgSettingOverrideUri=VK;P.AppSettingOverrideName="appsettings";function GK(e,t=!1){let n=`/api/data/v9.0/${P.AppSettingOverrideName}${e}`;return t?`${P.cdsServiceUrl.replace("/$","")}${n}`:n}P.getAppSettingOverrideUri=GK;var Sf;(function(e){e[e.All=0]="All",e[e.IsPlatformOnly=1]="IsPlatformOnly",e[e.NotPlatformOnly=2]="NotPlatformOnly"})(Sf||(P.RetrievePlatform=Sf={}));function jK(e,t,n,r=Sf.All,i=!1){let o=[];e&&o.push(`AppUniqueName='${e}'`),t!=null&&o.push(`ReleaseLevel=${t}`),n&&o.push(`RetrieveHiddenSettings=${n}`),r!==Sf.All&&o.push(`RetrievePlatformSettings=${r===Sf.IsPlatformOnly?1:0}`);let a="/api/data/v9.0/RetrieveUnpublishedOverridableSettingsInfo";return o.length&&(a=`${a}(${o.join(",")})`),i?`${P.cdsServiceUrl}${a}`:a}P.getPowerSettingsUri=jK;function WK(e,t,n,r=!1){let i=[`SettingName='${e}'`];t!==void 0&&i.push(`SolutionName='${t}'`),n!==void 0&&i.push(`AppUniqueName='${n}'`);let o="/api/data/v9.0/RetrieveUnpublishedSettingInfo";return i.length&&(o=`${o}(${i.join(",")})`),r?`${P.cdsServiceUrl}${o}`:o}P.getPowerSettingUri=WK;function zK(e=!1){let t="/api/data/v9.0/SaveSettingValue()";return e?`${P.cdsServiceUrl}${t}`:t}P.getSavePowerSettingUri=zK;P.retrieveUnpublishedSuffix="Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()";function HK(e){return`tools/systemcustomization/businessrules/businessRulesDesigner.aspx?BRlaunchpoint=BRGrid&appSolutionId={${e}}`}P.getBusinessRuleDesignerUri=HK;function PD({environmentInstanceUrl:e,entityLogicalName:t}){return e&&t?`${e}main.aspx?cmdbar=true&forceUCI=1&navbar=off&newWindow=true&pageType=entityRecord&etn=${t}`:void 0}P.getUCIEntityRecordBaseUrl=PD;function KK({baseUrl:e,environmentInstanceUrl:t,entityLogicalName:n,recordId:r}){let i=e||PD({environmentInstanceUrl:t,entityLogicalName:n});return i&&r?`${i}&id=${r}`:void 0}P.getUCIEntityRecordEditUrl=KK;P.retrieveOrganizationResources=`${P.cdsServiceUrl}api/data/v9.0/RetrieveOrganizationResources`});var $D=C(oc=>{"use strict";Object.defineProperty(oc,"__esModule",{value:!0});oc.readOnlyDataverse=oc.DataverseClient=void 0;var JK=zv(),$s=Y(),RD=pe(),YK=new Set(["entitydefinitions","relationshipdefinitions","globaloptionsetdefinitions"]);function QK(e){var t,n,r,i;let o=e.split("?")[0].split("/").filter(u=>u!==""),a=((t=o[0])===null||t===void 0?void 0:t.toLowerCase())==="api"&&((n=o[1])===null||n===void 0?void 0:n.toLowerCase())==="data"&&/^v\d/i.test((r=o[2])!==null&&r!==void 0?r:""),s=((i=o[a?3:0])!==null&&i!==void 0?i:"").split("(")[0].toLowerCase();return YK.has(s)}function XK(e){let t=e.indexOf("://"),n=t===-1?"":e.slice(t+3),r=n.search(/[/?#]/),i=r===-1?"":n.slice(r),o=i.search(/[?#]/);return o===-1?i:i.slice(0,o)}function kD(e,t){var n;if(!QK(e))return t;let r=(n=t?.headers)!==null&&n!==void 0?n:{};return Object.keys(r).some(i=>i.toLowerCase()==="consistency")?t:{...t,headers:{...r,Consistency:"Strong"}}}var Kv=class e{constructor(t,n,r,i=1){this.instanceUrl=t,this.httpClient=n,this.solutionUniqueName=r,this.readConcurrency=i}withSolution(t){return this.solutionUniqueName?{...t,headers:{...t?.headers,"MSCRM.SolutionUniqueName":this.solutionUniqueName}}:t}withoutSolution(){return this.solutionUniqueName===void 0?this:new e(this.instanceUrl,this.httpClient,void 0,this.readConcurrency)}withTransport(t){return new e(this.instanceUrl,t(this.httpClient),this.solutionUniqueName,this.readConcurrency)}apiUrl(t){let n=this.instanceUrl.replace(/\/+$/,""),r=t.startsWith("/")?t:`/${t}`;return`${n}/${JK.xrmApiUrl}${r}`}async send(t,n){try{return await n()}catch(r){throw r instanceof $s.SdkError?r:new $s.ConnectionError(t,0,r instanceof Error?r.message:String(r),r)}}get(t,n){let r=this.apiUrl(t),i=kD(t,n);return(0,RD.resendDeadlockVictim)(()=>this.send(r,()=>this.httpClient.get(r,i)))}getAbsolute(t,n){this.assertSameOrigin(t);let r=kD(XK(t),n);return(0,RD.resendDeadlockVictim)(()=>this.send(t,()=>this.httpClient.get(t,r)))}assertSameOrigin(t){let n,r;try{n=new URL(t),r=new URL(this.instanceUrl)}catch{throw new $s.InvalidArgumentError(`Refusing to follow a malformed absolute URL: '${t}'`)}if(n.protocol!==r.protocol||n.host!==r.host)throw new $s.InvalidArgumentError(`Refusing to follow a cross-origin link ('${n.origin}' is not the configured instance '${r.origin}'); server-driven pagination must stay on-instance.`)}post(t,n,r){let i=this.apiUrl(t);return this.send(i,()=>this.httpClient.post(i,n,this.withSolution(r)))}get supportsAtomicBatch(){return typeof this.httpClient.postRaw=="function"}get supportsPut(){return typeof this.httpClient.put=="function"}get solutionName(){return this.solutionUniqueName}postBatch(t,n,r){if(!this.httpClient.postRaw)throw new $s.InvalidArgumentError("The injected HttpClient does not implement postRaw(), required for atomic $batch change sets");let i=this.apiUrl("/$batch"),o={...r,headers:{...r?.headers,"Content-Type":`multipart/mixed;boundary=${n}`}};return this.send(i,()=>this.httpClient.postRaw(i,t,o))}patch(t,n,r){let i=this.apiUrl(t);return this.send(i,()=>this.httpClient.patch(i,n,this.withSolution(r)))}get supportsBinaryPatch(){return typeof this.httpClient.patchRaw=="function"}patchRaw(t,n,r){if(!this.httpClient.patchRaw)throw new $s.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,n,this.withSolution(r)))}put(t,n,r){if(!this.httpClient.put)throw new $s.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,n,this.withSolution(r)))}delete(t,n){let r=this.apiUrl(t);return this.send(r,()=>this.httpClient.delete(r,this.withSolution(n)))}readOnly(){let t={gets:0,refusedWrites:[]},n=this.httpClient,r=o=>a=>(t.refusedWrites.push(`${o} ${a}`),Promise.reject(new $s.SdkError("PREVIEW_WRITE_REFUSED",`A pre-push check attempted a write (${o} ${a}); it may only read. This is a defect in the SDK.`))),i={get:(o,a)=>(t.gets+=1,n.get(o,a)),post:r("POST"),patch:r("PATCH"),delete:r("DELETE")};return typeof n.put=="function"&&(i.put=r("PUT")),typeof n.postRaw=="function"&&(i.postRaw=r("POST")),typeof n.patchRaw=="function"&&(i.patchRaw=r("PATCH")),{client:new e(this.instanceUrl,i,this.solutionUniqueName,this.readConcurrency),guard:t}}};oc.DataverseClient=Kv;function ZK(e){return{apiUrl:t=>e.apiUrl(t),get:(t,n)=>e.get(t,n),getAbsolute:(t,n)=>e.getAbsolute(t,n),readConcurrency:e.readConcurrency}}oc.readOnlyDataverse=ZK});var Xv=C(dt=>{"use strict";Object.defineProperty(dt,"__esModule",{value:!0});dt.assertOneWritePerRow=dt.commandApi=dt.readCommandBarRows=dt.fetchEntityMetadataId=dt.isStorableLocation=dt.COMMAND_PARENT_LOCATION_UNREADABLE_CODE=dt.COMMAND_DUPLICATE_ROW_CODE=dt.COMMAND_ROW_NOT_IN_BAR_CODE=dt.COMMAND_TABLE_MISMATCH_CODE=void 0;var Yv=Ke(),UD=qi(),Qr=pe(),Ho=Y(),Xr=ae();dt.COMMAND_TABLE_MISMATCH_CODE="COMMAND_TABLE_MISMATCH";dt.COMMAND_ROW_NOT_IN_BAR_CODE="COMMAND_ROW_NOT_IN_BAR";dt.COMMAND_DUPLICATE_ROW_CODE="COMMAND_DUPLICATE_ROW";dt.COMMAND_PARENT_LOCATION_UNREADABLE_CODE="COMMAND_PARENT_LOCATION_UNREADABLE";function qD(e){return typeof e=="number"&&Number.isInteger(e)&&e>=0&&e<=6}dt.isStorableLocation=qD;var eJ="OnClickEventJavaScriptWebResourceId($select=name,webresourceid),IconWebResourceId($select=name,webresourceid)";async function _h(e,t){let n=`/EntityDefinitions(LogicalName='${(0,Xr.odataPathLiteral)(t)}')${(0,Xr.odataQuery)([["$select","MetadataId"]])}`,i=(0,Qr.ensureSuccess)(await e.get(n),e.apiUrl(n)).body,o=i?.MetadataId;return o?(0,Xr.normalizeGuid)(o,"entityMetadataId"):""}dt.fetchEntityMetadataId=_h;function Qv(e,t){return t?`_contextentity_value eq ${t}`:`contextvalue eq '${(0,Xr.odataLiteral)(e)}'`}function ac(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 LD(e,t){let n=e.entityLogicalName;if(t===void 0)return n;if(typeof n!="string"||n.toLowerCase()!==t.toLowerCase())throw new Ho.SdkError(dt.COMMAND_TABLE_MISMATCH_CODE,`Refusing to push command '${t}': its JSON names table '${String(n)}'. 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 MD(e,t,n){let r=await _h(e,t);if(n){let i=(0,Xr.normalizeGuid)(n,"entityMetadataId");if(i!==r)throw new Ho.SdkError(dt.COMMAND_TABLE_MISMATCH_CODE,`Refusing to push command '${t}': it was fetched for table id ${i}, but table '${t}' is ${r||"not resolvable"} on the server \u2014 the table was re-created, or the local copy edited. `+ac(t))}return r}function BD(e,t,n,r,i){let o=`/appactions${(0,Xr.odataQuery)([["$expand",eJ],["$filter",Qv(t,n)]])}`;return(0,Yv.collectPages)(e,o,r,i)}dt.readCommandBarRows=BD;dt.commandApi={async get(e,t){let n=t,r=await _h(e,n),i,o=await BD(e,n,r,"fetchArtifact('command')",u=>{i=u}),a={entityLogicalName:n,entityMetadataId:r,appActions:o},s={};for(let u of o){let l=typeof u.appactionid=="string"?u.appactionid:void 0;if(l){let c=u["@odata.etag"];s[(0,Xr.normalizeGuid)(l,"appactionid")]=typeof c=="string"?c:null}}return{raw:a,etag:i?(0,Qr.readEtag)(i):null,memberEtags:s}},async list(e,t){let n=t?.entityLogicalName;return n?[{type:"command",id:n,name:`${n} commands`,entityLogicalName:n,isDirty:!1}]:[]},async create(e,t,n,r=void 0){let i=t,o=LD(i,n),a=await MD(e,o,i.entityMetadataId);return xD(e,o,{...i,entityMetadataId:a},!1,void 0,r)},async update(e,t,n,r,i,o=void 0,a){let s=n,u=LD(s,t),l=await MD(e,u,s.entityMetadataId);return xD(e,u,{...s,entityMetadataId:l},!0,i,a)},planPush(e,t,n){return(0,UD.planPushThrough)(dt.commandApi,e,t,n)},async delete(e,t){let n=await _h(e,t),r=`/appactions${(0,Xr.odataQuery)([["$select","appactionid"],["$filter",Qv(t,n)]])}`,i=await(0,Yv.collectPages)(e,r,"deleteArtifact('command')");for(let o of i)o.appactionid&&await(0,Qr.deleteRecord)(e,"appactions",o.appactionid)}};async function xD(e,t,n,r,i,o){let a=n.entityMetadataId?(0,Xr.normalizeGuid)(n.entityMetadataId,"entityMetadataId"):"",s=await rJ(e,t,n,a,r,i,o);if(o)return o.reached({effects:tJ(s),attemptsWrite:s.writes.length+s.deletes.length>0});let u={};try{await aJ(e,s,a,u)}catch(l){throw(0,Ho.withPartialTokens)(l,{memberEtags:u})}return{id:n.entityLogicalName,etag:null,memberEtags:u}}function tJ(e){return[...e.writes.map(n=>{if(n.kind==="patch")return{componentName:"appaction",componentId:n.id,identity:"known",operation:"update"};let r=n.row.body.appactionid;return typeof r=="string"&&r!==""?{componentName:"appaction",componentId:_f(r),identity:"known",operation:"create"}:{componentName:"appaction",identity:"assignedAtWrite",operation:"create"}}),...e.deletes.map(n=>({componentName:"appaction",componentId:n.id,identity:"known",operation:"delete"}))]}function _f(e){return e.replace(/[{}]/g,"").toLowerCase()}function VD(e,t){var n;let r=new Map,i=[...t.rows.map(o=>[o.appactionid,"written"]),...((n=t.deletedRowIds)!==null&&n!==void 0?n:[]).map(o=>[o,"deleted"])];for(let[o,a]of i){let s=_f(o),u=r.get(s);if(u===void 0){r.set(s,a);continue}throw new Ho.SdkError(dt.COMMAND_DUPLICATE_ROW_CODE,u===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.`)}}dt.assertOneWritePerRow=VD;var nJ={entities:/^\/entities\(([^()]+)\)$/,appactions:/^\/appactions\(([^()]+)\)$/};function Jv(e,t){let n=nJ[t].exec(e);return n?_f(n[1]):void 0}async function rJ(e,t,n,r,i,o,a){var s,u,l,c;let d=(y,b)=>a?.observe({guard:"ifMatch",componentName:"appaction",componentId:y,held:typeof b=="string"?b:null,status:"missingHeld"});VD(t,n);let f=sJ(n.rows),p=new Set(f.map(y=>_f(y.appactionid))),m={writes:[],deletes:[]};for(let y of f){let b=y.body["[email protected]"];if(b!==void 0&&!(typeof b=="string"&&r!==""&&Jv(b,"entities")===r))throw new Ho.SdkError(dt.COMMAND_TABLE_MISMATCH_CODE,`Refusing to push command '${t}': app action '${y.appactionid}' binds to ${typeof b=="string"?`'${b}'`:String(b)}, not to table '${t}' (${r?`/entities(${r})`:"whose id is not resolvable"}). `+ac(t));let E=y.body["[email protected]"];if(typeof E=="string"){let w=Jv(E,"appactions");if(w===void 0||!p.has(w))throw new Ho.SdkError(dt.COMMAND_ROW_NOT_IN_BAR_CODE,`Refusing to push command '${t}': app action '${y.appactionid}' would be placed under '${E}', which is not a row of this command. `+ac(t))}if(i&&y.exists){let w=(0,Xr.normalizeGuid)(y.appactionid,"id"),_=(s=o?.[w])!==null&&s!==void 0?s:y.etag;if(!(0,Qr.isVersionToken)(_))throw d(w,_),FD(t,w,"update",_);m.writes.push({kind:"patch",row:y,id:w,token:_})}else{if(b===void 0&&!r)throw new Ho.SdkError("COMMAND_CONTEXT_ENTITY_UNRESOLVED",`Cannot create app action '${y.appactionid}' for entity '${n.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.`);m.writes.push({kind:"post",row:y})}}for(let y of(u=n.deletedRowIds)!==null&&u!==void 0?u:[]){let b=(0,Xr.normalizeGuid)(y,"id"),E=o?.[b];if(!(0,Qr.isVersionToken)(E))throw d(b,E),FD(t,b,"delete",E);m.deletes.push({id:b,token:E})}let h=[...m.writes.flatMap(y=>y.kind==="patch"?[{id:y.id,verb:"update"}]:[]),...m.deletes.map(y=>({id:y.id,verb:"delete"}))],g=m.writes.filter(y=>y.kind==="post"&&y.row.inheritsParentLocation===!0);if(g.length>0&&!i)throw GD(t,g[0].row.appactionid,void 0,void 0);if(h.length>0||g.length>0){let y=await oJ(e,t,r,g.length>0),b=h.find(E=>!y.has(E.id));if(b)throw a?.observe({guard:"membership",componentName:"appaction",componentId:b.id,status:"goneOnServer",detail:"not in the table's command bar on the server"}),new Ho.SdkError(dt.COMMAND_ROW_NOT_IN_BAR_CODE,`Refusing to push command '${t}': it would ${b.verb} app action '${b.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. `+ac(t));if(g.length>0&&iJ(t,m,y),a){let E=[...m.writes.flatMap(w=>w.kind==="patch"?[{id:w.id,token:w.token}]:[]),...m.deletes];for(let{id:w,token:_}of E){let I=(c=(l=y.get(w))===null||l===void 0?void 0:l.token)!==null&&c!==void 0?c:null;a.observe({guard:"ifMatch",componentName:"appaction",componentId:w,held:_,server:I,status:(0,UD.compareTokens)(_,I)})}}}return m}function iJ(e,t,n){let r=new Map;t.writes=t.writes.map(i=>{var o;if(i.kind!=="post")return i;let a=i.row;if(a.inheritsParentLocation===!0){let s=a.body["[email protected]"],u=typeof s=="string"?Jv(s,"appactions"):void 0,l=u===void 0?void 0:r.has(u)?r.get(u):(o=n.get(u))===null||o===void 0?void 0:o.location;if(!qD(l))throw GD(e,a.appactionid,u,l);a={...a,body:{...a.body,location:l}}}return r.set(_f(a.appactionid),a.body.location),{...i,row:a}})}function GD(e,t,n,r){return new Ho.SdkError(dt.COMMAND_PARENT_LOCATION_UNREADABLE_CODE,`Refusing to push command '${e}': app action '${t}' is new and must be created at the Location its parent ${n?`'${n}' `:""}actually holds \u2014 the runtime shows a command only under a parent at the same Location \u2014 but the server's answer gives that parent ${r===void 0?"no Location":`the Location ${JSON.stringify(r)}`}. `+ac(e))}function FD(e,t,n,r){return new Ho.SdkError(Qr.UPDATE_NO_ETAG_CODE,`Refusing to push command '${e}': ${typeof r=="string"&&r!==""?`the token held for app action '${t}' ('${r}') is not a version`:`no token is held for app action '${t}'`}, so its ${n} could not be made conditional and would overwrite or remove a concurrent edit. `+ac(e))}async function oJ(e,t,n,r){let i=`/appactions${(0,Xr.odataQuery)([["$select",r?"appactionid,location":"appactionid"],["$filter",Qv(t,n)]])}`,o=await(0,Yv.collectPages)(e,i,"pushArtifact('command') bar membership"),a=new Map;for(let s of o)if(typeof s.appactionid=="string"){let u=s["@odata.etag"];a.set((0,Xr.normalizeGuid)(s.appactionid,"appactionid"),{token:typeof u=="string"?u:null,location:s.location})}return a}async function aJ(e,t,n,r){for(let i of t.writes)if(i.kind==="patch"){let o=(0,Qr.echoWrite)("appactionid",{"If-Match":i.token}),a=`/appactions(${i.id})${o.query}`,s=(0,Qr.ensureSuccess)(await e.patch(a,i.row.body,o.options),e.apiUrl(a));r[i.id]=(0,Qr.readEtag)(s)}else{let o=(0,Qr.echoWrite)("appactionid"),a=`/appactions${o.query}`,s={...i.row.body};s["[email protected]"]===void 0&&(s["[email protected]"]=`/entities(${n})`);let u=(0,Qr.ensureSuccess)(await e.post(a,s,o.options),e.apiUrl(a)),l=(0,Qr.readCreatedId)(u,"appactionid");l&&(r[(0,Xr.normalizeGuid)(l,"appactionid")]=(0,Qr.readEtag)(u))}for(let{id:i,token:o}of[...t.deletes].reverse())await(0,Qr.deleteRecord)(e,"appactions",i,o),delete r[i]}function sJ(e){let t=new Map(e.map(o=>[o.appactionid,o])),n=new Set,r=[],i=o=>{if(n.has(o.appactionid))return;let a=o.body["[email protected]"];if(typeof a=="string"){let s=/\(([^)]+)\)/.exec(a),u=s?t.get(s[1]):void 0;u&&i(u)}n.add(o.appactionid),r.push(o)};return e.forEach(i),r}});var aw=C(Ko=>{"use strict";Object.defineProperty(Ko,"__esModule",{value:!0});Ko.classifyCommandBar=Ko.inspectCommandBar=Ko.inspectionUnreadable=Ko.validateCommandInspectOptions=void 0;var jD=Xv(),Sn=Y(),uJ=pe(),Ih=ae(),lJ={0:"button",1:"flyout",2:"split",3:"group"},cJ={0:"form",1:"homeGrid",2:"subGrid",3:"associatedGrid"},rw=["form","homeGrid","subGrid","associatedGrid"],WD=["button","flyout","split"],dJ=new Set(["rowId","surface","label","menuPath","kind"]),fJ=new Set(["find","appModuleId"]),qu="inspectArtifact('command')";function YD(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function QD(e,t){if(typeof e!="string"||e.trim()==="")throw new Sn.InvalidArgumentError(`${qu}: the id must be the table's logical name (got ${JSON.stringify(e)}).`);if(t===void 0)return{appModuleId:null};if(!YD(t))throw new Sn.InvalidArgumentError(`${qu}: options must be an object when given.`);let n=Object.keys(t).find(o=>!fJ.has(o));if(n!==void 0)throw new Sn.InvalidArgumentError(`${qu}: '${n}' is not a command inspection option (only 'find' and 'appModuleId'${n==="expected"?"; 'expected' is the dashboard witness's":""}).`);let r=t.appModuleId===void 0?null:(0,Ih.normalizeGuid)(String(t.appModuleId),`${qu} appModuleId`);if(t.find===void 0)return{appModuleId:r};if(!Array.isArray(t.find))throw new Sn.InvalidArgumentError(`${qu}: 'find' must be an array of control queries.`);return{queries:t.find.map((o,a)=>pJ(o,a)),appModuleId:r}}Ko.validateCommandInspectOptions=QD;function pJ(e,t){var n;let r=`${qu} find[${t}]`;if(!YD(e))throw new Sn.InvalidArgumentError(`${r} must be an object.`);let i=Object.keys(e).find(a=>!dJ.has(a));if(i!==void 0)throw new Sn.InvalidArgumentError(`${r}: '${i}' is not a query field.`);if(typeof e.surface!="string"||!rw.includes(e.surface))throw new Sn.InvalidArgumentError(`${r}: surface must be one of ${rw.join(", ")} (got ${JSON.stringify(e.surface)}).`);if(e.label!==void 0&&(typeof e.label!="string"||e.label===""))throw new Sn.InvalidArgumentError(`${r}: label must be a non-empty string when given.`);if(e.rowId===void 0&&e.label===void 0)throw new Sn.InvalidArgumentError(`${r}: give the rowId recorded at creation (verification) or a label (discovery) \u2014 a query with neither would match every control.`);let o=e.rowId===void 0?void 0:(0,Ih.normalizeGuid)(String(e.rowId),`${r} rowId`);if(e.menuPath!==void 0&&(!Array.isArray(e.menuPath)||e.menuPath.some(a=>typeof a!="string")))throw new Sn.InvalidArgumentError(`${r}: menuPath must be an array of captions.`);if(e.kind!==void 0&&!WD.includes(e.kind))throw new Sn.InvalidArgumentError(`${r}: kind must be one of ${WD.join(", ")} (got ${JSON.stringify(e.kind)}).`);return{original:e,rowId:o,surface:e.surface,label:e.label,menuPath:(n=e.menuPath)!==null&&n!==void 0?n:[],kind:e.kind}}function iw(e,t){if(t instanceof Sn.InspectionUnreadableError)return t;let n=t instanceof Sn.ConnectionError&&t.statusCode>0?t.statusCode:void 0,r=t instanceof Error?t.message:String(t);return(0,Sn.attachCause)(new Sn.InspectionUnreadableError("command",e,n,`${r}.`),t)}Ko.inspectionUnreadable=iw;async function mJ(e,t,n,r){let i=QD(t,n),o,a;try{if(o=await(0,jD.fetchEntityMetadataId)(e,t),!o)throw new Sn.InspectionUnreadableError("command",t,void 0,"the table's MetadataId could not be read, so its command bar cannot be selected.");a=await(0,jD.readCommandBarRows)(e,t,o,qu)}catch(u){throw iw(t,u)}let s=(0,uJ.nowIso)();try{return XD(t,o,a,r,i,s)}catch(u){throw iw(t,u)}}Ko.inspectCommandBar=mJ;function hJ(e){var t;let n=typeof e=="string"?`'${e}'`:(t=JSON.stringify(e))!==null&&t!==void 0?t:String(e);return n.length>60?`${n.slice(0,60)}\u2026`:n}function ow(e,t,n,r){throw new Sn.InvalidArgumentError(`the row ${e} answered ${t} as ${hJ(n)}, not ${r}, so it is not one well-formed bar`)}function zD(e,t,n){let r=e[t];if(r==null)return null;if(typeof r=="string")try{return(0,Ih.normalizeGuid)(r,t)}catch{}return ow(n,t,r,"a GUID or null")}function Zv(e,t,n){let r=e[t];return r==null?!1:typeof r=="boolean"?r:ow(n,t,r,"a boolean or null")}function ew(e,t,n){let r=e[t];return r==null?"":typeof r=="string"?r:ow(n,t,r,"text or null")}function HD(e){return typeof e=="number"&&Number.isInteger(e)?e:null}function XD(e,t,n,r,i,o){var a,s;let u=new Map;for(let p of n){let m=p?.appactionid;if(typeof m!="string"||m==="")throw new Sn.InvalidArgumentError(`the row '${String((a=p?.name)!==null&&a!==void 0?a:"")}' has no appactionid (its primary key), so it cannot be identified`);let h=(0,Ih.normalizeGuid)(m,"appactionid");if(u.has(h))throw new Sn.InvalidArgumentError(`two rows answered with one appactionid (${h}), so the read is not one bar`);u.set(h,{obs:gJ(h,p,e,r),raw:p,codes:[],audience:null,placed:!1,chainApps:new Set,duplicate:!1,peers:[]})}let l=yJ(u);for(let p of u.values())bJ(p,u);for(let p of u.values())ZD(p,u,l);AJ(u);let c=CJ(r.project(e,t,n));for(let p of u.values())p.obs.pointer=(s=c.get(p.obs.rowId))!==null&&s!==void 0?s:null,p.obs.diagnostics=[...p.codes,...p.duplicate?["DUPLICATE_PROJECTED_ID"]:[],...p.obs.pointer===null?["NOT_PROJECTED"]:[]];let d=eP(u),f={type:"command",id:e,tableId:t,observedAt:o,rows:d.map(p=>p.obs),diagnostics:SJ(d)};return i.queries&&(f.found=i.queries.map(p=>IJ(p,u,i.appModuleId))),f}Ko.classifyCommandBar=XD;function gJ(e,t,n,r){var i,o;let a=HD(t.type),s=(i=a!==null?lJ[a]:void 0)!==null&&i!==void 0?i:"unknown",u=HD(t.location),l=zD(t,"_appmoduleid_value",e),c=ew(t,"name",e),d=ew(t,"buttonlabeltext",e),f=ew(t,"grouptitle",e),p=typeof t.sequence=="number"?t.sequence:typeof t.buttonsequencepriority=="number"?t.buttonsequencepriority:null,m={rowId:e,projectedId:r.projectedId(c,n),name:c,kind:s,label:s==="group"?"":d,groupTitle:s==="group"?f:null,location:u,surface:(o=u!==null?cJ[u]:void 0)!==null&&o!==void 0?o:null,placement:"undetermined",audienceAppId:null,scope:l?"app":"table",appModuleId:l,parentRowId:zD(t,"_parentappactionid_value",e),ancestors:[],menuPath:[],hidden:Zv(t,"hidden",e),ancestorHidden:!1,disabled:Zv(t,"isdisabled",e),managed:Zv(t,"ismanaged",e),sequence:p,pointer:null,diagnostics:[]},h=r.action(t);return h&&(m.action=h),m}function yJ(e){var t,n;let r=new Set,i=new Set;for(let o of e.keys()){let a=[],s=new Set,u=o;for(;u!==null&&e.has(u)&&!i.has(u)&&!s.has(u);)a.push(u),s.add(u),u=(n=(t=e.get(u))===null||t===void 0?void 0:t.obs.parentRowId)!==null&&n!==void 0?n:null;if(u!==null&&s.has(u))for(let l of a.slice(a.indexOf(u)))r.add(l);for(let l of a)i.add(l)}return r}function bJ(e,t){let n=[],r=new Set([e.obs.rowId]),i=e.obs.parentRowId;for(;i!==null&&!r.has(i);){let o=t.get(i);if(!o)break;n.push(o),r.add(i),i=o.obs.parentRowId}n.reverse(),e.obs.ancestors=n.map(o=>o.obs.rowId),e.obs.menuPath=n.filter(o=>o.obs.kind==="flyout"||o.obs.kind==="split").map(o=>o.obs.label),e.obs.ancestorHidden=n.some(o=>o.obs.hidden);for(let o of[e,...n])o.obs.appModuleId&&e.chainApps.add(o.obs.appModuleId)}function vJ(e,t){return e==="group"?t==="flyout"||t==="split":t==="group"}function ZD(e,t,n){if(e.placed)return;e.placed=!0;let r=e.obs,i=r.parentRowId!==null?t.get(r.parentRowId):void 0,o=[];if(r.kind==="unknown"&&o.push("UNKNOWN_KIND"),r.surface===null&&o.push("UNSUPPORTED_LOCATION"),r.kind!=="unknown"&&(r.parentRowId===null&&r.kind==="group"||i&&i.obs.kind!=="unknown"&&!vJ(r.kind,i.obs.kind))&&o.push("INVALID_PARENT_KIND"),n.has(r.rowId)&&o.push("CYCLE"),o.length>0){sc(e,"undetermined",o,i);return}if(i&&ZD(i,t,n),i&&i.obs.placement==="undetermined"){sc(e,"undetermined",["ANCESTOR_UNDETERMINED"],i);return}if(r.disabled){sc(e,"disabled",[],i);return}let a=[];if(r.parentRowId!==null&&!i&&a.push("PARENT_NOT_IN_BAR"),i&&i.obs.location!==r.location&&a.push("LOCATION_MISMATCH"),wJ(e,i)&&a.push("MIXED_APP_SCOPE"),a.length>0){sc(e,"unhosted",a,i);return}if(i&&i.obs.placement!=="served"){sc(e,"unhosted",["ANCESTOR_NOT_SERVED"],i);return}sc(e,"served",[],i)}function wJ(e,t){let n=e.obs.appModuleId;return!n||!t?!1:typeof t.audience=="string"&&t.audience!=="mixed"&&t.audience!==n}function sc(e,t,n,r){e.obs.placement=t,e.codes=n;let i=r&&r.placed?r.audience:null,o=e.obs.appModuleId;i==="mixed"||o&&i&&o!==i?e.audience="mixed":e.audience=o??i,e.obs.audienceAppId=e.audience==="mixed"?null:e.audience}function EJ(e,t){return e===null||t===null||e===t}function AJ(e){var t;let n=new Map;for(let r of e.values())if(r.obs.placement==="served"){let i=`${r.obs.surface}\0${r.obs.projectedId}`;n.set(i,[...(t=n.get(i))!==null&&t!==void 0?t:[],r])}for(let r of n.values())for(let i of r)i.peers=r.filter(o=>o!==i&&EJ(i.obs.audienceAppId,o.obs.audienceAppId)),i.duplicate=i.peers.length>0}function KD(e,t){return e.peers.some(n=>t===null||n.obs.audienceAppId===null||n.obs.audienceAppId===t)}function tw(e){var t;let n=(t=e?.a)===null||t===void 0?void 0:t.find(r=>r[0]==="appactionid");return typeof n?.[1]=="string"&&n[1]!==""?n[1].toLowerCase():void 0}function CJ(e){var t;let n=new Map,r=(o,a)=>{o&&!n.has(o.toLowerCase())&&n.set(o.toLowerCase(),a)},i=(o,a)=>{var s;r(tw(o.bag),a),o.flyoutGroups&&o.flyoutGroups.length>0?o.flyoutGroups.forEach((u,l)=>{var c;r((c=tw(u.bag))!==null&&c!==void 0?c:u.id,`${a}/flyoutGroups/${l}`)}):o.flyoutGroupId&&r(o.flyoutGroupId,`${a}/flyoutGroupId`),((s=o.children)!==null&&s!==void 0?s:[]).forEach((u,l)=>i(u,`${a}/children/${l}`))};return((t=e.commandBars)!==null&&t!==void 0?t:[]).forEach((o,a)=>{var s;((s=o.groups)!==null&&s!==void 0?s:[]).forEach((u,l)=>{var c;r(tw(u.bag),`/commandBars/${a}/groups/${l}`),((c=u.controls)!==null&&c!==void 0?c:[]).forEach((d,f)=>i(d,`/commandBars/${a}/groups/${l}/controls/${f}`))})}),n}function JD(e,t){var n,r;let i=((n=e.obs.sequence)!==null&&n!==void 0?n:0)-((r=t.obs.sequence)!==null&&r!==void 0?r:0);return i!==0?i:e.obs.rowId<t.obs.rowId?-1:e.obs.rowId>t.obs.rowId?1:0}function eP(e){var t;let n=new Map;for(let a of e.values())a.obs.placement==="served"&&a.obs.parentRowId!==null&&n.set(a.obs.parentRowId,[...(t=n.get(a.obs.parentRowId))!==null&&t!==void 0?t:[],a]);let r=[],i=new Set,o=a=>{var s;r.push(a),i.add(a.obs.rowId);for(let u of[...(s=n.get(a.obs.rowId))!==null&&s!==void 0?s:[]].sort(JD))o(u)};for(let a of rw)[...e.values()].filter(s=>s.obs.placement==="served"&&s.obs.parentRowId===null&&s.obs.surface===a).sort(JD).forEach(o);return[...e.values()].filter(a=>!i.has(a.obs.rowId)).sort((a,s)=>a.obs.rowId<s.obs.rowId?-1:a.obs.rowId>s.obs.rowId?1:0).forEach(a=>r.push(a)),r}var nw={UNSUPPORTED_LOCATION:e=>`Row ${e.rowId} has Location ${e.location===null?"(none)":e.location}, not a table command surface (0-3); where the runtime serves it was never measured.`,UNKNOWN_KIND:e=>`Row ${e.rowId} has an unknown type; it is not read as a button, and its serving is unmeasured.`,INVALID_PARENT_KIND:e=>`Row ${e.rowId} (${e.kind}) has a parent kind the platform refuses to store${e.parentRowId===null?" (a group at top level)":""}; its serving is unmeasured.`,CYCLE:e=>`Row ${e.rowId} is on a parent loop; its serving is unmeasured.`,PARENT_NOT_IN_BAR:e=>`Row ${e.rowId}'s parent ${e.parentRowId} is not a row of this table's bar; the runtime does not serve it.`,LOCATION_MISMATCH:e=>`Row ${e.rowId}'s Location ${e.location} differs from its parent's; the runtime serves it in neither tree.`,MIXED_APP_SCOPE:e=>`Row ${e.rowId} is bound to app ${e.appModuleId} under a chain bound to another app; it is served to neither.`,ANCESTOR_NOT_SERVED:e=>`Row ${e.rowId}'s own links are valid, but an ancestor is not served.`,ANCESTOR_UNDETERMINED:e=>`Row ${e.rowId}'s own links are valid, but an ancestor's serving is unmeasured.`,DUPLICATE_PROJECTED_ID:e=>`Served rows on ${e.surface} share the projected id '${e.projectedId}'; which one a client shows is not determined.`,NOT_PROJECTED:e=>`fetchArtifact's projection omits row ${e.rowId}.`};function SJ(e){var t;let n=[];for(let i of e)for(let o of i.codes)n.push({code:o,rowIds:[i.obs.rowId],message:nw[o](i.obs)});let r=new Map;for(let i of e)if(i.duplicate){let o=`${i.obs.surface}\0${i.obs.projectedId}`;r.set(o,[...(t=r.get(o))!==null&&t!==void 0?t:[],i])}for(let i of r.values())n.push({code:"DUPLICATE_PROJECTED_ID",rowIds:i.map(o=>o.obs.rowId),message:nw.DUPLICATE_PROJECTED_ID(i[0].obs)});for(let i of e)i.obs.pointer===null&&n.push({code:"NOT_PROJECTED",rowIds:[i.obs.rowId],message:nw.NOT_PROJECTED(i.obs)});return n}function NJ(e,t){return e.length===t.length&&e.every((n,r)=>n===t[r])}function _J(e,t,n,r){let i=e.obs;return i.surface!==null&&i.surface!==t.surface||[...e.chainApps].some(a=>a!==n)||t.kind!==void 0&&i.kind!=="unknown"&&i.kind!==t.kind||t.rowId!==void 0&&t.label!==void 0&&i.label!==t.label||i.placement==="disabled"||i.placement==="unhosted"?"ELSEWHERE":i.placement==="undetermined"||i.surface===null||t.kind!==void 0&&i.kind==="unknown"?"UNCERTAIN":NJ(i.menuPath,t.menuPath)?KD(e,n)||i.ancestors.some(a=>{let s=r.get(a);return s!==void 0&&KD(s,n)})?"UNCERTAIN":"MATCH":"ELSEWHERE"}function IJ(e,t,n){var r,i;let o=e.rowId!==void 0?"row":"caption",a=e.rowId!==void 0?[t.get(e.rowId)].filter(f=>f!==void 0):eP(t).filter(f=>f.obs.label===e.label),s=[],u=[],l=[];for(let f of a){let p=_J(f,e,n,t);p==="MATCH"?s.push(f):p==="UNCERTAIN"?l.push(f.obs.rowId):u.push(f.obs.rowId)}let c;o==="row"?c=a.length===0?"missing":s.length===1?"present":l.length>0?"indeterminate":"misplaced":l.length>0?c="indeterminate":s.length===1?c="present":s.length>1?c="ambiguous":c=u.length>0?"misplaced":"missing";let d=s.length===1?s[0].obs:void 0;return{query:{...e.original,...e.original.menuPath?{menuPath:[...e.original.menuPath]}:{}},identity:o,verdict:c,rowIds:s.map(f=>f.obs.rowId),elsewhere:u,uncertain:l,hidden:(r=d?.hidden)!==null&&r!==void 0?r:!1,ancestorHidden:(i=d?.ancestorHidden)!==null&&i!==void 0?i:!1}}});var uc=C(xa=>{"use strict";function TJ(e,t,n){if(n===void 0&&(n=Array.prototype),e&&typeof n.find=="function")return n.find.call(e,t);for(var r=0;r<e.length;r++)if(Object.prototype.hasOwnProperty.call(e,r)){var i=e[r];if(t.call(void 0,i,r,e))return i}}function uw(e,t){return t===void 0&&(t=Object),t&&typeof t.freeze=="function"?t.freeze(e):e}function OJ(e,t){if(e===null||typeof e!="object")throw new TypeError("target is not an object");for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n]);return e}var tP=uw({HTML:"text/html",isHTML:function(e){return e===tP.HTML},XML_APPLICATION:"application/xml",XML_TEXT:"text/xml",XML_XHTML_APPLICATION:"application/xhtml+xml",XML_SVG_IMAGE:"image/svg+xml"}),nP=uw({HTML:"http://www.w3.org/1999/xhtml",isHTML:function(e){return e===nP.HTML},SVG:"http://www.w3.org/2000/svg",XML:"http://www.w3.org/XML/1998/namespace",XMLNS:"http://www.w3.org/2000/xmlns/"}),Th=/[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]/,sw=new RegExp("[\\-\\.0-9"+Th.source.slice(1,-1)+"\\u00B7\\u0300-\\u036F\\u203F-\\u2040]"),DJ=new RegExp("^"+Th.source+sw.source+"*(?::"+Th.source+sw.source+"*)?$");xa.assign=OJ;xa.find=TJ;xa.freeze=uw;xa.MIME_TYPE=tP;xa.NAMESPACE=nP;xa.nameStartChar=Th;xa.nameChar=sw;xa.tagNamePattern=DJ});var ww=C(Ba=>{var lw=uc(),Jo=lw.find,Tf=lw.NAMESPACE,lc=lw.tagNamePattern;function PJ(e){return e!==""}function RJ(e){return e?e.split(/[\t\n\f\r ]+/).filter(PJ):[]}function kJ(e,t){return e.hasOwnProperty(t)||(e[t]=!0),e}function rP(e){if(!e)return[];var t=RJ(e);return Object.keys(t.reduce(kJ,{}))}function $J(e){return function(t){return e&&e.indexOf(t)!==-1}}function Df(e,t){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])}function ei(e,t){var n=e.prototype;if(!(n instanceof t)){let i=function(){};var r=i;i.prototype=t.prototype,i=new i,Df(n,i),e.prototype=n=i}n.constructor!=e&&(typeof e!="function"&&console.error("unknown Class:"+e),n.constructor=e)}var ti={},Bi=ti.ELEMENT_NODE=1,cc=ti.ATTRIBUTE_NODE=2,If=ti.TEXT_NODE=3,dP=ti.CDATA_SECTION_NODE=4,fP=ti.ENTITY_REFERENCE_NODE=5,LJ=ti.ENTITY_NODE=6,cw=ti.PROCESSING_INSTRUCTION_NODE=7,dw=ti.COMMENT_NODE=8,pP=ti.DOCUMENT_NODE=9,mP=ti.DOCUMENT_TYPE_NODE=10,Fa=ti.DOCUMENT_FRAGMENT_NODE=11,MJ=ti.NOTATION_NODE=12,mr={},Bn={},CIe=mr.INDEX_SIZE_ERR=(Bn[1]="Index size error",1),SIe=mr.DOMSTRING_SIZE_ERR=(Bn[2]="DOMString size error",2),Zr=mr.HIERARCHY_REQUEST_ERR=(Bn[3]="Hierarchy request error",3),NIe=mr.WRONG_DOCUMENT_ERR=(Bn[4]="Wrong document",4),iP=mr.INVALID_CHARACTER_ERR=(Bn[5]="Invalid character",5),_Ie=mr.NO_DATA_ALLOWED_ERR=(Bn[6]="No data allowed",6),IIe=mr.NO_MODIFICATION_ALLOWED_ERR=(Bn[7]="No modification allowed",7),hP=mr.NOT_FOUND_ERR=(Bn[8]="Not found",8),TIe=mr.NOT_SUPPORTED_ERR=(Bn[9]="Not supported",9),oP=mr.INUSE_ATTRIBUTE_ERR=(Bn[10]="Attribute in use",10),ho=mr.INVALID_STATE_ERR=(Bn[11]="Invalid state",11),OIe=mr.SYNTAX_ERR=(Bn[12]="Syntax error",12),DIe=mr.INVALID_MODIFICATION_ERR=(Bn[13]="Invalid modification",13),PIe=mr.NAMESPACE_ERR=(Bn[14]="Invalid namespace",14),RIe=mr.INVALID_ACCESS_ERR=(Bn[15]="Invalid access",15);function Ge(e,t){if(t instanceof Error)var n=t;else n=this,Error.call(this,Bn[e]),this.message=Bn[e],Error.captureStackTrace&&Error.captureStackTrace(this,Ge);return n.code=e,t&&(this.message=this.message+": "+t),n}Ge.prototype=Error.prototype;Df(mr,Ge);function Ua(){}Ua.prototype={length:0,item:function(e){return e>=0&&e<this.length?this[e]:null},toString:function(e,t,n){for(var r=!!n&&!!n.requireWellFormed,i=[],o=0;o<this.length;o++)vw(this[o],i,e,t,null,r);return i.join("")},filter:function(e){return Array.prototype.filter.call(this,e)},indexOf:function(e){return Array.prototype.indexOf.call(this,e)}};function dc(e,t){this._node=e,this._refresh=t,fw(this)}function fw(e){var t=e._node._inc||e._node.ownerDocument._inc;if(e._inc!==t){var n=e._refresh(e._node);if(TP(e,"length",n.length),!e.$$length||n.length<e.$$length)for(var r=n.length;r in e;r++)Object.prototype.hasOwnProperty.call(e,r)&&delete e[r];Df(n,e),e._inc=t}}dc.prototype.item=function(e){return fw(this),this[e]||null};ei(dc,Ua);function Dh(){this._nameIndex=Object.create(null)}function gP(e,t){for(var n=e.length;n--;)if(e[n]===t)return n}function xJ(e,t){e._nameIndex[t.nodeName]=t}function yP(e,t){e._nameIndex[t.nodeName]===t&&delete e._nameIndex[t.nodeName]}function aP(e,t,n,r){if(r?(t[gP(t,r)]=n,yP(t,r)):t[t.length++]=n,xJ(t,n),e){n.ownerElement=e;var i=e.ownerDocument;i&&(r&&wP(i,e,r),FJ(i,e,n))}}function sP(e,t,n){var r=gP(t,n);if(r>=0){for(var i=t.length-1;r<i;)t[r]=t[++r];if(t.length=i,yP(t,n),e){var o=e.ownerDocument;o&&(wP(o,e,n),n.ownerElement=null)}}else throw new Ge(hP,new Error(e.tagName+"@"+n))}Dh.prototype={length:0,item:Ua.prototype.item,getNamedItem:function(e){for(var t=this.length;t--;){var n=this[t];if(n.nodeName==e)return n}},setNamedItem:function(e){var t=e.ownerElement;if(t&&t!=this._ownerElement)throw new Ge(oP);var n=this._nameIndex[e.nodeName];return aP(this._ownerElement,this,e,n),n},setNamedItemNS:function(e){var t=e.ownerElement,n;if(t&&t!=this._ownerElement)throw new Ge(oP);return n=this.getNamedItemNS(e.namespaceURI,e.localName),aP(this._ownerElement,this,e,n),n},removeNamedItem:function(e){var t=this.getNamedItem(e);return sP(this._ownerElement,this,t),t},removeNamedItemNS:function(e,t){var n=this.getNamedItemNS(e,t);return sP(this._ownerElement,this,n),n},getNamedItemNS:function(e,t){for(var n=this.length;n--;){var r=this[n];if(r.localName==t&&r.namespaceURI==e)return r}return null}};function bP(){}bP.prototype={hasFeature:function(e,t){return!0},createDocument:function(e,t,n){var r=new Pf;if(r.implementation=this,r.childNodes=new Ua,r.doctype=n||null,n&&r.appendChild(n),t){var i=r.createElementNS(e,t);r.appendChild(i)}return r},createDocumentType:function(e,t,n){var r=new Lh;return r.name=e,r.nodeName=e,r.publicId=t||"",r.systemId=n||"",r}};function at(){}at.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 Rh(this,e,t)},replaceChild:function(e,t){Rh(this,e,t,AP),t&&this.removeChild(t)},removeChild:function(e){return EP(this,e)},appendChild:function(e){return this.insertBefore(e,null)},hasChildNodes:function(){return this.firstChild!=null},cloneNode:function(e){return IP(this.ownerDocument||this,this,e)},normalize:function(){qn(this,null,{enter:function(e){for(var t=e.firstChild;t;){var n=t.nextSibling;if(n!==null&&n.nodeType===If&&t.nodeType===If){for(var r=[],i=n;i!==null&&i.nodeType===If;)r.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(r.join("")),$h(e.ownerDocument,e),t=i}else t=n}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 n=t._nsMap;if(n){for(var r in n)if(Object.prototype.hasOwnProperty.call(n,r)&&n[r]===e)return r}t=t.nodeType==cc?t.ownerDocument:t.parentNode}return null},lookupNamespaceURI:function(e){for(var t=this;t;){var n=t._nsMap;if(n&&Object.prototype.hasOwnProperty.call(n,e))return n[e];t=t.nodeType==cc?t.ownerDocument:t.parentNode}return null},isDefaultNamespace:function(e){var t=this.lookupPrefix(e);return t==null}};function vP(e){return e=="<"&&"<"||e==">"&&">"||e=="&"&&"&"||e=='"'&&"""||"&#"+e.charCodeAt()+";"}Df(ti,at);Df(ti,at.prototype);function Ph(e,t){return qn(e,null,{enter:function(n){return t(n)?qn.STOP:!0}})===qn.STOP}function qn(e,t,n){for(var r=[{node:e,context:t,phase:qn.ENTER}];r.length>0;){var i=r.pop();if(i.phase===qn.ENTER){var o=n.enter(i.node,i.context);if(o===qn.STOP)return qn.STOP;if(r.push({node:i.node,context:o,phase:qn.EXIT}),o==null)continue;for(var a=i.node.lastChild;a;)r.push({node:a,context:o,phase:qn.ENTER}),a=a.previousSibling}else n.exit&&n.exit(i.node,i.context)}}qn.STOP=Symbol("walkDOM.STOP");qn.ENTER=0;qn.EXIT=1;function Pf(){this.ownerDocument=this}function FJ(e,t,n){e&&e._inc++;var r=n.namespaceURI;r===Tf.XMLNS&&(t._nsMap[n.prefix?n.localName:""]=n.value)}function wP(e,t,n,r){e&&e._inc++;var i=n.namespaceURI;i===Tf.XMLNS&&delete t._nsMap[n.prefix?n.localName:""]}function $h(e,t,n){if(e&&e._inc){e._inc++;var r=t.childNodes;if(n)r[r.length++]=n;else{for(var i=t.firstChild,o=0;i;)r[o++]=i,i=i.nextSibling;r.length=o,delete r[r.length]}}}function EP(e,t){var n=t.previousSibling,r=t.nextSibling;return n?n.nextSibling=r:e.firstChild=r,r?r.previousSibling=n:e.lastChild=n,t.parentNode=null,t.previousSibling=null,t.nextSibling=null,$h(e.ownerDocument,e),t}function UJ(e){return e&&(e.nodeType===at.DOCUMENT_NODE||e.nodeType===at.DOCUMENT_FRAGMENT_NODE||e.nodeType===at.ELEMENT_NODE)}function qJ(e){return e&&(Yo(e)||pw(e)||qa(e)||e.nodeType===at.DOCUMENT_FRAGMENT_NODE||e.nodeType===at.COMMENT_NODE||e.nodeType===at.PROCESSING_INSTRUCTION_NODE)}function qa(e){return e&&e.nodeType===at.DOCUMENT_TYPE_NODE}function Yo(e){return e&&e.nodeType===at.ELEMENT_NODE}function pw(e){return e&&e.nodeType===at.TEXT_NODE}function uP(e,t){var n=e.childNodes||[];if(Jo(n,Yo)||qa(t))return!1;var r=Jo(n,qa);return!(t&&r&&n.indexOf(r)>n.indexOf(t))}function lP(e,t){var n=e.childNodes||[];function r(o){return Yo(o)&&o!==t}if(Jo(n,r))return!1;var i=Jo(n,qa);return!(t&&i&&n.indexOf(i)>n.indexOf(t))}function BJ(e,t,n){if(!UJ(e))throw new Ge(Zr,"Unexpected parent node type "+e.nodeType);if(n&&n.parentNode!==e)throw new Ge(hP,"child not in parent");if(!qJ(t)||qa(t)&&e.nodeType!==at.DOCUMENT_NODE)throw new Ge(Zr,"Unexpected node type "+t.nodeType+" for parent node type "+e.nodeType)}function VJ(e,t,n){var r=e.childNodes||[],i=t.childNodes||[];if(t.nodeType===at.DOCUMENT_FRAGMENT_NODE){var o=i.filter(Yo);if(o.length>1||Jo(i,pw))throw new Ge(Zr,"More than one element or text in fragment");if(o.length===1&&!uP(e,n))throw new Ge(Zr,"Element in fragment can not be inserted before doctype")}if(Yo(t)&&!uP(e,n))throw new Ge(Zr,"Only one element can be added and only after doctype");if(qa(t)){if(Jo(r,qa))throw new Ge(Zr,"Only one doctype is allowed");var a=Jo(r,Yo);if(n&&r.indexOf(a)<r.indexOf(n))throw new Ge(Zr,"Doctype can only be inserted before an element");if(!n&&a)throw new Ge(Zr,"Doctype can not be appended since element is present")}}function AP(e,t,n){var r=e.childNodes||[],i=t.childNodes||[];if(t.nodeType===at.DOCUMENT_FRAGMENT_NODE){var o=i.filter(Yo);if(o.length>1||Jo(i,pw))throw new Ge(Zr,"More than one element or text in fragment");if(o.length===1&&!lP(e,n))throw new Ge(Zr,"Element in fragment can not be inserted before doctype")}if(Yo(t)&&!lP(e,n))throw new Ge(Zr,"Only one element can be added and only after doctype");if(qa(t)){let u=function(l){return qa(l)&&l!==n};var s=u;if(Jo(r,u))throw new Ge(Zr,"Only one doctype is allowed");var a=Jo(r,Yo);if(n&&r.indexOf(a)<r.indexOf(n))throw new Ge(Zr,"Doctype can only be inserted before an element")}}function Rh(e,t,n,r){BJ(e,t,n),e.nodeType===at.DOCUMENT_NODE&&(r||VJ)(e,t,n);var i=t.parentNode;if(i&&i.removeChild(t),t.nodeType===Fa){var o=t.firstChild;if(o==null)return t;var a=t.lastChild}else o=a=t;var s=n?n.previousSibling:e.lastChild;o.previousSibling=s,a.nextSibling=n,s?s.nextSibling=o:e.firstChild=o,n==null?e.lastChild=a:n.previousSibling=a;do{o.parentNode=e;var u=e.ownerDocument||e;Of(o,u)}while(o!==a&&(o=o.nextSibling));return $h(e.ownerDocument||e,e),t.nodeType==Fa&&(t.firstChild=t.lastChild=null),t}function Of(e,t){if(e.ownerDocument!==t){if(e.ownerDocument=t,e.nodeType===Bi&&e.attributes)for(var n=0;n<e.attributes.length;n++){var r=e.attributes.item(n);r&&(r.ownerDocument=t)}for(var i=e.firstChild;i;)Of(i,t),i=i.nextSibling}}function GJ(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,$h(e.ownerDocument,e,t);var n=e.ownerDocument||e;return Of(t,n),t}Pf.prototype={nodeName:"#document",nodeType:pP,doctype:null,documentElement:null,_inc:1,insertBefore:function(e,t){if(e.nodeType==Fa){for(var n=e.firstChild;n;){var r=n.nextSibling;this.insertBefore(n,t),n=r}return e}return Rh(this,e,t),Of(e,this),this.documentElement===null&&e.nodeType===Bi&&(this.documentElement=e),e},removeChild:function(e){return this.documentElement==e&&(this.documentElement=null),EP(this,e)},replaceChild:function(e,t){Rh(this,e,t,AP),Of(e,this),t&&this.removeChild(t),Yo(e)&&(this.documentElement=e)},importNode:function(e,t){return jJ(this,e,t)},getElementById:function(e){var t=null;return Ph(this.documentElement,function(n){if(n.nodeType==Bi&&n.getAttribute("id")==e)return t=n,!0}),t},getElementsByClassName:function(e){var t=rP(e);return new dc(this,function(n){var r=[];return t.length>0&&Ph(n.documentElement,function(i){if(i!==n&&i.nodeType===Bi){var o=i.getAttribute("class");if(o){var a=e===o;if(!a){var s=rP(o);a=t.every($J(s))}a&&r.push(i)}}}),r})},createElement:function(e){var t=new Bu;t.ownerDocument=this,t.nodeName=e,t.tagName=e,t.localName=e,t.childNodes=new Ua;var n=t.attributes=new Dh;return n._ownerElement=t,t},createDocumentFragment:function(){var e=new Mh;return e.ownerDocument=this,e.childNodes=new Ua,e},createTextNode:function(e){var t=new mw;return t.ownerDocument=this,t.appendData(e),t},createComment:function(e){var t=new hw;return t.ownerDocument=this,t.appendData(e),t},createCDATASection:function(e){if(e.indexOf("]]>")!==-1)throw new Ge(iP,'data contains "]]>"');var t=new gw;return t.ownerDocument=this,t.appendData(e),t},createProcessingInstruction:function(e,t){var n=new bw;return n.ownerDocument=this,n.tagName=n.nodeName=n.target=e,n.nodeValue=n.data=t,n},createAttribute:function(e){var t=new kh;return t.ownerDocument=this,t.name=e,t.nodeName=e,t.localName=e,t.specified=!0,t},createEntityReference:function(e){if(!lc.test(e))throw new Ge(iP,'not a valid xml name "'+e+'"');var t=new yw;return t.ownerDocument=this,t.nodeName=e,t},createElementNS:function(e,t){var n=new Bu,r=t.split(":"),i=n.attributes=new Dh;return n.childNodes=new Ua,n.ownerDocument=this,n.nodeName=t,n.tagName=t,n.namespaceURI=e,r.length==2?(n.prefix=r[0],n.localName=r[1]):n.localName=t,i._ownerElement=n,n},createAttributeNS:function(e,t){var n=new kh,r=t.split(":");return n.ownerDocument=this,n.nodeName=t,n.name=t,n.namespaceURI=e,n.specified=!0,r.length==2?(n.prefix=r[0],n.localName=r[1]):n.localName=t,n}};ei(Pf,at);function Bu(){this._nsMap={}}Bu.prototype={nodeType:Bi,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 n=this.ownerDocument.createAttribute(e);n.value=n.nodeValue=""+t,this.setAttributeNode(n)},removeAttribute:function(e){var t=this.getAttributeNode(e);t&&this.removeAttributeNode(t)},appendChild:function(e){return e.nodeType===Fa?this.insertBefore(e,null):GJ(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 n=this.getAttributeNodeNS(e,t);n&&this.removeAttributeNode(n)},hasAttributeNS:function(e,t){return this.getAttributeNodeNS(e,t)!=null},getAttributeNS:function(e,t){var n=this.getAttributeNodeNS(e,t);return n&&n.value||""},setAttributeNS:function(e,t,n){var r=this.ownerDocument.createAttributeNS(e,t);r.value=r.nodeValue=""+n,this.setAttributeNode(r)},getAttributeNodeNS:function(e,t){return this.attributes.getNamedItemNS(e,t)},getElementsByTagName:function(e){return new dc(this,function(t){var n=[];return Ph(t,function(r){r!==t&&r.nodeType==Bi&&(e==="*"||r.tagName==e)&&n.push(r)}),n})},getElementsByTagNameNS:function(e,t){return new dc(this,function(n){var r=[];return Ph(n,function(i){i!==n&&i.nodeType===Bi&&(e==="*"||i.namespaceURI===e)&&(t==="*"||i.localName==t)&&r.push(i)}),r})}};Pf.prototype.getElementsByTagName=Bu.prototype.getElementsByTagName;Pf.prototype.getElementsByTagNameNS=Bu.prototype.getElementsByTagNameNS;ei(Bu,at);function kh(){}kh.prototype.nodeType=cc;ei(kh,at);function Rf(){}Rf.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(Bn[Zr])},deleteData:function(e,t){this.replaceData(e,t,"")},replaceData:function(e,t,n){var r=this.data.substring(0,e),i=this.data.substring(e+t);n=r+n+i,this.nodeValue=this.data=n,this.length=n.length}};ei(Rf,at);function mw(){}mw.prototype={nodeName:"#text",nodeType:If,splitText:function(e){var t=this.data,n=t.substring(e);t=t.substring(0,e),this.data=this.nodeValue=t,this.length=t.length;var r=this.ownerDocument.createTextNode(n);return this.parentNode&&this.parentNode.insertBefore(r,this.nextSibling),r}};ei(mw,Rf);function hw(){}hw.prototype={nodeName:"#comment",nodeType:dw};ei(hw,Rf);function gw(){}gw.prototype={nodeName:"#cdata-section",nodeType:dP};ei(gw,Rf);function Lh(){}Lh.prototype.nodeType=mP;ei(Lh,at);function CP(){}CP.prototype.nodeType=MJ;ei(CP,at);function SP(){}SP.prototype.nodeType=LJ;ei(SP,at);function yw(){}yw.prototype.nodeType=fP;ei(yw,at);function Mh(){}Mh.prototype.nodeName="#document-fragment";Mh.prototype.nodeType=Fa;ei(Mh,at);function bw(){}bw.prototype.nodeType=cw;ei(bw,at);function NP(){}NP.prototype.serializeToString=function(e,t,n,r){return _P.call(e,t,n,r)};at.prototype.toString=_P;function _P(e,t,n){var r=!!n&&!!n.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 u=[{namespace:s,prefix:null}]}return vw(this,i,e,t,u,r),i.join("")}function cP(e,t,n){var r=e.prefix||"",i=e.namespaceURI;if(!i||r==="xml"&&i===Tf.XML||i===Tf.XMLNS)return!1;for(var o=n.length;o--;){var a=n[o];if(a.prefix===r)return a.namespace!==i}return!0}function Oh(e,t,n,r){if(r&&!lc.test(t))throw new Ge(ho,'The attribute name "'+t+'" is not a valid XML QName');e.push(" ",t,'="',n.replace(/[<>&"\t\n\r]/g,vP),'"')}function vw(e,t,n,r,i,o){i||(i=[]),qn(e,{ns:i,isHTML:n},{enter:function(a,s){var u=s.ns,l=s.isHTML;if(r)if(a=r(a),a){if(typeof a=="string")return t.push(a),null}else return null;switch(a.nodeType){case Bi:var c=a.attributes,d=c.length,f=a.tagName;l=Tf.isHTML(a.namespaceURI)||l;var p=f;if(!l&&!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=u.length-1;g>=0;g--){var y=u[g];if(y.prefix===""&&y.namespace===a.namespaceURI){m=y.namespace;break}}if(m!==a.namespaceURI)for(var g=u.length-1;g>=0;g--){var y=u[g];if(y.namespace===a.namespaceURI){y.prefix&&(p=y.prefix+":"+f);break}}}if(o&&!lc.test(p))throw new Ge(ho,'The element name "'+p+'" is not a valid XML QName');t.push("<",p);for(var b=u.slice(),E=0;E<d;E++){var w=c.item(E);w.prefix=="xmlns"?b.push({prefix:w.localName,namespace:w.value}):w.nodeName=="xmlns"&&b.push({prefix:"",namespace:w.value})}for(var E=0;E<d;E++){var w=c.item(E);if(cP(w,l,b)){var _=w.prefix||"",I=w.namespaceURI;Oh(t,_?"xmlns:"+_:"xmlns",I,o),b.push({prefix:_,namespace:I})}var T=r?r(w):w;T&&(typeof T=="string"?t.push(T):Oh(t,T.name,T.value,o))}if(f===p&&cP(a,l,b)){var O=a.prefix||"",I=a.namespaceURI;Oh(t,O?"xmlns:"+O:"xmlns",I,o),b.push({prefix:O,namespace:I})}var v=a.firstChild;if(v||l&&!/^(?:meta|link|img|br|hr|input)$/i.test(f)){if(t.push(">"),l&&/^script$/i.test(f)){for(;v;)v.data?t.push(v.data):vw(v,t,l,r,b.slice(),o),v=v.nextSibling;return t.push("</",f,">"),null}return{ns:b,isHTML:l,tag:p}}else return t.push("/>"),null;case pP:case Fa:return{ns:u.slice(),isHTML:l,tag:null};case cc:return Oh(t,a.name,a.value,o),null;case If:return t.push(a.data.replace(/[<&>]/g,vP)),null;case dP:if(o&&a.data.indexOf("]]>")!==-1)throw new Ge(ho,'The CDATASection data contains "]]>"');return t.push("<![CDATA[",a.data.replace(/]]>/g,"]]]]><![CDATA[>"),"]]>"),null;case dw:if(o&&a.data.indexOf("-->")!==-1)throw new Ge(ho,'The comment node data contains "-->"');return t.push("<!--",a.data,"-->"),null;case mP:if(o){if(!lc.test(a.name))throw new Ge(ho,'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 Ge(ho,"DocumentType publicId is not a valid PubidLiteral");if(a.systemId&&!/^("[^"]*"|'[^']*')$/.test(a.systemId))throw new Ge(ho,"DocumentType systemId is not a valid SystemLiteral");if(a.internalSubset&&a.internalSubset.indexOf("]>")!==-1)throw new Ge(ho,'DocumentType internalSubset contains "]>"')}var N=a.publicId,S=a.systemId;if(t.push("<!DOCTYPE ",a.name),N)t.push(" PUBLIC ",N),S&&S!="."&&t.push(" ",S),t.push(">");else if(S&&S!=".")t.push(" SYSTEM ",S,">");else{var R=a.internalSubset;R&&t.push(" [",R,"]"),t.push(">")}return null;case cw:if(o){if(!lc.test(a.target)||a.target.indexOf(":")!==-1||a.target.toLowerCase()==="xml")throw new Ge(ho,'The processing instruction target "'+a.target+'" is not a valid XML NCName or is reserved');if(a.data.indexOf("?>")!==-1)throw new Ge(ho,'The ProcessingInstruction data contains "?>"')}return t.push("<?",a.target," ",a.data,"?>"),null;case fP:if(o&&!lc.test(a.nodeName))throw new Ge(ho,'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 jJ(e,t,n){var r;return qn(t,null,{enter:function(i,o){var a=i.cloneNode(!1);a.ownerDocument=e,a.parentNode=null,o===null?r=a:o.appendChild(a);var s=i.nodeType===cc||n;return s?a:null}}),r}function IP(e,t,n){var r;return qn(t,null,{enter:function(i,o){var a=new i.constructor;for(var s in i)if(Object.prototype.hasOwnProperty.call(i,s)){var u=i[s];typeof u!="object"&&u!=a[s]&&(a[s]=u)}i.childNodes&&(a.childNodes=new Ua),a.ownerDocument=e;var l=n;switch(a.nodeType){case Bi:var c=i.attributes,d=a.attributes=new Dh,f=c.length;d._ownerElement=a;for(var p=0;p<f;p++)a.setAttributeNode(IP(e,c.item(p),!0));break;case cc:l=!0}return o!==null?o.appendChild(a):r=a,l?a:null}}),r}function TP(e,t,n){e[t]=n}try{Object.defineProperty&&(Object.defineProperty(dc.prototype,"length",{get:function(){return fw(this),this.$$length}}),Object.defineProperty(at.prototype,"textContent",{get:function(){if(this.nodeType===Bi||this.nodeType===Fa){var e=[];return qn(this,null,{enter:function(t){if(t.nodeType===Bi||t.nodeType===Fa)return!0;if(t.nodeType===cw||t.nodeType===dw)return null;e.push(t.nodeValue)}}),e.join("")}return this.nodeValue},set:function(e){switch(this.nodeType){case Bi:case Fa: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}}}),TP=function(e,t,n){e["$$"+t]=n})}catch{}Ba.DocumentType=Lh;Ba.DOMException=Ge;Ba.DOMImplementation=bP;Ba.Element=Bu;Ba.Node=at;Ba.NodeList=Ua;Ba.walkDOM=qn;Ba.XMLSerializer=NP});var DP=C(kf=>{"use strict";var OP=uc().freeze;kf.XML_ENTITIES=OP({amp:"&",apos:"'",gt:">",lt:"<",quot:'"'});kf.HTML_ENTITIES=OP({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"});kf.entityMap=kf.HTML_ENTITIES});var LP=C(Aw=>{var Mf=uc().NAMESPACE,Ew=uc().tagNamePattern,fc=0,Ls=1,pc=2,$f=3,mc=4,hc=5,Lf=6,xh=7;function gc(e,t){this.message=e,this.locator=t,Error.captureStackTrace&&Error.captureStackTrace(this,gc)}gc.prototype=new Error;gc.prototype.name=gc.name;function kP(){}kP.prototype={parse:function(e,t,n){var r=this.domBuilder;r.startDocument(),JJ(t,t={}),WJ(e,t,n,r,this.errorHandler),r.endDocument()}};function WJ(e,t,n,r,i){function o(M){if(M>65535){M-=65536;var q=55296+(M>>10),X=56320+(M&1023);return String.fromCharCode(q,X)}else return String.fromCharCode(M)}function a(M){var q=M.slice(1,-1);return Object.hasOwnProperty.call(n,q)?n[q]:q.charAt(0)==="#"?o(parseInt(q.substr(1).replace("x","0x"))):(i.error("entity not found:"+M),M)}function s(M){if(M>h){var q=e.substring(h,M).replace(/&#?\w+;/g,a);f&&u(h),r.characters(q,0,M-h),h=M}}function u(M,q){for(;M>=c&&(q=d.exec(e));)l=q.index,c=l+q[0].length,f.lineNumber++;f.columnNumber=M-l+1}for(var l=0,c=0,d=/.*(?:\r\n?|\n)|.*$/g,f=r.locator,p=[{currentNSMap:t}],m={},h=0;;){try{var g=e.indexOf("<",h);if(g<0){if(!e.substr(h).match(/^\s*$/)){var y=r.doc,b=y.createTextNode(e.substr(h));y.appendChild(b),r.currentElement=b}return}switch(g>h&&s(g),e.charAt(g+1)){case"/":var S=e.indexOf(">",g+3),E=e.substring(g+2,S).replace(/^([\s\S]*?[^ \t\n\r])?[ \t\n\r]*$/,"$1"),w=p.pop();S<0?(E=e.substring(g+2).replace(/[\s<].*/,""),i.error("end tag name: "+E+" is not complete:"+w.tagName),S=g+1+E.length):E.match(/\s</)?(E=E.replace(/[\s<].*/,""),i.error("end tag name: "+E+" maybe not complete"),S=g+1+E.length):/[ \t\n\r]/.test(E)&&Ew.test(E.split(/[ \t\n\r]/)[0])&&i.error('end tag name is followed by whitespace and trailing content: "'+E+'"');var _=w.localNSMap,I=w.tagName==E,T=I||w.tagName&&w.tagName.toLowerCase()==E.toLowerCase();if(T){if(r.endElement(w.uri,w.localName,E),_)for(var O in _)Object.prototype.hasOwnProperty.call(_,O)&&r.endPrefixMapping(O);I||i.fatalError("end tag name: "+E+" is not match the current start tagName:"+w.tagName)}else p.push(w);S++;break;case"?":f&&u(g),S=QJ(e,g,r);break;case"!":f&&u(g),S=YJ(e,g,r,i);break;default:f&&u(g);var v=new $P,N=p[p.length-1].currentNSMap,S=zJ(e,g,v,N,a,i),R=v.length;if(!v.closed&&KJ(e,S,v.tagName,m)&&(v.closed=!0,n.nbsp||i.warning("unclosed xml attribute")),f&&R){for(var x=PP(f,{}),G=0;G<R;G++){var U=v[G];u(U.offset),U.locator=PP(f,{})}r.locator=x,RP(v,r,N)&&p.push(v),r.locator=f}else RP(v,r,N)&&p.push(v);Mf.isHTML(v.uri)&&!v.closed?S=HJ(e,S,v.tagName,a,r):S++}}catch(M){if(M instanceof gc)throw M;i.error("element parse error: "+M),S=-1}S>h?h=S:s(Math.max(g,h)+1)}}function PP(e,t){return t.lineNumber=e.lineNumber,t.columnNumber=e.columnNumber,t}function zJ(e,t,n,r,i,o){function a(p,m,h){n.attributeNames.hasOwnProperty(p)&&o.fatalError("Attribute "+p+" redefined"),n.addValue(p,m.replace(/[\t\n\r]/g," ").replace(/&#?\w+;/g,i),h)}for(var s,u,l=++t,c=fc;;){var d=e.charAt(l);if(c===fc&&d==="<")throw new Error("unexpected < in tag name: "+e.slice(t,l));switch(d){case"=":if(c===Ls)s=e.slice(t,l),c=$f;else if(c===pc)c=$f;else throw new Error("attribute equal must after attrName");break;case"'":case'"':if(c===$f||c===Ls)if(c===Ls&&(o.warning('attribute value must after "="'),s=e.slice(t,l)),t=l+1,l=e.indexOf(d,t),l>0)u=e.slice(t,l),a(s,u,t-1),c=hc;else throw new Error("attribute value no end '"+d+"' match");else if(c==mc)u=e.slice(t,l),a(s,u,t),o.warning('attribute "'+s+'" missed start quot('+d+")!!"),t=l+1,c=hc;else throw new Error('attribute value must after "="');break;case"/":switch(c){case fc:n.setTagName(e.slice(t,l));case hc:case Lf:case xh:c=xh,n.closed=!0;case mc:case Ls:break;case pc:n.closed=!0;break;default:throw new Error("attribute invalid close char('/')")}break;case"":return o.error("unexpected end of input"),c==fc&&n.setTagName(e.slice(t,l)),l;case">":switch(c){case fc:n.setTagName(e.slice(t,l));case hc:case Lf:case xh:break;case mc:case Ls:u=e.slice(t,l),u.slice(-1)==="/"&&(n.closed=!0,u=u.slice(0,-1));case pc:c===pc&&(u=s),c==mc?(o.warning('attribute "'+u+'" missed quot(")!'),a(s,u,t)):((!Mf.isHTML(r[""])||!u.match(/^(?:disabled|checked|selected)$/i))&&o.warning('attribute "'+u+'" missed value!! "'+u+'" instead!!'),a(u,u,t));break;case $f:throw new Error("attribute value missed!!")}return l;case"\x80":d=" ";default:if(d<=" ")switch(c){case fc:n.setTagName(e.slice(t,l)),c=Lf;break;case Ls:s=e.slice(t,l),c=pc;break;case mc:var u=e.slice(t,l);o.warning('attribute "'+u+'" missed quot(")!!'),a(s,u,t);case hc:c=Lf;break}else switch(c){case pc:var f=n.tagName;(!Mf.isHTML(r[""])||!s.match(/^(?:disabled|checked|selected)$/i))&&o.warning('attribute "'+s+'" missed value!! "'+s+'" instead2!!'),a(s,s,t),t=l,c=Ls;break;case hc:o.warning('attribute space is required"'+s+'"!!');case Lf:c=Ls,t=l;break;case $f:c=mc,t=l;break;case xh:throw new Error("elements closed character '/' and '>' must be connected to")}}l++}}function RP(e,t,n){for(var r=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 u=o.prefix=a.slice(0,f),l=a.slice(f+1),c=u==="xmlns"&&l;else l=a,u=null,c=a==="xmlns"&&"";o.localName=l,c!==!1&&(i==null&&(i={},n=Object.create(n)),n[c]=i[c]=s,o.uri=Mf.XMLNS,t.startPrefixMapping(c,s))}for(var d=e.length;d--;){o=e[d];var u=o.prefix;u&&(u==="xml"&&(o.uri=Mf.XML),u!=="xmlns"&&(o.uri=n[u||""]))}var f=r.indexOf(":");f>0?(u=e.prefix=r.slice(0,f),l=e.localName=r.slice(f+1)):(u=null,l=e.localName=r);var p=e.uri=n[u||""];if(t.startElement(p,l,r,e),e.closed){if(t.endElement(p,l,r),i)for(u in i)Object.prototype.hasOwnProperty.call(i,u)&&t.endPrefixMapping(u)}else return e.currentNSMap=n,e.localNSMap=i,!0}function HJ(e,t,n,r,i){if(/^(?:script|textarea)$/i.test(n)){var o=e.indexOf("</"+n+">",t),a=e.substring(t+1,o);if(/[&<]/.test(a))return/^script$/i.test(n)?(i.characters(a,0,a.length),o):(a=a.replace(/&#?\w+;/g,r),i.characters(a,0,a.length),o)}return t+1}function KJ(e,t,n,r){var i=r[n];return i==null&&(i=e.lastIndexOf("</"+n+">"),i<t&&(i=e.lastIndexOf("</"+n)),r[n]=i),i<t}function JJ(e,t){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])}function YJ(e,t,n,r){var i=e.charAt(t+2);switch(i){case"-":if(e.charAt(t+3)==="-"){var o=e.indexOf("-->",t+4);return o>t?(n.comment(e,t+4,o-t-4),o+3):(r.error("Unclosed comment"),-1)}else return-1;default:if(e.substr(t+3,6)=="CDATA["){var o=e.indexOf("]]>",t+9);return n.startCDATA(),n.characters(e,t+9,o-t-9),n.endCDATA(),o+3}var a=XJ(e,t),s=a.length;if(s>1&&/!doctype/i.test(a[0][0])){var u=a[1][0],l=!1,c=!1;s>3&&(/^public$/i.test(a[2][0])?(l=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 n.startDTD(u,l,c),n.endDTD(),d.index+d[0].length}}return-1}function QJ(e,t,n){var r=e.indexOf("?>",t);if(r){var i=e.substring(t,r).match(/^<\?(\S*)\s*([\s\S]*?)$/);if(i){var o=i[0].length;return n.processingInstruction(i[1],i[2]),r+2}else return-1}return-1}function $P(){this.attributeNames={}}$P.prototype={setTagName:function(e){if(!Ew.test(e))throw new Error("invalid tagName:"+e);this.tagName=e},addValue:function(e,t,n){if(!Ew.test(e))throw new Error("invalid attribute:"+e);this.attributeNames[e]=this.length,this[this.length++]={qName:e,value:t,offset:n}},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 XJ(e,t){var n,r=[],i=/'[^']+'|"[^"]+"|[^\s<>\/=]+=?|(\/?\s*>|<)/g;for(i.lastIndex=t,i.exec(e);n=i.exec(e);)if(r.push(n),n[1])return r}Aw.XMLReader=kP;Aw.ParseError=gc});var VP=C(Uh=>{var ZJ=uc(),eY=ww(),MP=DP(),UP=LP(),tY=eY.DOMImplementation,xP=ZJ.NAMESPACE,nY=UP.ParseError,rY=UP.XMLReader;function qP(e){return e.replace(/\r[\n\u0085]/g,`+`).replace(/[\r\u0085\u2028]/g,`+`)}function BP(e){this.options=e||{locator:{}}}BP.prototype.parseFromString=function(e,t){var n=this.options,r=new rY,i=n.domBuilder||new xf,o=n.errorHandler,a=n.locator,s=n.xmlns||{},u=/\/x?html?$/.test(t),l=u?MP.HTML_ENTITIES:MP.XML_ENTITIES;a&&i.setDocumentLocator(a),r.errorHandler=iY(o,i,a),r.domBuilder=n.domBuilder||i,u&&(s[""]=xP.HTML),s.xml=s.xml||xP.XML;var c=n.normalizeLineEndings||qP;return e&&typeof e=="string"?r.parse(c(e),s,l):r.errorHandler.error("invalid doc source"),i.doc};function iY(e,t,n){if(!e){if(t instanceof xf)return t;e=t}var r={},i=e instanceof Function;n=n||{};function o(a){var s=e[a];!s&&i&&(s=e.length==2?function(u){e(a,u)}:e),r[a]=s&&function(u){s("[xmldom "+a+"] "+u+Cw(n))}||function(){}}return o("warning"),o("error"),o("fatalError"),r}function xf(){this.cdata=!1}function yc(e,t){t.lineNumber=e.lineNumber,t.columnNumber=e.columnNumber}xf.prototype={startDocument:function(){this.doc=new tY().createDocument(null,null,null),this.locator&&(this.doc.documentURI=this.locator.systemId)},startElement:function(e,t,n,r){var i=this.doc,o=i.createElementNS(e,n||t),a=r.length;Fh(this,o),this.currentElement=o,this.locator&&yc(this.locator,o);for(var s=0;s<a;s++){var e=r.getURI(s),u=r.getValue(s),n=r.getQName(s),l=i.createAttributeNS(e,n);this.locator&&yc(r.getLocator(s),l),l.value=l.nodeValue=u,o.setAttributeNode(l)}},endElement:function(e,t,n){var r=this.currentElement,i=r.tagName;this.currentElement=r.parentNode},startPrefixMapping:function(e,t){},endPrefixMapping:function(e){},processingInstruction:function(e,t){var n=this.doc.createProcessingInstruction(e,t);this.locator&&yc(this.locator,n),Fh(this,n)},ignorableWhitespace:function(e,t,n){},characters:function(e,t,n){if(e=FP.apply(this,arguments),e){if(this.cdata)var r=this.doc.createCDATASection(e);else var r=this.doc.createTextNode(e);this.currentElement?this.currentElement.appendChild(r):/^\s*$/.test(e)&&this.doc.appendChild(r),this.locator&&yc(this.locator,r)}},skippedEntity:function(e){},endDocument:function(){this.doc.normalize()},setDocumentLocator:function(e){(this.locator=e)&&(e.lineNumber=0)},comment:function(e,t,n){e=FP.apply(this,arguments);var r=this.doc.createComment(e);this.locator&&yc(this.locator,r),Fh(this,r)},startCDATA:function(){this.cdata=!0},endCDATA:function(){this.cdata=!1},startDTD:function(e,t,n){var r=this.doc.implementation;if(r&&r.createDocumentType){var i=r.createDocumentType(e,t,n);this.locator&&yc(this.locator,i),Fh(this,i),this.doc.doctype=i}},warning:function(e){console.warn("[xmldom warning] "+e,Cw(this.locator))},error:function(e){console.error("[xmldom error] "+e,Cw(this.locator))},fatalError:function(e){throw new nY(e,this.locator)}};function Cw(e){if(e)return`+@`+(e.systemId||"")+"#[line:"+e.lineNumber+",col:"+e.columnNumber+"]"}function FP(e,t,n){return typeof e=="string"?e.substr(t,n):e.length>=t+n||t?new java.lang.String(e,t,n)+"":e}"endDTD,startEntity,endEntity,attributeDecl,elementDecl,externalEntityDecl,internalEntityDecl,resolveEntity,getExternalSubset,notationDecl,unparsedEntityDecl".replace(/\w+/g,function(e){xf.prototype[e]=function(){return null}});function Fh(e,t){e.currentElement?e.currentElement.appendChild(t):e.doc.appendChild(t)}Uh.__DOMHandler=xf;Uh.normalizeLineEndings=qP;Uh.DOMParser=BP});var Ms=C(qh=>{var GP=ww();qh.DOMImplementation=GP.DOMImplementation;qh.XMLSerializer=GP.XMLSerializer;qh.DOMParser=VP().DOMParser});var Nw=C(bc=>{"use strict";Object.defineProperty(bc,"__esModule",{value:!0});bc.deleteAppCascade=bc.collectGenPageIds=void 0;var oY=vc(),aY=Y(),Sw=ae(),sY=Ms();function jP(e){let t=[],n=s=>u=>t.push(`${s}: ${u}`),r=new sY.DOMParser({errorHandler:{warning:n("warning"),error:n("error"),fatalError:n("fatalError")}}).parseFromString(e,"text/xml"),i=r?.documentElement;if(!i||t.length>0)throw new aY.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 l=s.getAttribute("GenPageId");l&&o.push((0,Sw.normalizeGuid)(l,"GenPageId"))}let u=s.childNodes;for(let l=0;l<u.length;l+=1){let c=u[l];c.nodeType===1&&a(c)}};return a(i),o}bc.collectGenPageIds=jP;async function uY(e,t,n){let r=(0,Sw.normalizeGuid)(t,"appModuleId");(0,Sw.normalizeGuid)(n,"appModuleIdUnique");let i=[],o=[],a=[];await(0,oY.deleteAppResolvingOnce)(e,r,u=>{u!==void 0&&a.push(...jP(u))}),i.push({type:"app",id:r});let s=[...new Set(a)].map(u=>({type:"genPage",id:u}));return{success:o.length===0,deleted:i,failures:o,retained:s}}bc.deleteAppCascade=uY});var Vh=C(Oi=>{"use strict";Object.defineProperty(Oi,"__esModule",{value:!0});Oi.observeGenPageTargets=Oi.findMissingGenPages=Oi.GENPAGE_LOOKUP_CHUNK=Oi.GENPAGE_COMPONENT_NAME=void 0;var lY=Ke(),Bh=ae();Oi.GENPAGE_COMPONENT_NAME="uxagentproject";Oi.GENPAGE_LOOKUP_CHUNK=50;async function cY(e,t,n){let r=[...new Set(t.map(o=>(0,Bh.normalizeGuid)(o,"uxagentprojectid")))],i=new Set;for(let o=0;o<r.length;o+=Oi.GENPAGE_LOOKUP_CHUNK){let a=r.slice(o,o+Oi.GENPAGE_LOOKUP_CHUNK),s="/uxagentprojects/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,Bh.odataQuery)([["$select","uxagentprojectid"],["$filter",a.map(l=>`uxagentprojectid eq ${l}`).join(" or ")]]),u=await(0,lY.collectPages)(e,s,n);for(let l of u){let c=l.uxagentprojectid;typeof c=="string"&&c.trim()!==""&&i.add((0,Bh.normalizeGuid)(c,"uxagentprojectid"))}}return r.filter(o=>!i.has(o))}Oi.findMissingGenPages=cY;function dY(e,t,n){if(!e)return;let r=new Set(n);for(let i of new Set(t.map(o=>(0,Bh.normalizeGuid)(o,"uxagentprojectid"))))e.observe({guard:"dependency",componentName:Oi.GENPAGE_COMPONENT_NAME,componentId:i,status:r.has(i)?"absent":"present"})}Oi.observeGenPageTargets=dY});var Ff=C(Vn=>{"use strict";Object.defineProperty(Vn,"__esModule",{value:!0});Vn.applyAppSettings=Vn.setAppSetting=Vn.readAppSettings=Vn.resolveSettingDefinitions=Vn.APP_SETTING_UNSET=Vn.APP_SETTING_OFF=Vn.APP_SETTING_ON=Vn.HEADER_AND_NAVIGATION_REFRESH=void 0;var Gh=Ke(),HP=pe(),Va=ae();Vn.HEADER_AND_NAVIGATION_REFRESH="HeaderAndNavigationRefresh";Vn.APP_SETTING_ON="2";Vn.APP_SETTING_OFF="1";Vn.APP_SETTING_UNSET="0";function KP(e,t){return"/appsettings/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,Va.odataQuery)([["$select",e],["$filter",t]])}async function JP(e,t){let n=[...new Set(t.filter(Boolean))],r=new Map;if(n.length===0)return r;let i=n.map(s=>`uniquename eq '${(0,Va.odataLiteral)(s)}'`).join(" or "),o=`/settingdefinitions${(0,Va.odataQuery)([["$select","settingdefinitionid,uniquename,displayname"],["$filter",i]])}`,a=(await(0,Gh.collectPages)(e,o,"the setting definitions")).filter(Boolean);for(let s of a)s.uniquename&&r.set(s.uniquename,s);return r}Vn.resolveSettingDefinitions=JP;async function fY(e,t){let n=(0,Va.normalizeGuid)(t,"App id"),r=KP("appsettingid,value,_settingdefinitionid_value",`_parentappmoduleid_value eq ${n}`),i=(await(0,Gh.collectPages)(e,r,"readAppSettings")).filter(Boolean);if(i.length===0)return[];let o=[...new Set(i.map(s=>s._settingdefinitionid_value).filter(Boolean))],a=new Map;if(o.length>0){let s=o.map(c=>`settingdefinitionid eq ${(0,Va.normalizeGuid)(c,"Setting definition id")}`).join(" or "),u=`/settingdefinitions${(0,Va.odataQuery)([["$select","settingdefinitionid,uniquename,displayname"],["$filter",s]])}`,l=await(0,Gh.collectPages)(e,u,"the setting definitions");for(let c of l.filter(Boolean))c.settingdefinitionid&&a.set(c.settingdefinitionid.toLowerCase(),c)}return i.map(s=>{var u,l,c,d,f;let p=a.get(((u=s._settingdefinitionid_value)!==null&&u!==void 0?u:"").toLowerCase());return{id:(l=s.appsettingid)!==null&&l!==void 0?l:"",name:(d=(c=p?.uniquename)!==null&&c!==void 0?c:s._settingdefinitionid_value)!==null&&d!==void 0?d:"",value:(f=s.value)!==null&&f!==void 0?f:"",...p?.displayname?{displayName:p.displayname}:{}}})}Vn.readAppSettings=fY;async function WP(e,t,n){var r;let i=KP("appsettingid,value",`_parentappmoduleid_value eq ${t} and _settingdefinitionid_value eq ${n}`),o=(await(0,Gh.collectPages)(e,i,"the app setting read")).filter(Boolean)[0];return o?.appsettingid?{id:o.appsettingid,value:(r=o.value)!==null&&r!==void 0?r:""}:void 0}async function YP(e,t,n,r){let i=(0,Va.normalizeGuid)(t,"App id"),a=(await JP(e,[n])).get(n),s=a?.settingdefinitionid;if(!s)throw new Error(`App setting '${n}' 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 u=(0,Va.normalizeGuid)(s,"Setting definition id"),l=await WP(e,i,u);if(l)return zP(e,l,r);let c="/appsettings",d={"[email protected]":`/appmodules(${i})`,"[email protected]":`/settingdefinitions(${u})`,value:r},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 WP(e,i,u)}catch{m=void 0}if(m)return zP(e,m,r);throw f&&(0,HP.ensureSuccess)(f,e.apiUrl(c)),p}Vn.setAppSetting=YP;async function zP(e,t,n){if(t.value===n)return"unchanged";let r=`/appsettings(${(0,Va.normalizeGuid)(t.id,"App setting id")})`;return(0,HP.ensureSuccess)(await e.patch(r,{value:n}),e.apiUrl(r)),"updated"}async function pY(e,t,n){var r;let i=[];for(let[o,a]of Object.entries(n??{}))try{await YP(e,t,o,a)}catch(s){i.push(`App setting '${o}' was not applied: ${(r=s?.message)!==null&&r!==void 0?r:String(s)} The app was created; set it later with setAppSetting().`)}return i}Vn.applyAppSettings=pY});var _w=C(wc=>{"use strict";Object.defineProperty(wc,"__esModule",{value:!0});wc.isFailureAfterPrimaryWrite=wc.failedAfterPrimaryWrite=void 0;var QP=Symbol.for("cds-maker-sdk.createFailedAfterPrimaryWrite");function mY(e){return typeof e=="object"&&e!==null&&(e[QP]=!0),e}wc.failedAfterPrimaryWrite=mY;function hY(e){return typeof e=="object"&&e!==null&&e[QP]===!0}wc.isFailureAfterPrimaryWrite=hY});var ft=C(Qo=>{"use strict";Object.defineProperty(Qo,"__esModule",{value:!0});Qo.assignMissingIds=Qo.pointerTouchesValueMap=Qo.isValueMapKey=Qo.newId=void 0;var gY=ec();function XP(){return globalThis.crypto.randomUUID().toLowerCase()}Qo.newId=XP;function yY(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}var Tw=new Set(["parameters","bag","expression","rawExpression","lookupValue","stepLabels","genPage","inputData","customControl"]);function bY(e){return Tw.has(e)}Qo.isValueMapKey=bY;function vY(e){return gY.JsonPointer.parse(e).some(t=>Tw.has(t))}Qo.pointerTouchesValueMap=vY;function wY(e){return Iw(e),e}Qo.assignMissingIds=wY;function Iw(e){if(Array.isArray(e)){e.forEach(t=>Iw(t));return}if(yY(e)){(typeof e.id!="string"||e.id.length===0)&&(e.id=XP());for(let t of Object.keys(e))t==="id"||Tw.has(t)||Iw(e[t])}}});var Zo=C(Dt=>{"use strict";Object.defineProperty(Dt,"__esModule",{value:!0});Dt.parseChangeSetsParts=Dt.renderChangeSets=Dt.MAX_BATCH_PARTS=Dt.sendChangeSet=Dt.isChangeSetLockRefusal=Dt.partResponse=Dt.postChangeSet=Dt.parseChangeSetParts=Dt.parseChangeSetStatuses=Dt.renderChangeSet=void 0;var Xo=Y(),Vu=pe(),jh=ft(),Uf=ae();function Ow(e,t){let n=`batch_${(0,jh.newId)()}`,r=`changeset_${(0,jh.newId)()}`,i=t.map((s,u)=>String(u+1)),o=t.map((s,u)=>eR(e,s,i[u],r,n));return{body:[`--${n}`,`Content-Type: multipart/mixed;boundary=${r}`,"",...o,`--${r}--`,`--${n}--`,""].join(`\r+`),batchId:n,contentIds:i}}Dt.renderChangeSet=Ow;function eR(e,t,n,r,i){var o,a;if(t.rawBody!==void 0&&t.contentType===void 0)throw new Xo.InvalidArgumentError(`batch operation ${t.method} ${t.path} has a raw body but no Content-Type`);let s=(o=t.rawBody)!==null&&o!==void 0?o:t.body===void 0?void 0:JSON.stringify(t.body);if(s!==void 0&&(s.includes(`--${r}`)||s.includes(`--${i}`)))throw new Xo.InvalidArgumentError(`batch operation ${t.method} ${t.path} has a body containing the batch boundary`);(0,Uf.assertNoControlChars)(t.path,"batch operation path"),t.etag&&(0,Uf.assertNoControlChars)(t.etag,"batch operation etag");let u=Object.entries((a=t.headers)!==null&&a!==void 0?a:{});for(let[l,c]of u)if((0,Uf.assertNoControlChars)(l,"batch operation header name"),(0,Uf.assertNoControlChars)(c,"batch operation header value"),!/^[A-Za-z0-9!#$%&'*+.^_`|~-]+$/.test(l))throw new Xo.InvalidArgumentError(`batch operation header name '${l}' is not a valid HTTP token`);return t.contentType!==void 0&&(0,Uf.assertNoControlChars)(t.contentType,"batch operation content type"),[`--${r}`,"Content-Type: application/http","Content-Transfer-Encoding: binary",`Content-ID: ${n}`,"",`${t.method} ${e.apiUrl(t.path)} HTTP/1.1`,...s===void 0?[]:[`Content-Type: ${t.rawBody!==void 0?t.contentType:"application/json;type=entry"}`],...e.solutionName?[`MSCRM.SolutionUniqueName: ${e.solutionName}`]:[],...t.etag?[`If-Match: ${t.etag}`]:[],...u.map(([l,c])=>`${l}: ${c}`),"",...s===void 0?[]:[s]].join(`\r+`)}function tR(e,t){var n;return(n=Wh(e,t))===null||n===void 0?void 0:n.map(r=>r.status)}Dt.parseChangeSetStatuses=tR;function Wh(e,t){var n,r;if(typeof e!="string"||e.length===0)return;let i=(n=/^--(\S+)\r?\n/.exec(e))===null||n===void 0?void 0:n[1];if(i===void 0||!e.trimEnd().endsWith(`--${i}--`))return;let o=(r=/Content-Type:\s*multipart\/mixed;\s*boundary=(\S+)/i.exec(e))===null||r===void 0?void 0:r[1];if(o===void 0||o===i)return;let a=e.split(`--${o}`);if(a.length<2||!/^--(\r?\n|$)/.test(a[a.length-1]))return;let s=new Set(t),u=[],l=new Set;for(let c of a.slice(1)){if(c.startsWith("--"))break;let d=nR(c,s,l);if(d===void 0)return;u.push(d)}return u.length===0?void 0:u}Dt.parseChangeSetParts=Wh;function nR(e,t,n){var r,i;let o=e.indexOf(`\r+\r+`);if(o===-1)return;let a=e.slice(0,o),s=e.slice(o+4);if(!/^Content-Type:\s*application\/http\b/im.test(a))return;let u=/^HTTP\/1\.[01] (\d{3})\b/.exec(s);if(!u||((r=s.match(/^HTTP\/1\.[01] \d{3}\b/gm))!==null&&r!==void 0?r:[]).length!==1)return;let l=(i=/^Content-ID:\s*(\S+)/im.exec(a))===null||i===void 0?void 0:i[1];if(!(l===void 0||n.has(l)||!t.has(l)))return n.add(l),{status:Number(u[1]),text:s,contentId:l}}async function EY(e,t,n){if(t.length===0)return;let{body:r,batchId:i,contentIds:o}=Ow(e,t),a=await e.postBatch(r,i),s=e.apiUrl("/$batch");if((0,Vu.ensureSuccess)(a,s),typeof a.body!="string"||a.body.length===0)throw new Xo.ConnectionError(s,a.status,`atomic write of ${n} cannot be confirmed: the $batch response had no readable body, so the change set's outcome is unknown`);let u=tR(a.body,o);if(u===void 0)throw new Xo.ConnectionError(s,a.status,`atomic write of ${n} cannot be confirmed: the $batch response could not be parsed as a change set, so the outcome is unknown`);if(u.length!==t.length)throw new Xo.ConnectionError(s,a.status,`atomic write of ${n} cannot be confirmed: the change set reported ${u.length} result(s) for ${t.length} operation(s)`);let l=u.find(c=>c<200||c>=300);if(l!==void 0)throw new Xo.ConnectionError(s,l,`atomic write of ${n} was rolled back: the change set reported HTTP ${l}`)}Dt.postChangeSet=EY;function Dw(e){let t=e.text.replace(/\r\n/g,`+`),n=t.indexOf(`++`),r=n===-1?t:t.slice(0,n),i=(n===-1?"":t.slice(n+2)).trim(),o={};for(let s of r.split(`+`).slice(1)){let u=s.indexOf(":");u>0&&(o[s.slice(0,u).trim()]=s.slice(u+1).trim())}let a=i===""?void 0:i;if(i!=="")try{a=JSON.parse(i)}catch{}return{status:e.status,headers:o,body:a}}Dt.partResponse=Dw;function ZP(e){let t=e.path.indexOf("?");return t===-1?e.path:e.path.slice(0,t)}function AY(e,t){let n=e.find(r=>(0,Vu.isVersionToken)(r.etag));if(!n||e.some(r=>ZP(r)!==ZP(n)))throw new Xo.InvalidArgumentError(`the change set writing ${t} cannot be re-sent under the customization lock: it needs an operation conditioned on a version token and every operation writing that operation's row`)}function rR(e,t){var n;if(e.status!==429&&(e.status<200||e.status>=300))return!1;let r=(n=Wh(e.body,t))===null||n===void 0?void 0:n.filter(i=>i.status<200||i.status>=300);return r!==void 0&&r.length>0&&r.every(i=>(0,Vu.isConcurrencyLockRefusal)(Dw(i)))}Dt.isChangeSetLockRefusal=rR;async function CY(e,t,n,r={}){r.resendWhileLockRefused&&AY(t,n);let{body:i,batchId:o,contentIds:a}=Ow(e,t),s=()=>e.postBatch(i,o),u=r.resendWhileLockRefused?await(0,Vu.resendWhile)(f=>rR(f,a),s,Vu.LOCK_BACKOFF_MS):await s(),l=e.apiUrl("/$batch"),c=Wh(u.body,a),d=c?.find(f=>f.status<200||f.status>=300);if(d&&(0,Vu.ensureSuccess)(Dw(d),e.apiUrl(t[a.indexOf(d.contentId)].path)),(0,Vu.ensureSuccess)(u,l),!c||c.length!==t.length)throw new Xo.ConnectionError(l,u.status,`atomic write of ${n} cannot be confirmed: the $batch response ${c?`reported ${c.length} result(s) for ${t.length} operation(s)`:"could not be parsed"}, so the outcome is unknown`);return a.map(f=>c.find(p=>p.contentId===f))}Dt.sendChangeSet=CY;Dt.MAX_BATCH_PARTS=1e3;function SY(e,t){if(t.length>Dt.MAX_BATCH_PARTS)throw new Xo.InvalidArgumentError(`a $batch holds at most ${Dt.MAX_BATCH_PARTS} change sets \u2014 the platform refuses the 1001st part; got ${t.length}`);let n=`batch_${(0,jh.newId)()}`,r=t.map((a,s)=>String(s+1)),i=[];return t.forEach((a,s)=>{let u=`changeset_${(0,jh.newId)()}`;i.push(`--${n}`,`Content-Type: multipart/mixed;boundary=${u}`,"",eR(e,a,r[s],u,n),`--${u}--`)}),{body:[...i,`--${n}--`,""].join(`\r+`),batchId:n,contentIds:r}}Dt.renderChangeSets=SY;function NY(e,t){var n,r;if(typeof e!="string"||e.length===0)return;let i=(n=/^--(\S+)\r?\n/.exec(e))===null||n===void 0?void 0:n[1];if(i===void 0||!e.trimEnd().endsWith(`--${i}--`))return;let o=e.split(`--${i}`);if(!/^--(\r?\n|$)/.test(o[o.length-1]))return;let a=new Set(t),s=new Set,u=[];for(let l of o.slice(1)){if(l.startsWith("--"))break;let c=l.indexOf(`\r+\r+`);if(c===-1)return;let d=(r=/^Content-Type:\s*multipart\/mixed;\s*boundary=(\S+)/im.exec(l.slice(0,c)))===null||r===void 0?void 0:r[1];if(d===void 0||d===i)return;let f=l.slice(c+4).split(`--${d}`);if(f.length<3||f[0].trim()!==""||!/^--(\r?\n|$)/.test(f[f.length-1]))return;for(let p of f.slice(1,-1)){let m=nR(p,a,s);if(m===void 0)return;u.push(m)}}return u.length===0?void 0:u}Dt.parseChangeSetsParts=NY});var vc=C(Yt=>{"use strict";Object.defineProperty(Yt,"__esModule",{value:!0});Yt.appApi=Yt.SITEMAP_TARGET_NOT_FOUND_CODE=Yt.deleteAppResolvingOnce=Yt.publishApp=Yt.assertAppPublicationCombinable=Yt.assertAppPublicationProvable=Yt.mainFormModeIssues=Yt.mainFormSetShapeIssues=Yt.unpublishedAppModulesQuery=void 0;var kr=Ke(),_Y=Nw(),iR=Vh(),Fw=mo(),IY=Ff(),TY=_w(),ea=qi(),ce=pe(),De=ae(),Pw=ft(),ju=Zo(),fe=Y(),OY=(0,De.odataQuery)([["$select","appmoduleid,name,uniquename,description,aiappdescription"]]),zh="appmoduleid,name,uniquename,description,aiappdescription";function Vf(e,t,n){return"/appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,De.odataQuery)([["$select",e],["$filter",t],["$top",n]])}Yt.unpublishedAppModulesQuery=Vf;function Rw(e,t){return Vf(e,t?`appmoduleid eq ${t}`:void 0,t?1:void 0)}function Zh(e,t){return"/sitemaps/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,De.odataQuery)([["$select",t],["$filter",`sitemapid eq ${e}`],["$top",1]])}function qf(e){var t;let n=(t=e.body)===null||t===void 0?void 0:t.value;if(Array.isArray(n))return n[0]}function DY(e){let t=e?.["@odata.etag"];return typeof t=="string"?t:null}function Gf(e,t){if(typeof e!="string")return!1;try{return(0,De.normalizeGuid)(e,"sitemapid")===t}catch{return!1}}function Gu(e){let t=new Set,n=[];for(let r of e??[])r&&!t.has(r)&&(t.add(r),n.push(r));return n}function PY(e){return`cdsapp_${(e||"").replace(/[^a-zA-Z0-9]/g,"")||"app"}`}async function RY(e,t){var n,r;let i=l=>{throw new fe.SdkError("APP_SITEMAP_UNRESOLVED",`The sitemap lookup for app uniquename '${t??""}' ${l}, 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,De.odataQuery)([["$select","sitemapid"],["$filter",`sitemapnameunique eq '${(0,De.odataLiteral)(t)}'`],["$top",1]])}`,a;try{a=await e.get(o)}catch(l){return i(`failed (${l.message})`)}if(a.status<200||a.status>=300)return i(`returned HTTP ${a.status}`);let s=(n=a.body)===null||n===void 0?void 0:n.value;if(!Array.isArray(s))return i("returned a malformed body");if(!(0,kr.boundedPageComplete)(a.body,s.length))return i("returned no row but says more rows exist (or links to them)");let u=(r=s[0])===null||r===void 0?void 0:r.sitemapid;return s.length>0&&!u?i("returned a row with no sitemapid"):u}async function kY(e){let t=s=>`/webresourceset${(0,De.odataQuery)([["$select","webresourceid"],["$top",1],["$filter",s]])}`,n=async s=>{var u,l;let c=t(s),d=await e.get(c),f=(u=d.body)===null||u===void 0?void 0:u.value;if(Array.isArray(f)&&!(0,kr.boundedPageComplete)(d.body,f.length))throw new fe.ConnectionError(e.apiUrl(c),d.status,"the app icon lookup answered no web resource but says more rows exist (or links to them); refusing to choose a less suitable icon from an incomplete answer. Nothing was written.");return(l=f?.[0])===null||l===void 0?void 0:l.webresourceid},r="(webresourcetype eq 5 or webresourcetype eq 6 or webresourcetype eq 7 or webresourcetype eq 10 or webresourcetype eq 11)",i=await n("webresourcetype eq 5 and ismanaged eq false and contains(name,'icon')");if(i)return{id:i,managed:!1};let o=await n(`${r} and ismanaged eq false`);if(o)return{id:o,managed:!1};let a=await n(r);return a?{id:a,managed:!0}:void 0}var oR="627090ff-40a3-4053-8790-584edc5be201";function Gn(e){return e instanceof Error?e.message:String(e)}async function $Y(e,t){var n;try{let r=`/roles${(0,De.odataQuery)([["$select","roleid,_parentrootroleid_value"],["$filter",`_roletemplateid_value eq ${oR}`]])}`,i=await(0,kr.collectPages)(e,r,"the System Administrator role"),o=i.find(u=>typeof u.roleid=="string"&&typeof u._parentrootroleid_value=="string"&&u.roleid.toLowerCase()===u._parentrootroleid_value.toLowerCase()),a=(n=o??i.find(u=>typeof u.roleid=="string"))===null||n===void 0?void 0:n.roleid;if(!a)return`App roles: no 'System Administrator' role (template ${oR}) 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,ce.ensureSuccess)(await e.post(s,{"@odata.id":e.apiUrl(`/roles(${a})`)}),e.apiUrl(s)),null}catch(r){return`App roles: could not associate the 'System Administrator' role with the app (${Gn(r)}); it will not be visible or playable until a role is granted access to it.`}}async function LY(e,t,n=!0){let r=[];async function i(u,l,c){try{return(await(0,kr.collectPages)(e,u,`app assets (${c} for '${t}')`)).map(f=>String(f[l])).filter(f=>f&&f!=="undefined")}catch(d){return r.push(`App components: could not enumerate ${c} for table '${t}' (${Gn(d)}); they were NOT added to the app.`),[]}}let[o,a,s]=await Promise.all([n?i(`/systemforms${(0,De.odataQuery)([["$select","formid"],["$filter",`objecttypecode eq '${(0,De.odataLiteral)(t)}' and type eq 2 and formactivationstate eq 1`]])}`,"formid","forms"):Promise.resolve([]),i(`/savedqueries${(0,De.odataQuery)([["$select","savedqueryid"],["$filter",`returnedtypecode eq '${(0,De.odataLiteral)(t)}' and querytype eq 0 and statecode eq 0`]])}`,"savedqueryid","views"),i(`/savedqueryvisualizations${(0,De.odataQuery)([["$select","savedqueryvisualizationid"],["$filter",`primaryentitytypecode eq '${(0,De.odataLiteral)(t)}'`]])}`,"savedqueryvisualizationid","charts")]);return{forms:o,views:a,charts:s,warnings:r}}var aR=new WeakMap;async function MY(e,t){let n=aR.get(e);n||(n=new Map,aR.set(e,n));let r=n.get(t);if(r!==void 0)return r;let i=await xY(e,t);return i&&n.set(t,i),i}async function sR(e,t,n){let r=new Array(e.length),i=0;async function o(){for(let a=i;a<e.length;a=i)i=a+1,r[a]=await n(e[a])}return await Promise.all(Array.from({length:Math.min(t,e.length)},()=>o())),r}async function xY(e,t){let n=`/EntityDefinitions(LogicalName='${(0,De.odataPathLiteral)(t)}')${(0,De.odataQuery)([["$select","MetadataId,EntitySetName"]])}`,r=await e.get(n);if(r.status>=200&&r.status<300){let i=r.body;if(i?.MetadataId&&i.EntitySetName)return{logicalName:t,metadataId:i.MetadataId,entitySetName:i.EntitySetName}}}async function uR(e,t,n){let r=[],i=Gu(t.entities),o=4,a=await sR(i,o,g=>MY(e,g)),s=i.filter((g,y)=>!a[y]);if(s.length>0)throw new fe.SdkError("APP_ENTITY_COMPONENT_UNRESOLVED",`Refusing to build app components: table(s) ${s.map(g=>`'${g}'`).join(", ")} could not be resolved to an EntityDefinitions MetadataId + EntitySetName. Pinning the rest would produce an app whose navigation references a table the app does not contain. Verify the table name(s) exist in this environment and retry.`);let u=a.filter(g=>!!g);for(let g of u)r.push({"@odata.id":`${g.entitySetName}(${g.metadataId})`});for(let g of Gu(t.components.forms))r.push({"@odata.type":"Microsoft.Dynamics.CRM.systemform",formid:g});for(let g of Gu(t.components.views))r.push({"@odata.type":"Microsoft.Dynamics.CRM.savedquery",savedqueryid:g});for(let g of Gu(t.components.charts))r.push({"@odata.type":"Microsoft.Dynamics.CRM.savedqueryvisualization",savedqueryvisualizationid:g});for(let g of Gu(t.components.dashboards))r.push({"@odata.type":"Microsoft.Dynamics.CRM.systemform",formid:g});let l=new Set(t.components.forms),c=new Set(t.components.views),d=new Set(t.components.charts),f=new Map((n??[]).map(g=>[g.table,g])),p=await sR(i,o,g=>LY(e,g,!f.has(g.toLowerCase()))),m=p.flatMap(g=>g.warnings),h=new Set([...Gu(t.components.forms),...Gu(t.components.dashboards)].map(Ze));return p.forEach((g,y)=>{let b=f.get(i[y].toLowerCase());if(b)for(let E of b.allowed)h.has(E)||(h.add(E),l.add(E),r.push({"@odata.type":"Microsoft.Dynamics.CRM.systemform",formid:E}));else for(let E of g.forms)l.has(E)||(l.add(E),r.push({"@odata.type":"Microsoft.Dynamics.CRM.systemform",formid:E}));for(let E of g.views)c.has(E)||(c.add(E),r.push({"@odata.type":"Microsoft.Dynamics.CRM.savedquery",savedqueryid:E}));for(let E of g.charts)d.has(E)||(d.add(E),r.push({"@odata.type":"Microsoft.Dynamics.CRM.savedqueryvisualization",savedqueryvisualizationid:E}))}),{components:r,tables:u,warnings:m}}function Ze(e){let t=String(e).trim();return(t.startsWith("{")&&t.endsWith("}")?t.slice(1,-1):t).toLowerCase()}var ta=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,kw="/components/mainFormsByTable",lR=50;function gR(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}function yR(e,t){if(e===void 0)return[];if(e===null||typeof e!="object"||Array.isArray(e))return[{pointer:kw,rule:"app-main-form-set-shape",message:"must be an object mapping a table logical name to its Main form ids"}];let n=[],r=new Set(t.map(o=>o.toLowerCase())),i=new Set;for(let[o,a]of Object.entries(e)){let s=o.toLowerCase(),u=`${kw}/${gR(o)}`;if(i.has(s)){n.push({pointer:u,rule:"app-main-form-set-shape",message:`table '${o}' is listed twice (logical names compare case-insensitively)`});continue}if(i.add(s),r.has(s)||n.push({pointer:u,rule:"app-main-form-set-table",message:`'${o}' is not a table this app's sitemap navigates to (Entity subareas: ${[...r].join(", ")||"none"})`}),!Array.isArray(a)){n.push({pointer:u,rule:"app-main-form-set-shape",message:"must be an array of Main form ids"});continue}if(a.length===0){n.push({pointer:u,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 l=new Set;a.forEach((c,d)=>{let f=`${u}/${d}`;typeof c!="string"||!ta.test(Ze(c))?n.push({pointer:f,rule:"app-main-form-set-shape",message:`'${String(c)}' is not a form id`}):l.has(Ze(c))?n.push({pointer:f,rule:"app-main-form-set-shape",message:`form '${c}' is listed twice`}):l.add(Ze(c))})}return n}Yt.mainFormSetShapeIssues=yR;var cR="/components/mainFormsOnUpdate";function bR(e,t){if(e===void 0)return[];if(e!=="addOnly"&&e!=="exact")return[{pointer:cR,rule:"app-main-form-mode-shape",message:`must be 'addOnly' or 'exact', not ${JSON.stringify(e)}`}];let n=t!==null&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length>0;return e==="exact"&&!n?[{pointer:cR,rule:"app-main-form-mode-without-list",message:"'exact' needs a non-empty components.mainFormsByTable: it removes only the Main forms of a LISTED table that the list does not name, so without one it would remove nothing"}]:[]}Yt.mainFormModeIssues=bR;async function dR(e,t,n){let r=t.components.mainFormsByTable,i=bR(t.components.mainFormsOnUpdate,r);if(i.length>0)throw new fe.ValidationError("app",n,i);if(r===void 0)return;let o=yR(r,t.entities);if(o.length>0)throw new fe.ValidationError("app",n,o);if(Object.keys(r).length===0)return;let a=[],s=[];for(let[l,c]of Object.entries(r)){let d=l.toLowerCase(),f=await(0,kr.collectPages)(e,`/systemforms${(0,De.odataQuery)([["$select","formid,formactivationstate"],["$filter",`objecttypecode eq '${(0,De.odataLiteral)(d)}' and type eq 2`]])}`,`app Main-form allow-list ('${d}')`),p=new Set,m=new Set;for(let g of f)typeof g.formid=="string"&&(p.add(Ze(g.formid)),Number(g.formactivationstate)===1&&m.add(Ze(g.formid)));let h=c.map(Ze);h.forEach((g,y)=>{let b=`${kw}/${gR(l)}/${y}`;p.has(g)?m.has(g)||a.push({pointer:b,rule:"app-main-form-set-inactive",message:`Main form '${c[y]}' of '${d}' is inactive, so no app can offer it`}):a.push({pointer:b,rule:"app-main-form-set-not-main-form",message:`'${c[y]}' is not a Main form of '${d}'`})}),s.push({table:d,allowed:h,catalog:p})}let u=[...t.components.forms.map((l,c)=>({id:l,pointer:`/components/forms/${c}`})),...t.components.dashboards.map((l,c)=>({id:l,pointer:`/components/dashboards/${c}`}))];for(let l of u){let c=Ze(l.id);for(let d of s)d.catalog.has(c)&&!d.allowed.includes(c)&&a.push({pointer:l.pointer,rule:"app-main-form-set-conflict",message:`'${l.id}' is a Main form of '${d.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(a.length>0)throw new fe.ValidationError("app",n,a);return s}function eg(e,t=new Map){return e.tables.map(n=>{var r;return{table:n.table,membership:n.extras.length===0&&n.missing.length===0?"exact":"notExact",removed:((r=t.get(n.table))!==null&&r!==void 0?r:[]).filter(i=>!n.members.includes(i)),retained:n.extras,missing:n.missing}})}function $w(e,t){return e.map(n=>({table:n.table,membership:"inconclusive",removed:[],retained:[],missing:[],reason:t}))}async function tg(e,t){var n,r;let i=l=>({kind:"inconclusive",reason:l}),o=await e.get(Vf("appmoduleid,appmoduleidunique,componentstate",`appmoduleid eq ${t}`));if(o.status<200||o.status>=300)return i(`reading the app returned HTTP ${o.status}`);let a=(n=o.body)===null||n===void 0?void 0:n.value;if(!Array.isArray(a)||a.length===0)return i("reading the app returned no row");if((0,kr.pageEnd)(o.body).kind!=="end")return i("reading the app returned a page that says more rows exist (or links to them)");let s=a.length===1?a:a.filter(l=>Number(l?.componentstate)===1),u=s.length===1?(r=s[0])===null||r===void 0?void 0:r.appmoduleidunique:"";return typeof u!="string"||!ta.test(Ze(u))?i(`no single current layer among ${a.length} app row(s)`):{kind:"read",unique:Ze(u)}}function xs(e,t){let n;return()=>n??(n=tg(e,t))}var vR=62;function FY(e,t,n,r,i){let o=i.map(a=>`'${a}'`).join(", ");return t==="delete"?new fe.SdkError("APP_SITEMAP_SHARED",`Refusing to delete app '${e}': its sitemap '${n.sitemapId}' is also the navigation of app ${o}. The delete removes an app's sitemap with it, and the platform does not stop that for a sitemap another app uses, so those apps would be left without navigation. Nothing was deleted. Remove the sitemap from the other app first, then retry.`):new fe.SdkError("APP_SITEMAP_SHARED",`Refusing to ${t} app '${e}': it has no SiteMap component, and the sitemap named like it ('${r??""}', '${n.sitemapId}') is the navigation of app ${o}, so it is not this app's. Nothing was ${t==="fetch"?"saved":"modified"}.`)}async function Bf(e,t,n,r,i=!1){var o;let a=c=>{throw new fe.SdkError("APP_SITEMAP_UNRESOLVED",`Refusing to ${r} app '${t}': ${c}, so it cannot be determined which sitemap is this app's. Nothing was ${r==="fetch"?"saved":r==="delete"?"deleted":"modified"}. Retry.`)},s;try{s=await tg(e,t)}catch(c){return a(`reading its current layer failed (${Gn(c)})`)}if(s.kind==="inconclusive")return a(`its current layer could not be read (${s.reason})`);let u;try{u=await(0,kr.collectPages)(e,`/appmodulecomponents${(0,De.odataQuery)([["$select","objectid"],["$filter",`_appmoduleidunique_value eq ${s.unique} and componenttype eq ${vR}`]])}`,`app SiteMap component ('${t}')`)}catch(c){return a(`reading its SiteMap component failed (${Gn(c)})`)}let l;if(u.length>1)return a(`its current layer carries ${u.length} SiteMap components, where an app can hold one`);if(u.length===1){let c=(o=u[0])===null||o===void 0?void 0:o.objectid;if(typeof c!="string"||!ta.test(Ze(c)))return a(`its SiteMap component carries an object id that is not a GUID ('${String(c)}')`);l={sitemapId:Ze(c),by:"component"}}else{let c=await RY(e,n);if(!c)return;let d;try{d=(0,De.normalizeGuid)(c,"sitemapId")}catch{return a(`the sitemap lookup by unique name returned a sitemapid that is not a GUID ('${String(c)}')`)}l={sitemapId:d,by:"name"}}if(i||l.by==="name"){let c=await UY(e,l.sitemapId,t,a);if(c.length>0)throw FY(t,r,l,n,c)}return l}async function UY(e,t,n,r){var i;let o;try{o=await(0,kr.collectPages)(e,`/appmodulecomponents${(0,De.odataQuery)([["$select","_appmoduleidunique_value"],["$filter",`componenttype eq ${vR} and objectid eq ${t}`]])}`,`apps using sitemap '${t}'`)}catch(l){return r(`reading which apps use sitemap '${t}' failed (${Gn(l)})`)}let a=new Set;for(let l of o){let c=l?._appmoduleidunique_value;if(typeof c!="string"||!ta.test(Ze(c)))return r(`a SiteMap component naming sitemap '${t}' carries no app layer id`);a.add(Ze(c))}let s=Ze(n),u=[];for(let l of a){let c;try{c=await e.get(Vf("appmoduleid",`appmoduleidunique eq ${l}`))}catch(f){return r(`resolving app layer '${l}' failed (${Gn(f)})`)}if(c.status<200||c.status>=300)return r(`resolving app layer '${l}' returned HTTP ${c.status}`);let d=(i=c.body)===null||i===void 0?void 0:i.value;if(!Array.isArray(d))return r(`resolving app layer '${l}' returned a malformed body`);if((0,kr.pageEnd)(c.body).kind!=="end")return r(`resolving app layer '${l}' returned a page that says more rows exist (or links to them)`);for(let f of d){let p=f?.appmoduleid;if(typeof p!="string"||!ta.test(Ze(p)))return r(`app layer '${l}' resolved to a row with no app id`);let m=Ze(p);if(m===s||u.includes(m))continue;let h;try{h=await tg(e,m)}catch(g){return r(`reading the current layer of app '${m}' failed (${Gn(g)})`)}if(h.kind==="inconclusive")return r(`the current layer of app '${m}' could not be read (${h.reason})`);h.unique===l&&u.push(m)}}return u}async function Wu(e,t,n,r=xs(e,t)){let i=p=>({kind:"inconclusive",reason:p}),o=await r();if(o.kind==="inconclusive")return o;let a=o.unique,s;try{let p=await(0,kr.collectPages)(e,`/appmodulecomponents${(0,De.odataQuery)([["$select","objectid"],["$filter",`_appmoduleidunique_value eq ${Ze(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=>Ze(String(m.objectid)))}catch(p){return i(`reading its form components failed (${Gn(p)})`)}let u=new Map,l=[];for(let p of new Set(s)){let m=n.find(h=>h.catalog.has(p));m?u.set(p,m.table):l.push(p)}if(l.some(p=>!ta.test(p)))return i("a form component carries an object id that is not a GUID");let c=new Set(n.map(p=>p.table)),d=new Set;for(let p=0;p<l.length;p+=lR){let m=l.slice(p,p+lR);try{let h=await(0,kr.collectPages)(e,`/systemforms${(0,De.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 y=Ze(g.formid);d.add(y);let b=g.type===2?String(g.objecttypecode).toLowerCase():"";c.has(b)&&u.set(y,b)}}catch(h){return i(`classifying its form components failed (${Gn(h)})`)}}let f=l.filter(p=>!d.has(p));return f.length>0?i(`form component(s) ${f.join(", ")} could not be classified`):{kind:"read",tables:n.map(p=>{let m=[...u].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 qY(e,t,n,r){let i=await Wu(e,t,n,r);if(i.kind==="inconclusive")throw new fe.SdkError("APP_MAIN_FORM_SET_UNVERIFIED",`App '${t}': its Main-form allow-list was written but could not be verified \u2014 ${i.reason}.`);let o=i.tables.filter(a=>a.extras.length>0||a.missing.length>0);if(o.length>0)throw new fe.SdkError("APP_MAIN_FORM_SET_NOT_APPLIED",`App '${t}': its Main forms do not match the allow-list after the write \u2014 ${o.map(a=>`'${a.table}': unexpected [${a.extras.join(", ")}], missing [${a.missing.join(", ")}]`).join("; ")}.`);return i}async function BY(e,t,n,r){let i;try{i=await Wu(e,t,n,r)}catch(a){i={kind:"inconclusive",reason:Gn(a)}}if(i.kind==="inconclusive")return{warnings:[`Main-form membership of app '${t}' could not be verified (${i.reason}).`],tables:$w(n,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{warnings:o,tables:eg(i)}}function VY(e){return{"@odata.type":"Microsoft.Dynamics.CRM.systemform",formid:e}}async function Uw(e,t){let{body:n,batchId:r,contentIds:i}=(0,ju.renderChangeSet)(e,t),o;try{o=await e.postBatch(n,r)}catch(u){return{kind:"unknown",reason:`its answer was lost (${Gn(u)})`}}let a=(0,ju.parseChangeSetParts)(o.body,i);if(!a)return{kind:"unknown",reason:`its answer (HTTP ${o.status}) could not be read as a change set`};let s=a.find(u=>u.status<200||u.status>=300);return s?{kind:"refused",op:t[i.indexOf(s.contentId)],answer:(0,ju.partResponse)(s)}:a.length!==t.length?{kind:"unknown",reason:`its answer reported ${a.length} result(s) for ${t.length} operation(s)`}:{kind:"committed",answers:i.map(u=>(0,ju.partResponse)(a.find(l=>l.contentId===u)))}}function Lw(e,t,n,r){var i;let o=(i=n.answer.body)===null||i===void 0?void 0:i.error,a=typeof o?.code=="string"?` ${o.code}`:"",s=typeof o?.message=="string"?`: ${o.message}`:"",u=`${n.op.method} ${n.op.path.split("?")[0]}`;return n.answer.status===412?new fe.SdkError(ce.VERSION_CONFLICT_CODE,`${r} of app '${t}' was refused: ${u} answered 412${a} \u2014 the row moved since this copy (another writer changed the app's header, its components or its sitemap). Nothing was committed: the change set is atomic. Re-fetch the app, re-apply BOTH components.mainFormsByTable and components.mainFormsOnUpdate (a fetch carries neither), and push again.`):new fe.ConnectionError(e.apiUrl("/$batch"),n.answer.status,`${r} of app '${t}' was refused and rolled back: ${u} answered HTTP ${n.answer.status}${a}${s}. Nothing was committed: the change set is atomic.`,n.answer.body)}async function Kh(e,t){try{let n=await e.get(`/appmodules(${t})?$select=appmoduleid`);return n.status>=200&&n.status<300?(0,ce.readEtag)(n):null}catch{return null}}async function GY(e,t,n){return t.observe({guard:"ifMatch",componentName:"AppModule",componentId:n.appId,held:n.appToken,server:n.serverAppToken,status:(0,ea.compareTokens)(n.appToken,n.serverAppToken)}),await(0,ea.observeIfMatch)(e,t,{entitySet:"sitemaps",idColumn:"sitemapid",id:n.sitemapId,componentName:"SiteMap",held:n.sitemapToken}),t.reached({effects:[{componentName:"AppModule",componentId:n.appId,identity:"known",operation:"update"},{componentName:"SiteMap",componentId:n.sitemapId,identity:"known",operation:"update"}],attemptsWrite:!0})}async function jY(e){var t,n,r,i;let{client:o,appId:a,body:s,sets:u}=e,l=X=>new fe.SdkError("APP_MAIN_FORM_REMOVAL_UNSUPPORTED",`Refusing exact Main-form reconciliation of app '${a}': ${X}. Nothing was modified.`);if(!o.supportsAtomicBatch)throw l("the HttpClient has no postRaw(), and the removal is bound to this copy only inside ONE $batch change set");if(!e.currentHeader)throw l(e.headerProblem?`its header read is ambiguous \u2014 ${e.headerProblem} \u2014 so neither its managed state nor the header edit can be judged`:"the app's header could not be read, so whether it is managed is unknown");if(e.currentHeader.ismanaged!==!1)throw l(`it is not affirmatively unmanaged (ismanaged: ${JSON.stringify(e.currentHeader.ismanaged)}); removal from a managed app has not been verified`);let c=`/appmodules(${a})?$select=appmoduleid`,d={guard:"rowToken",componentName:"AppModule",componentId:a,held:e.appToken},f;try{f=await o.get(c)}catch(X){throw(t=e.preview)===null||t===void 0||t.observe({...d,status:(0,ea.failedReadStatus)(X),detail:(0,ea.failureDetail)(X)}),X}if(f.status===404)throw l("it is a draft (never published), and a draft app row cannot carry the condition that binds the removal to this copy. Publish it first (published: true in the default mode), then push exact");if(e.preview&&(f.status<200||f.status>=300)&&e.preview.observe({...d,status:"readFailed",detail:`HTTP ${f.status}`}),(0,ce.ensureSuccess)(f,o.apiUrl(c)),!(0,ce.isVersionToken)(e.appToken))throw(n=e.preview)===null||n===void 0||n.observe({...d,status:"missingHeld"}),new fe.SdkError("APP_UPDATE_NO_ETAG",`Refusing to push app '${a}' in exact Main-form mode: ${e.appToken?`the concurrency token held for its appmodule row ('${e.appToken}') is not a version`:"no concurrency token is held for its appmodule row"}, so the removal could not be bound to this copy. Nothing was modified. Re-fetch the app (fetchArtifact('app', '${a}', { overwrite: true })), re-apply BOTH components.mainFormsByTable and components.mainFormsOnUpdate, and push again.`);let p=(0,ce.readEtag)(f);if((r=e.preview)===null||r===void 0||r.observe({...d,server:p,status:(0,ea.compareTokens)(e.appToken,p)}),p!==e.appToken)throw new fe.SdkError(ce.VERSION_CONFLICT_CODE,`Version conflict for app '${a}': its appmodule row moved since this copy (held ${e.appToken}, now ${p??"(none)"}) \u2014 another writer changed its header or its components. Nothing was modified.`);let m=await Wu(o,a,u,xs(o,a));if(m.kind==="inconclusive")throw new fe.SdkError("APP_MAIN_FORM_SET_UNVERIFIED",`App '${a}': its Main-form membership could not be read before the exact write (${m.reason}). Nothing was modified.`);let h=new Map(m.tables.map(X=>[X.table,X.extras])),g=m.tables.flatMap(X=>X.extras);if(e.preview)return GY(o,e.preview,{appId:a,sitemapId:e.sitemapId,sitemapToken:e.sitemapToken,appToken:e.appToken,serverAppToken:p});let y={Prefer:"return=representation"},b=[{method:"PATCH",path:`/appmodules(${a})`,body:e.headerWrite,etag:e.appToken},{method:"PATCH",path:`/sitemaps(${e.sitemapId})${(0,ce.echoWrite)("sitemapid").query}`,body:{...Xh(s)},etag:e.sitemapToken,headers:y},...e.plan.components.length>0?[{method:"POST",path:"/AddAppComponents",body:{AppId:a,Components:e.plan.components}}]:[],...g.length>0?[{method:"POST",path:"/RemoveAppComponents",body:{AppId:a,Components:g.map(VY)}}]:[],{method:"PATCH",path:`/appmodules(${a})?$select=appmoduleid`,body:{},headers:y}],E=await Uw(o,b);if(E.kind==="refused")throw Lw(o,a,E,"The exact write");let w=HY(o,a,u);if(E.kind==="unknown")throw await WY(e,E.reason);let _=(0,ce.readEtag)(E.answers[1]),I=(0,ce.readEtag)(E.answers[E.answers.length-1]),T=[...e.plan.warnings],O=xs(o,a);try{await Mw(o,a,e.plan.tables,O)}catch(X){T.push(`App '${a}': one or more components were not pinned (${X.message}). Navigation may reference content not included in the app; re-push to retry.`)}let v;try{v=await Wu(o,a,w,O)}catch(X){v={kind:"inconclusive",reason:Gn(X)}}let N=I?await Kh(o,a):null,S=new Set(u.map(X=>X.table)),R,x=[];if(v.kind==="inconclusive")R=$w(u,v.reason);else if(I&&N!==I)R=$w(u,"another writer changed the app after this push's write");else{let X=eg(v,h);R=X.filter(ye=>S.has(ye.table)),x=X.filter(ye=>!S.has(ye.table)&&ye.membership!=="exact").map(ye=>ye.table)}for(let X of R)X.membership==="inconclusive"?T.push(`Main-form membership of app '${a}' could not be proven after the exact write for table '${X.table}' (${X.reason}); nothing is claimed about it.`):X.membership==="notExact"&&T.push(`Main forms of table '${X.table}' are not exact in app '${a}' after the exact write: retained [${X.retained.join(", ")}], missing [${X.missing.join(", ")}]. Nothing was re-sent.`);I||T.push(`App '${a}': the exact write returned no app token, so none is held \u2014 the next header edit is refused (APP_UPDATE_NO_ETAG) until a re-fetch, after which re-apply BOTH components.mainFormsByTable and components.mainFormsOnUpdate (a fetch carries neither).`);let G={kind:"notRequested"},U="notRead",M=I,q=_;if(s.published===!0)if(!(R.every(ye=>ye.membership==="exact")&&x.length===0)||!I){let ye=x.map(_e=>`'${_e}'`).join(", "),Ve=I?x.length>0&&R.every(_e=>_e.membership==="exact")?`the Main forms of table(s) ${ye} \u2014 listed by an earlier exact push of this app in this SDK instance and not yet seen published \u2014 are not exactly that list`:"the proof after the write is not exact or not readable":"the exact write returned no app token to bind the publish to";G={kind:"failed",error:new fe.SdkError("APP_MAIN_FORM_PUBLISH_WITHHELD",`App '${a}': the requested publish was WITHHELD \u2014 no publish request was sent \u2014 because ${Ve}. The saved change stays on the app's pending layer. ${Jh}`)},T.push(G.error.message)}else{let ye=await ER(o,a,I);if(ye.kind==="refused"&&ye.answer.status===412)G={kind:"failed",error:new fe.SdkError("APP_MAIN_FORM_PUBLISH_CONFLICT",`App '${a}': the publish change set WAS sent, and its guard refused it (412): another writer changed the app after this push's write. Nothing was published. ${Jh}`)},T.push(G.error.message);else if(ye.kind==="refused")G={kind:"failed",error:Lw(o,a,ye,"The publish")},T.push(`App '${a}': saved, but publishing failed (${G.error.message}).`);else{G=ye.kind==="committed"?{kind:"submitted"}:{kind:"unverifiable",reason:`the publish change set was sent, but ${ye.reason}`},ye.kind==="unknown"&&T.push(`App '${a}': the publish change set was sent, but ${ye.reason}; it may have published.`);let Ve=await wR(o,a,w,v);U=zY(Ve,u),qw(o,a,Ve.kind==="read"?Ve.matching:[]),U!=="matches"&&T.push(U==="differs"?`App '${a}': its published layer does not hold the Main forms the current layer was proven to hold.`:`App '${a}': its published layer could not be read, so the published Main forms are unverified.`),M=ye.kind==="committed"?await Kh(o,a):null,q=(i=await Hh(o,e.sitemapId,Xh(s),e.expectedUniqueName))!==null&&i!==void 0?i:_}}else R.some(X=>X.removed.length>0)&&T.push(`App '${a}': the exact write changed the app's pending (unpublished) layer, and this push did not publish \u2014 what users get was not read. To publish it, push again in exact mode with published: true \u2014 the guarded publish re-proves the membership first; a plain publishArtifact would publish whatever is pending by then.`);return{id:a,etag:q,siblingEtags:{[a]:M},publish:G,...T.length>0?{warnings:T}:{},appMainForms:{mode:"exact",tables:R,published:U}}}async function WY(e,t){let{client:n,appId:r}=e,i;try{let o=await n.get(`/sitemaps(${e.sitemapId})?$select=sitemapid`),a=o.status>=200&&o.status<300?(0,ce.readEtag)(o):null;if(!(0,ce.isVersionToken)(a))i=`the outcome cannot be observed (the sitemap token could not be read: HTTP ${o.status})`;else if(a===e.sitemapToken)i="commit not observed at this read; the request may still complete";else{i="a write occurred (the sitemap token moved); it cannot be attributed to this push";try{let s=await Wu(n,r,e.sets,xs(n,r));s.kind==="read"&&(i+=` \u2014 the current layer now holds ${s.tables.map(u=>`'${u.table}': [${u.members.join(", ")}]`).join("; ")}`)}catch{}}}catch(o){i=`the outcome cannot be observed (${Gn(o)})`}return new fe.SdkError("APP_UPDATE_OUTCOME_UNKNOWN",`The exact write of app '${r}' was sent, but ${t}: whether it committed is NOT CONFIRMED. Observed: ${i}. Nothing was re-sent and the held tokens are kept. Re-pushing this same copy is safe \u2014 it is conditioned on the same tokens, so at most one of the two writes can commit; a re-fetch does not prove that this write settled.`)}async function wR(e,t,n,r){var i;let o={kind:"unreadable"};if(r.kind==="inconclusive")return o;let a;try{let l=await e.get(`/appmodules(${t})?$select=appmoduleidunique`),c=(i=l.body)===null||i===void 0?void 0:i.appmoduleidunique;if(l.status<200||l.status>=300||typeof c!="string"||!ta.test(Ze(c)))return o;a=Ze(c)}catch{return o}let s;try{s=await Wu(e,t,n,()=>Promise.resolve({kind:"read",unique:a}))}catch{return o}return s.kind==="inconclusive"?o:{kind:"read",matching:r.tables.filter(l=>{let c=s.kind==="read"?s.tables.find(d=>d.table===l.table):void 0;return c!==void 0&&c.members.length===l.members.length&&c.members.every(d=>l.members.includes(d))}).map(l=>l.table)}}function zY(e,t){return e.kind==="unreadable"?"unreadable":t.every(n=>e.matching.includes(n.table))?"matches":"differs"}var Jh="Do NOT publish it plainly: from this SDK instance, publishArtifact and setAppTheme with publish: true now prove the membership again and publish only in a guarded change set, but a publish from another instance, process or tool repeats neither the proof nor the guard and would publish whatever is pending (a listed table left with no Main form makes the app offer every form). Review the app, re-fetch it (keeping any edits of your own aside), re-apply BOTH components.mainFormsByTable and components.mainFormsOnUpdate, and push again in exact mode with published: true.",Yh=new WeakMap;function HY(e,t,n){var r;let i=Yh.get(e);i||(i=new Map,Yh.set(e,i));let o=Ze(t),a=(r=i.get(o))!==null&&r!==void 0?r:new Map;i.set(o,a);for(let u of n)a.set(u.table,u);let s=new Set(n.map(u=>u.table));return[...n,...[...a.values()].filter(u=>!s.has(u.table))]}function qw(e,t,n){let r=Yh.get(e),i=Ze(t),o=r?.get(i);if(!(!r||!o)){for(let a of n??[...o.keys()])o.delete(a);o.size===0&&r.delete(i)}}function Bw(e,t){var n;let r=(n=Yh.get(e))===null||n===void 0?void 0:n.get(Ze(String(t)));return r&&r.size>0?[...r.values()]:void 0}function ER(e,t,n){return Uw(e,[{method:"PATCH",path:`/appmodules(${t})`,body:{},etag:n},{method:"POST",path:"/PublishXml",body:{ParameterXml:(0,Fw.appModulePublishParameterXml)(t)}}])}async function AR(e,t,n){let r=await Kh(e,t);if(!(0,ce.isVersionToken)(r))return{why:"the app row's version could not be read, so a publish could not be bound to the membership"};let i;try{i=await Wu(e,t,n,xs(e,t))}catch(a){i={kind:"inconclusive",reason:Gn(a)}}if(i.kind==="inconclusive")return{why:`its Main-form membership could not be read (${i.reason})`};let o=eg(i).filter(a=>a.membership!=="exact");return o.length>0?{why:`its Main forms are not exactly the listed ones (${o.map(a=>`'${a.table}': outside the list [${a.retained.join(", ")}], missing [${a.missing.join(", ")}]`).join("; ")})`}:{token:r,membership:i}}function Vw(e,t,n="the requested publish"){return new fe.SdkError("APP_MAIN_FORM_PUBLISH_WITHHELD",`App '${e}': ${n} was WITHHELD \u2014 no publish request was sent \u2014 because this SDK instance's exact Main-form push of the app left a membership no published layer was seen to hold, and ${t}. `+Jh)}async function KY(e,t){let n=Bw(e,t);if(!n)return;let r=(0,De.normalizeGuid)(t,"appId"),i=await AR(e,r,n);if("why"in i)throw Vw(r,i.why)}Yt.assertAppPublicationProvable=KY;function JY(e,t){if(Bw(e,t))throw Vw((0,De.normalizeGuid)(t,"appId"),"its publication must be proven and guarded on its own, which one combined PublishXml envelope cannot carry \u2014 publish it with publishArtifact","publishing it in publishArtifacts")}Yt.assertAppPublicationCombinable=JY;async function CR(e,t){let n=Bw(e,t);if(!n)return(0,Fw.publishAppModule)(e,t);let r=(0,De.normalizeGuid)(t,"appId"),i=await AR(e,r,n);if("why"in i)throw Vw(r,i.why);let o=await ER(e,r,i.token);if(o.kind==="refused")throw o.answer.status===412?new fe.SdkError("APP_MAIN_FORM_PUBLISH_CONFLICT",`App '${r}': the guarded publish change set WAS sent, and its guard refused it (412): the app changed after its Main forms were proven. Nothing was published. ${Jh}`):Lw(e,r,o,"The guarded publish");let a=await wR(e,r,n,i.membership);if(qw(e,r,a.kind==="read"?a.matching:[]),o.kind==="unknown")throw new fe.ConnectionError(e.apiUrl("/$batch"),0,`the guarded publish change set of app '${r}' was sent, but ${o.reason}; it may have published`)}Yt.publishApp=CR;async function SR(e,t,n){if(n.length===0)return;let r="/AddAppComponents";(0,ce.ensureSuccess)(await e.post(r,{AppId:t,Components:n}),e.apiUrl(r))}function YY(e,t){let n=Object.keys(e),r=e["@odata.id"];if(n.length===1&&typeof r=="string"){let s=t.find(u=>`${u.entitySetName}(${u.metadataId})`===r);return s&&ta.test(Ze(s.metadataId))?`1:${Ze(s.metadataId)}`:void 0}let i={"Microsoft.Dynamics.CRM.systemform":["formid",60],"Microsoft.Dynamics.CRM.savedquery":["savedqueryid",26],"Microsoft.Dynamics.CRM.savedqueryvisualization":["savedqueryvisualizationid",59]},o=typeof e["@odata.type"]=="string"?i[e["@odata.type"]]:void 0,a=o?e[o[0]]:void 0;if(!(!o||n.length!==2||typeof a!="string"||!ta.test(Ze(a))))return`${o[1]}:${Ze(a)}`}async function QY(e,t,n,r){let i=[];for(let o of n.components){let a=YY(o,n.tables);if(a===void 0)return"legacy";i.push(a)}try{if(await Kh(e,t)!==r)return"legacy";let o=await tg(e,t);if(o.kind!=="read")return"legacy";let a=await(0,kr.collectPages)(e,`/appmodulecomponents${(0,De.odataQuery)([["$select","objectid,componenttype"],["$filter",`_appmoduleidunique_value eq ${o.unique}`]])}`,`app components ('${t}')`),s=new Set;for(let u of a){if(typeof u.objectid!="string"||!ta.test(Ze(u.objectid))||!Number.isInteger(u.componenttype))return"legacy";s.add(`${u.componenttype}:${Ze(u.objectid)}`)}return i.every(u=>s.has(u))?"allPresent":"missingObserved"}catch{return"legacy"}}async function XY(e,t,n,r){let i=async()=>{try{return await SR(e,t,n.components),{warnings:[]}}catch(s){return{warnings:[],error:s}}};if(r===void 0||await QY(e,t,n,r)!=="missingObserved")return i();let o={method:"POST",path:"/AddAppComponents",body:{AppId:t,Components:n.components}},a=await Uw(e,[{method:"PATCH",path:`/appmodules(${t})`,body:{},etag:r},o,{method:"PATCH",path:`/appmodules(${t})${(0,ce.echoWrite)("appmoduleid").query}`,body:{},headers:{Prefer:"return=representation"}}]);if(a.kind==="committed"){let s=(0,ce.readEtag)(a.answers[a.answers.length-1]);return(0,ce.isVersionToken)(s)?{appToken:s,warnings:[]}:{warnings:[`App '${t}': its components were added, but the change set returned no app token, so the one held is kept \u2014 the next header edit may answer VERSION_CONFLICT until a re-fetch.`]}}if(a.kind==="refused"){if(a.op!==o)return i();let s=new Error(`AddAppComponents answered HTTP ${a.answer.status}`);try{(0,ce.ensureSuccess)(a.answer,e.apiUrl(o.path))}catch(u){s=u}return{warnings:[],error:s}}return{warnings:[`App '${t}': the change set adding its components was sent, but ${a.reason}; it may have committed, and nothing was re-sent. The app token held is kept \u2014 the next header edit may answer VERSION_CONFLICT until a re-fetch.`]}}async function Mw(e,t,n,r=xs(e,t)){var i;if(n.length===0)return;let o=await r();if(o.kind==="inconclusive")throw new fe.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,De.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 fe.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 u=(i=s.body)===null||i===void 0?void 0:i.value;if(!Array.isArray(u))throw new fe.SdkError("APP_COMPONENTS_UNVERIFIED",`App '${t}': its table components were written but could not be verified \u2014 the read-back returned no readable result set. Re-push to retry.`);let l=new Set(u.map(d=>d.objectid).filter(d=>typeof d=="string").map(d=>d.toLowerCase())),c=n.filter(d=>!l.has(d.metadataId.toLowerCase()));if(c.length>0)throw new fe.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 ZY(e,t,n){let r=`/appmodules(${t})`,i=`/sitemaps(${n.sitemapId})`,o;try{o=await tQ(e,n.sitemapId,n.sitemapNameUnique)}catch(u){return{outcome:"kept",reason:`whether its sitemap row exists could not be determined (${Gn(u)})`}}let a=o==="foreign",s=u=>u.kind==="deleted"?{outcome:"removed",foreignSitemap:a}:u.kind==="refused"?{outcome:"kept",foreignSitemap:a,reason:`its delete was refused (${Gn(u.error)})`,...u.lock?{lock:!0}:{}}:{outcome:"unconfirmed",foreignSitemap:a,reason:`its delete was sent but its outcome is unknown (${Gn(u.error)})`,...u.lock?{lock:!0}:{}};try{if(o==="absent"||o==="foreign"){if(!n.serverRefusedSitemap)return{outcome:"kept",foreignSitemap:a,reason:"the sitemap write's outcome was never observed, so its row may still appear"};let u=await(0,ce.resendAppSearchIndexRace)(()=>e.delete(r));if(u.status===404)return s({kind:"deleted"});let l=xw(u,e.apiUrl(r));return s(l.kind!=="deleted"&&(0,ce.isConcurrencyLockRefusal)(u)?{...l,lock:!0}:l)}return e.supportsAtomicBatch?n.sitemapWriteToken?s(await _R(e,[{path:r},{path:i,etag:n.sitemapWriteToken}],{reportLock:!0})):{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(u){return s({kind:"unknown",error:u})}}function eQ(e,t,n){if(!(e instanceof Error))return e;let r=t.foreignSitemap?` Sitemap id '${n.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.${r}`,e;let i=t.foreignSitemap?`appmodule '${n.appId}' (unique name '${n.uniqueName}')`:`appmodule '${n.appId}' (unique name '${n.uniqueName}') and, if it was written, sitemap '${n.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', '${n.appId}')`:`deleteRecord('appmodule', '${n.appId}') and deleteRecord('sitemap', '${n.sitemapId}')`}.`,s="Once the lock frees \u2014 another customization operation holds it \u2014 check that the rows exist and are this create's own before removing them.";return t.lock&&t.outcome==="kept"?e.message+=` The partial app this create wrote was KEPT \u2014 its rollback deleted nothing, because the environment's customization lock refused it (another customization operation was running): ${i}. ${s} While it exists, ${a}`:t.lock?e.message+=` Whether the partial app this create wrote was removed could not be confirmed, because the environment's customization lock refused or interrupted its rollback, so it may not have run. Check for ${i}. ${s} While any of it exists, ${a}`: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+=r,e}async function tQ(e,t,n){var r,i,o;let a=Zh(t,"sitemapid,sitemapnameunique"),s=await e.get(a);if(s.status<200||s.status>=300)throw new fe.SdkError("APP_SITEMAP_UNRESOLVED",`The unpublished-aware read of sitemap '${t}' returned HTTP ${s.status}, so it cannot be determined whether the row exists.`);let u=(r=s.body)===null||r===void 0?void 0:r.value;if(!Array.isArray(u))throw new fe.SdkError("APP_SITEMAP_UNRESOLVED",`The unpublished-aware read of sitemap '${t}' returned no readable result set, so it cannot be determined whether the row exists.`);if(!(0,kr.boundedPageComplete)(s.body,u.length))throw new fe.SdkError("APP_SITEMAP_UNRESOLVED",`The unpublished-aware read of sitemap '${t}' returned no row but says more rows exist (or links to them), so it cannot be determined whether the row exists.`);return u.length===0?"absent":String((o=(i=u[0])===null||i===void 0?void 0:i.sitemapnameunique)!==null&&o!==void 0?o:"")===n?"ours":"foreign"}async function nQ(e,t){var n;let r;try{r=await e.get(Vf("appmoduleid,uniquename,componentstate",`appmoduleid eq ${t}`))}catch(s){return{kind:"unsettled",why:`its unpublished read failed (${s.message})`}}if(r.status<200||r.status>=300)return{kind:"unsettled",why:`its unpublished read returned HTTP ${r.status}`};let i=(n=r.body)===null||n===void 0?void 0:n.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`};if((0,kr.pageEnd)(r.body).kind!=="end")return{kind:"unsettled",why:"its unpublished read says more rows exist (or links to them), so its one row is not exactly one"};let o=i[0],a=o?.uniquename;return!Gf(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 NR(e,t){var n;let r=(0,De.normalizeGuid)(t,"id"),i=b=>{throw new fe.SdkError("APP_SITEMAP_UNRESOLVED",`Refusing to delete app '${r}': ${b} Deleting the app would destroy the only pointer to its sitemap, stranding that row and reserving its unique name forever. Retry.`)},o=`/appmodules(${r})${OY}`,a;try{a=await e.get(o)}catch(b){return i(`reading the app failed (${b.message}).`)}let s,u=!1;if(a.status===404){let b=await nQ(e,r);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,u=!0}else{if(a.status<200||a.status>=300)return i(`reading the app returned HTTP ${a.status}.`);s=(n=a.body)===null||n===void 0?void 0:n.uniquename}if(!s)return i("the app record carried no uniquename, so its sitemap cannot be located.");let l=u?{draft:!0}:{appEtag:(0,ce.readEtag)(a)},c=await Bf(e,r,s,"delete");if(!c)return{uniquename:s,...l};let d=c.sitemapId,f=await Qh(e,d),p=Zh(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=qf(m);if(!h)return i(`sitemap '${d}' was not returned by the unpublished-aware read.`);if(c.by==="name"&&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(!Gf(h.sitemapid,d))return i(`sitemap '${d}' was read back as a row carrying sitemapid '${String(h.sitemapid)}'.`);let g=h.sitemapxml;if(typeof g!="string")return i(`sitemap '${d}' returned no sitemapxml.`);let y=await Bf(e,r,s,"delete",!0);return y?.sitemapId!==d||y.by!==c.by?i(`its sitemap link changed while it was read (sitemap '${d}' by ${c.by}, then ${y?`'${y.sitemapId}' by ${y.by}`:"none"}).`):{sitemapId:d,uniquename:s,sitemapXml:g,...l,sitemapEtag:f}}async function rQ(e,t,n){let r=(0,De.normalizeGuid)(t,"id"),i=await NR(e,r);await n?.(i.sitemapXml),await TR(e,r,i)}Yt.deleteAppResolvingOnce=rQ;async function iQ(e,t){let n=await _R(e,t);if(n.kind!=="deleted")throw n.error}function xw(e,t){try{return(0,ce.ensureSuccess)(e,t),{kind:"deleted"}}catch(n){return IR(e.status)?{kind:"refused",error:n}:{kind:"unknown",error:n}}}function oQ(e,t){var n;if(e.status!==400&&(e.status<200||e.status>=300))return!1;let r=(n=(0,ju.parseChangeSetParts)(e.body,t))===null||n===void 0?void 0:n.filter(i=>i.status<200||i.status>=300);return r!==void 0&&r.length>0&&r.every(i=>i.status===400&&(0,ce.namesAppSearchIndexRace)(i.text))}async function _R(e,t,n={}){let r=`batch_${(0,Pw.newId)()}`,i=`changeset_${(0,Pw.newId)()}`,o=t.map((m,h)=>[`--${i}`,"Content-Type: application/http","Content-Transfer-Encoding: binary",`Content-ID: ${h+1}`,"",`DELETE ${e.apiUrl(m.path)} HTTP/1.1`,...m.etag?[`If-Match: ${m.etag}`]:[],""].join(`\r+`)),a=[`--${r}`,`Content-Type: multipart/mixed;boundary=${i}`,"",...o,`--${i}--`,`--${r}--`,""].join(`\r+`),s=e.apiUrl("/$batch"),u=o.map((m,h)=>String(h+1)),l;try{l=await(0,ce.resendWhile)(m=>oQ(m,u),()=>e.postBatch(a,r),ce.DEADLOCK_BACKOFF_MS)}catch(m){return{kind:"unknown",error:m}}if(n.reportLock){if((0,ju.isChangeSetLockRefusal)(l,u))return{kind:"refused",lock:!0,error:new fe.ConnectionError(s,l.status,`atomic delete of app '${t[0].path}' was refused whole by the customization lock, so it deleted nothing`)};if((0,ce.isConcurrencyLockRefusal)(l)){let m=xw(l,s);return m.kind==="deleted"?m:{...m,lock:!0}}}let c=xw(l,s);if(c.kind!=="deleted")return c;let d=`app '${t[0].path}'`;if(typeof l.body!="string"||l.body.length===0)return{kind:"unknown",error:new fe.ConnectionError(s,l.status,`atomic delete of ${d} cannot be confirmed: the $batch response had no readable body, so the change set's outcome is unknown`)};let f=(0,ju.parseChangeSetStatuses)(l.body,u);if(f===void 0)return{kind:"unknown",error:new fe.ConnectionError(s,l.status,`atomic delete of ${d} cannot be confirmed: the $batch response could not be parsed as a change set, so the outcome is unknown`)};let p=f.find(m=>m<200||m>=300);return p!==void 0?{kind:"refused",error:new fe.ConnectionError(s,p,`atomic delete of ${d} was rolled back: the change set reported HTTP ${p}`)}:f.length!==o.length?{kind:"unknown",error:new fe.ConnectionError(s,l.status,`atomic delete of ${d} cannot be confirmed: the $batch response reported ${f.length} operation result(s), expected exactly ${o.length}`)}:{kind:"deleted"}}async function Qh(e,t){try{let n=await e.get(`/sitemaps(${t})?$select=sitemapid`);return n.status<200||n.status>=300?null:(0,ce.readEtag)(n)}catch{return null}}async function fR(e,t){let n=`/appmodules(${t})?$select=appmoduleid`,r=await e.get(n);if(r.status!==404)return(0,ce.ensureSuccess)(r,e.apiUrl(n)),(0,ce.readEtag)(r)}function Xh(e){return{sitemapxml:e.sitemapxml,...e.sitemapname!==void 0?{sitemapname:e.sitemapname}:{}}}async function Hh(e,t,n,r){if(!r)return null;let i=await Qh(e,t);if(!i)return null;try{let o=await e.get(Zh(t,"sitemapid,sitemapname,sitemapnameunique,sitemapxml"));if(o.status<200||o.status>=300)return null;let a=qf(o);return!a||!Gf(a.sitemapid,t)||a.sitemapnameunique!==r||a.sitemapxml!==n.sitemapxml||n.sitemapname!==void 0&&a.sitemapname!==n.sitemapname?null:i}catch{return null}}function IR(e){return e>=400&&e<500&&e!==408&&e!==429}function pR(e,t,n){if(!e)throw new fe.SdkError("APP_SITEMAP_UNRESOLVED",`Refusing to delete app '${t}': the ${n} 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 TR(e,t,n){let r=`/appmodules(${t})`,i=n.draft?void 0:pR(n.appEtag,t,"app");if(!n.sitemapId){if(n.draft){(0,ce.ensureSuccess)(await(0,ce.resendAppSearchIndexRace)(()=>e.delete(r)),e.apiUrl(r));return}await aQ(e,r,i);return}if(!e.supportsAtomicBatch)throw new fe.SdkError("APP_DELETE_NOT_ATOMIC",`Refusing to delete app '${t}': it owns a sitemap, and the injected HttpClient cannot send a raw body, so the two rows would have to be deleted as separate requests. A failure between them strands the sitemap and permanently reserves the app's unique name. Implement HttpClient.postRaw so the SDK can delete them atomically.`);await iQ(e,[{path:r,etag:i},{path:`/sitemaps(${n.sitemapId})`,etag:pR(n.sitemapEtag,t,"sitemap")}])}async function aQ(e,t,n){(0,ce.ensureSuccess)(await(0,ce.resendAppSearchIndexRace)(()=>e.delete(t,{headers:{"If-Match":n}})),e.apiUrl(t))}Yt.SITEMAP_TARGET_NOT_FOUND_CODE="SITEMAP_TARGET_NOT_FOUND";async function mR(e,t,n){if(!/GenPageId/i.test(t))return;let r;try{r=[...new Set((0,_Y.collectGenPageIds)(t))]}catch(o){throw new fe.SdkError("SITEMAP_TARGET_UNVERIFIABLE",`Refusing to push the app: its sitemap xml could not be parsed, so the generative pages it navigates to cannot be verified (${Gn(o)}).`)}if(r.length===0)return;let i=await(0,iR.findMissingGenPages)(e,r,"sitemap generative-page preflight");if((0,iR.observeGenPageTargets)(n,r,i),i.length>0)throw new fe.SdkError(Yt.SITEMAP_TARGET_NOT_FOUND_CODE,`Refusing to push the app: its sitemap navigates to generative page(s) ${i.map(o=>`'${o}'`).join(", ")} that do not exist in this environment. Push the page before the app that links to it.`)}function sQ(e){var t,n;if(e.status!==400)return!1;let r=e.body;return String((n=(t=r?.error)===null||t===void 0?void 0:t.message)!==null&&n!==void 0?n:"").includes("retrieval of version numbers failed")}function OR(e){return new fe.SdkError("APP_DRAFT_HEADER_NOT_WRITABLE",`Refusing to update app '${e}': 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.`)}async function uQ(e,t,n){var r;await(0,ea.observeIfMatch)(e,t,{entitySet:"sitemaps",idColumn:"sitemapid",id:n.sitemapId,componentName:"SiteMap",held:n.sitemapToken});let i=await(0,ea.readRowToken)(e,{entitySet:"appmodules",idColumn:"appmoduleid",id:n.appId});if(n.writesHeader){let o={guard:"ifMatch",componentName:"AppModule",componentId:n.appId,held:n.appToken};if(i.kind==="notFound"&&n.headerRead)throw OR(n.appId);i.kind==="token"?t.observe({...o,server:i.token,status:(0,ea.compareTokens)(n.appToken,i.token)}):t.observe({...o,status:"readFailed",detail:i.kind==="failed"?i.detail:"HTTP 404, and the unpublished header was unreadable"})}else i.kind==="token"&&i.token!==null&&n.appToken!==i.token&&t.warn("PREVIEW_SIBLING_MOVED",`App '${n.appId}': its appmodule header changed on the server since it was read (held ${(r=n.appToken)!==null&&r!==void 0?r:"(none)"}, server ${i.token}), but this push writes no header field \u2014 every header value it supplies equals the server's \u2014 so it is not a conflict for this push. Re-fetch to see the change.`);return n.pinMayGuard&&t.warn("PREVIEW_APP_PIN_GUARD_NOT_EVALUATED",`App '${n.appId}': after the primary save, this push may use a guarded component pin that also writes the app row. That later gate, its token echo and fallback are not evaluated by this preview.`),t.reached({effects:[...n.writesHeader?[{componentName:"AppModule",componentId:n.appId,identity:"known",operation:"update"}]:[],{componentName:"SiteMap",componentId:n.sitemapId,identity:"known",operation:"update"}],attemptsWrite:!0})}function lQ(e,t){var n;let r=[["name",e.appModuleName],["description",e.appModuleDescription],["aiappdescription",e.appModuleAiDescription]],i={};for(let[o,a]of r)a!==void 0&&(t!==void 0&&String((n=t[o])!==null&&n!==void 0?n:"")===String(a??"")||(i[o]=a));return i}async function hR(e,t,n){var r;let i=(0,De.normalizeGuid)(t,"id"),o=n==="tokens-first",a=o?await fR(e,i):null,s=Rw(zh,i),u=(0,ce.ensureSuccess)(await e.get(s),e.apiUrl(s)),l=(r=qf(u))!==null&&r!==void 0?r:{};if(!l.appmoduleid)throw new fe.SdkError("APP_NOT_FOUND",`App '${i}' was not found (checked the unpublished-aware projection, which includes drafts).`);let c=await Bf(e,i,l.uniquename,"fetch"),d=c?.sitemapId,f=null;if(c&&d){o&&(f=await Qh(e,d));let m=Zh(d,"sitemapid,sitemapname,sitemapnameunique,sitemapxml"),h=(0,ce.ensureSuccess)(await e.get(m),e.apiUrl(m)),g=qf(h),y=E=>{throw new fe.SdkError("APP_SITEMAP_UNRESOLVED",`Refusing to fetch app '${i}': its sitemap '${d}' was located by its ${c.by==="component"?"SiteMap component":"unique name"}, but ${E}, 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 y("the by-id read returned no row");if(c.by==="name"&&g.sitemapnameunique!==l.uniquename)throw new fe.SdkError("APP_SITEMAP_UNRESOLVED",`Refusing to fetch app '${i}': sitemap '${d}' now carries sitemapnameunique '${String(g.sitemapnameunique)}', not '${String(l.uniquename)}', so it is no longer this app's sitemap. Retry.`);if(!Gf(g.sitemapid,d))return y(`the by-id read returned a row carrying sitemapid '${String(g.sitemapid)}'`);if(typeof g.sitemapxml!="string")return y("the by-id read returned no sitemapxml");let b=await Bf(e,i,l.uniquename,"fetch");if(b?.sitemapId!==d||b.by!==c.by)throw new fe.SdkError("APP_SITEMAP_UNRESOLVED",`Refusing to fetch app '${i}': its sitemap link changed while it was read (sitemap '${d}' by ${c.by}, then ${b?`'${b.sitemapId}' by ${b.by}`:"none"}). Nothing was saved. Retry.`);l.$sitemap=g,o||(f=await Qh(e,d))}o||(a=await fR(e,i));let p=a??DY(l);return{raw:l,etag:f,...l.appmoduleid?{siblingEtags:{[(0,De.normalizeGuid)(l.appmoduleid,"appmoduleid")]:p}}:{}}}Yt.appApi={get(e,t){return hR(e,t,"tokens-first")},readContentThenToken(e,t){return hR(e,t,"content-first")},async list(e,t){let n=Rw(zh);return(await(0,kr.collectPages)(e,n,"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,n,r=void 0){let i=t;if(typeof i.appModuleName!="string"||i.appModuleName.trim()==="")throw new fe.ValidationError("app",i.appModuleId,[{pointer:"/name",rule:"app-name-required",message:"an app needs a name to be created, and its 'name' is missing or blank \u2014 set it (updateElement('app', id, '/name', \u2026), or addElement when the key was removed) and push again. Nothing was written."}]);await mR(e,i.sitemapxml,r);let o=await dR(e,i,i.appModuleId),a=i.iconWebResourceId?void 0:await kY(e),s=i.iconWebResourceId||a?.id;if(!s)throw new fe.SdkError("APP_ICON_UNRESOLVED",`Cannot create app '${i.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 u=null;a?.managed&&(u=`No unmanaged image web resource was available, so the app icon resolved to a MANAGED one (${a.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=i.appModuleUniqueName||PY(i.appModuleId),c={name:i.appModuleName,uniquename:l,clienttype:4,formfactor:1,navigationtype:0};i.appModuleDescription&&(c.description=i.appModuleDescription),i.appModuleAiDescription&&(c.aiappdescription=i.appModuleAiDescription),s&&(c.webresourceid=s);let d="/appmodules";if(r){let T=n?(0,De.normalizeGuid)(n,"appmoduleid"):void 0,O=i.sitemapId?(0,De.normalizeGuid)(i.sitemapId,"sitemapId"):void 0;return r.reached({effects:[{componentName:"AppModule",componentId:T,identity:"known",operation:"create"},O?{componentName:"SiteMap",componentId:O,identity:"known",operation:"create"}:{componentName:"SiteMap",identity:"assignedAtWrite",operation:"create"}],attemptsWrite:!0},T?()=>(0,ea.existsByKey)(e,r,{collection:"/appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()",key:"appmoduleid",id:T,componentName:"AppModule"}):void 0)}let f=(0,ce.ensureSuccess)(await(0,ce.resendDeadlockVictim)(()=>e.post(d,(0,ce.withClientMintedId)(c,"appmoduleid",n))),e.apiUrl(d)),p=(0,ce.resolveCreatedId)(f,"appmoduleid","app module",n),m=null,h=null,g=[];u&&g.push(u);let y={kind:"notRequested"},b=i.sitemapId?(0,De.normalizeGuid)(i.sitemapId,"sitemapId"):(0,Pw.newId)(),E=!1,w,_=Xh(i);try{let T="/sitemaps",O=(0,ce.echoWrite)("sitemapid"),v=await e.post(`${T}${O.query}`,{sitemapid:b,sitemapnameunique:l,..._},O.options);E=IR(v.status);let N=(0,ce.ensureSuccess)(v,e.apiUrl(T));h=(0,ce.readEtag)(N),m=h??await Hh(e,b,_,l);let S=await uR(e,i,o);g.push(...S.warnings);let R=S.components;R.unshift({"@odata.type":"Microsoft.Dynamics.CRM.sitemap",sitemapid:b}),await SR(e,p,R);let x=xs(e,p);if(await Mw(e,p,S.tables,x),o){let U=await qY(e,p,o,x);w={mode:"create",tables:eg(U),published:"notRead"}}let G=await $Y(e,p);G&&g.push(G),i.appSettings&&Object.keys(i.appSettings).length>0&&g.push(...await(0,IY.applyAppSettings)(e,p,i.appSettings)),i.published!==!1&&(await(0,Fw.publishAppModule)(e,p),y={kind:"submitted"})}catch(T){let O=await ZY(e,p,{sitemapId:b,sitemapNameUnique:l,serverRefusedSitemap:E,sitemapWriteToken:h});throw(0,TY.failedAfterPrimaryWrite)(eQ(T,O,{appId:p,sitemapId:b,uniqueName:l}))}let I=null;if(y.kind==="submitted")try{let T=await e.get(`/appmodules(${p})?$select=appmoduleid`);T.status>=200&&T.status<300&&(I=(0,ce.readEtag)(T))}catch{}return qw(e,p),{id:p,etag:m,serverIdentity:{sitemapId:b},siblingEtags:{[p]:I},publish:y,...g.length>0?{warnings:g}:{},...w?{appMainForms:w}:{}}},async update(e,t,n,r,i,o,a=void 0){var s,u,l,c,d,f;let p=n,m=(0,De.normalizeGuid)(t,"id");if(await mR(e,p.sitemapxml,a),!p.sitemapId)throw new fe.ValidationError("app",m,[{pointer:"/sitemapId",rule:"app-sitemap-identity-missing",message:`missing sitemap identity \u2014 re-fetch the app before pushing edits: fetchArtifact('app', '${m}', { 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', '${m}'), clear the local copy with deleteArtifact('app', '${m}'), then author the app again and push.`}]);let h=(0,De.normalizeGuid)(p.sitemapId,"sitemapId");if(!(0,ce.isVersionToken)(r))throw a?.observe({guard:"ifMatch",componentName:"SiteMap",componentId:h,held:r,status:"missingHeld"}),new fe.SdkError("APP_UPDATE_NO_ETAG",`Refusing to push app '${m}': ${r?`the concurrency token held for its sitemap row ('${r}') 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 g=await dR(e,p,m),y=await uR(e,p,g),b=p.components.mainFormsOnUpdate==="exact"&&g!==void 0,E=`/appmodules(${m})`,w=(s=o?.[m])!==null&&s!==void 0?s:null,_,I,T;try{let xe=Rw(b?`${zh},ismanaged`:zh,m),Et=await e.get(xe),zt=(u=Et.body)===null||u===void 0?void 0:u.value;if(b&&Et.status>=200&&Et.status<300&&(!Array.isArray(zt)||zt.length!==1||!Gf((l=zt[0])===null||l===void 0?void 0:l.appmoduleid,m)))I=Array.isArray(zt)?zt.length===1?"the header read returned one row that is not identified as this app, not exactly one row of this app":`the header read returned ${zt.length} rows, not exactly one row of this app`:"the header read returned no row collection, not exactly one row of this app";else if(Et.status>=200&&Et.status<300){let Ht=qf(Et);if(typeof Ht=="object"&&Ht!==null&&!Array.isArray(Ht)){_=Ht;let W=_.uniquename;T=typeof W=="string"&&W?W:void 0}}}catch{}let O=lQ(p,_),v=await Bf(e,m,T||p.appModuleUniqueName,"push");if(v?.sitemapId!==h)throw new fe.SdkError("APP_SITEMAP_UNRESOLVED",`Refusing to push app '${m}': ${v?`its sitemap is now '${v.sitemapId}'`:"it has no sitemap now"}, not '${h}', the one this copy holds \u2014 the app's sitemap is no longer the one this copy was fetched with. Nothing was modified. Re-fetch the app (fetchArtifact('app', '${m}', { overwrite: true })) and re-apply the change.`);if(b)return jY({client:e,appId:m,body:p,sitemapId:h,sitemapToken:r,appToken:w,headerWrite:O,currentHeader:_,headerProblem:I,plan:y,sets:g,expectedUniqueName:p.sitemapNameUnique||T||p.appModuleUniqueName||void 0,preview:a});let N=w,S=Object.keys(O).length>0;if(S&&!(0,ce.isVersionToken)(w))throw new fe.SdkError("APP_UPDATE_NO_ETAG",`Refusing to push app '${m}': ${w?`the concurrency token held for its appmodule header ('${w}') 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', '${m}', { overwrite: true })) and re-apply the change.`);if(a)return uQ(e,a,{appId:m,sitemapId:h,sitemapToken:r,appToken:w,writesHeader:S,headerRead:_!==void 0,pinMayGuard:p.published!==!0&&y.components.length>0&&e.supportsAtomicBatch&&(0,ce.isVersionToken)(w)});if(S&&(0,ce.isVersionToken)(w)){let xe=(0,ce.echoWrite)("appmoduleid",{"If-Match":w}),Et=await e.patch(`${E}${xe.query}`,O,xe.options);if(sQ(Et))throw OR(m);(0,ce.ensureSuccess)(Et,e.apiUrl(E)),N=(0,ce.readEtag)(Et)}let R=Xh(p),x=p.sitemapNameUnique||T||p.appModuleUniqueName||void 0,G=(0,ce.echoWrite)("sitemapid",{"If-Match":r}),U=`/sitemaps(${h})`,M;try{M=(0,ce.ensureSuccess)(await e.patch(`${U}${G.query}`,{...R},G.options),e.apiUrl(U))}catch(xe){throw(0,fe.withPartialTokens)(xe,{siblingEtags:{[m]:N}})}let q=[...y.warnings],X=await XY(e,m,y,p.published!==!0&&y.components.length>0&&e.supportsAtomicBatch&&(0,ce.isVersionToken)(N)?N:void 0);N=(c=X.appToken)!==null&&c!==void 0?c:N,q.push(...X.warnings);let ye=xs(e,m);try{if(X.error!==void 0)throw X.error;await Mw(e,m,y.tables,ye)}catch(xe){q.push(`App '${m}': one or more components were not pinned (${xe.message}). Navigation may reference content not included in the app; re-push to retry.`)}let Ve;if(g){let xe=await BY(e,m,g,ye);q.push(...xe.warnings),Ve={mode:"addOnly",tables:xe.tables,published:"notRead"}}let _e={kind:"notRequested"},wt=N,Fn=(d=(0,ce.readEtag)(M))!==null&&d!==void 0?d:await Hh(e,h,R,x);if(p.published===!0){try{await CR(e,m),_e={kind:"submitted"}}catch(xe){_e={kind:"failed",error:xe},q.push(`App '${m}': saved, but publishing failed (${xe.message}). The app remains unpublished; re-push to retry.`)}if(_e.kind==="submitted"){wt=null;try{let xe=await e.get(`/appmodules(${m})?$select=appmoduleid`);xe.status>=200&&xe.status<300&&(wt=(0,ce.readEtag)(xe)),Fn=(f=await Hh(e,h,R,x))!==null&&f!==void 0?f:Fn}catch{}}}return{id:m,etag:Fn,siblingEtags:{[m]:wt},publish:_e,...q.length>0?{warnings:q}:{},...Ve?{appMainForms:Ve}:{}}},planPush(e,t,n){return(0,ea.planPushThrough)(Yt.appApi,e,t,n)},async delete(e,t){let n=(0,De.normalizeGuid)(t,"id");await TR(e,n,await NR(e,n))}}});var Us=C(ni=>{"use strict";Object.defineProperty(ni,"__esModule",{value:!0});ni.rebuildRaw=ni.assembleChildren=ni.spliceChildren=ni.mergeAttrs=ni.rawFromNode=ni.emptyBag=void 0;var Fs=Y(),DR=1e6,rg=512;function cQ(){return{a:[],c:[]}}ni.emptyBag=cQ;function PR(e,t=0){if(t>rg)throw new Fs.InvalidArgumentError(`Artifact node tree exceeds the maximum depth of ${rg}`);return{n:e.getNodeName(),a:e.getAllProperties().map(n=>[n.key,n.value]),c:e.getAllChildren().map(n=>PR(n,t+1))}}ni.rawFromNode=PR;function dQ(e,t,n=[]){let r=new Map;for(let[s,u]of t)r.set(s,u);let i=new Set(n.filter(s=>!r.has(s))),o=new Set,a=[];for(let[s,u]of e)i.has(s)||(r.has(s)?a.push([s,r.get(s)]):a.push([s,u]),o.add(s));for(let[s,u]of t)o.has(s)||(a.push([s,u]),o.add(s));return a}ni.mergeAttrs=dQ;function ng(e,t){let n=new Set;for(let s of e){let u=s.i;if(!Number.isInteger(u)||u<0||u>DR)throw new Fs.InvalidArgumentError(`Bag child index must be an integer in [0, ${DR}] (got ${String(u)})`);if(n.has(u))throw new Fs.InvalidArgumentError(`Duplicate bag child index ${u}`);n.add(u)}let r=[...e].sort((s,u)=>s.i-u.i),i=[],o=0,a=0;for(let s of r){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}ni.spliceChildren=ng;function fQ(e,t){if(e.w){let n={n:e.w.n,a:e.w.a.map(r=>[r[0],r[1]]),c:ng(e.w.c,t)};return ng(e.c,[n])}return ng(e.c,t)}ni.assembleChildren=fQ;function RR(e,t,n,r=0){if(r>rg)throw new Fs.InvalidArgumentError(`Artifact node tree exceeds the maximum depth of ${rg}`);pQ(e,r);let i=t.make(e.n,n);for(let[o,a]of e.a)t.setProp(i,o,a);for(let o of e.c)t.addChild(i,RR(o,t,i,r+1));return i}ni.rebuildRaw=RR;function pQ(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Fs.InvalidArgumentError(`Malformed hybrid node at depth ${t}: expected a JSON object`);let n=e;if(typeof n.n!="string")throw new Fs.InvalidArgumentError(`Malformed hybrid node at depth ${t}: 'n' (tag name) must be a string`);if(!Array.isArray(n.a)||!Array.isArray(n.c))throw new Fs.InvalidArgumentError(`Malformed hybrid node '${n.n}': 'a' and 'c' must be arrays`);for(let r of n.a)if(!Array.isArray(r)||r.length!==2||typeof r[0]!="string"||typeof r[1]!="string")throw new Fs.InvalidArgumentError(`Malformed hybrid node '${n.n}': each attribute must be a [string, string] pair`)}});var Ga=C(ig=>{"use strict";Object.defineProperty(ig,"__esModule",{value:!0});ig.installDomShim=void 0;var kR=Ms(),$R=!1,mQ={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 hQ(){if($R)return;let e=globalThis;typeof e.DOMParser>"u"&&(e.DOMParser=kR.DOMParser),typeof e.XMLSerializer>"u"&&(e.XMLSerializer=kR.XMLSerializer),typeof e.Node>"u"&&(e.Node=mQ),$R=!0}ig.installDomShim=hQ});var ja=C(on=>{"use strict";Object.defineProperty(on,"__esModule",{value:!0});on.projectElementBag=on.serializeNode=on.domEngine=on.nodeLikeFromDom=on.parseXmlRoot=on.EMPTY_FORM_SENTINEL=on.TEXT_SENTINEL=void 0;var gQ=Us(),Ec=Y(),yQ=Ga();on.TEXT_SENTINEL="#text";on.EMPTY_FORM_SENTINEL="#empty";var ag=new WeakSet;function bQ(e,t){(0,yQ.installDomShim)();let n=e&&e.trim()!==""?e:t,r=new DOMParser().parseFromString(n,"text/xml"),i=r.documentElement;if(!i)throw new Ec.InvalidArgumentError("XML source has no root element (empty or malformed input)");return vQ(n),EQ(r),CQ(i),SQ(i),IQ(i,n),i}on.parseXmlRoot=bQ;function vQ(e){let t=e.search(/\S/);if(t!==-1&&e[t]!=="<")throw MR(3)}var wQ=["http://www.mozilla.org/newlayout/xml/parsererror.xml","http://www.w3.org/1999/xhtml"];function EQ(e){var t;for(let n of wQ){let r=e.getElementsByTagNameNS(n,"parsererror")[0];if(r){let i=((t=r.textContent)!==null&&t!==void 0?t:"").replace(/\s+/g," ").trim().slice(0,200);throw new Ec.InvalidArgumentError(`XML source is not well-formed (${i||"the XML parser reported an error"}), so it cannot be round-tripped`)}}}var AQ=new Set([1,3]);function CQ(e){let t=[e];for(;t.length>0;){let r=t.pop().childNodes;for(let i=0;i<r.length;i+=1){let o=r[i];if(!AQ.has(o.nodeType))throw new Ec.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 SQ(e){var t,n;let r=(t=e.ownerDocument)!==null&&t!==void 0?t:e.parentNode;if(!r)return;let i=r.childNodes;for(let o=0;o<i.length;o+=1){let a=i[o];if(a!==e&&!(a.nodeType===3&&((n=a.nodeValue)!==null&&n!==void 0?n:"").trim()===""))throw MR(a.nodeType)}}function MR(e){return new Ec.InvalidArgumentError(`Unsupported document-level XML node (type ${e}: declaration / comment / processing-instruction outside the root element) cannot be round-tripped`)}function NQ(e){let t=[],n=/<([^>]*)>/g;for(let r=n.exec(e);r!==null;r=n.exec(e)){let i=r[1];i.startsWith("/")||i.startsWith("?")||i.startsWith("!")||t.push(i.endsWith("/"))}return t}function _Q(e){let t=[],n=[e];for(;n.length>0;){let r=n.pop();t.push(r);let i=r.childNodes;for(let o=i.length-1;o>=0;o-=1){let a=i[o];a.nodeType===1&&n.push(a)}}return t}function xR(e){let t=e.childNodes;for(let n=0;n<t.length;n+=1){let r=t[n].nodeType;if(r===1||r===3)return!0}return!1}function IQ(e,t){let n=NQ(t),r=_Q(e),i=Math.min(n.length,r.length);for(let o=0;o<i;o+=1){if(n[o])continue;let a=r[o];xR(a)||ag.add(a)}}function Gw(e){let t=e.nodeType===3;return{getNodeName:()=>t?on.TEXT_SENTINEL:e.tagName,getAllProperties:()=>{var n;if(t)return[{key:on.TEXT_SENTINEL,value:(n=e.nodeValue)!==null&&n!==void 0?n:""}];let r=e.attributes,i=[];for(let o=0;o<r.length;o+=1)i.push({key:r[o].name,value:r[o].value});return ag.has(e)&&!xR(e)&&i.push({key:on.EMPTY_FORM_SENTINEL,value:"1"}),i},getAllChildren:()=>{if(t)return[];let n=[],r=e.childNodes;for(let i=0;i<r.length;i+=1){let o=r[i];(o.nodeType===1||o.nodeType===3)&&n.push(Gw(o))}return n}}}on.nodeLikeFromDom=Gw;function TQ(e){return{make:t=>t===on.TEXT_SENTINEL?e.createTextNode(""):e.createElement(t),setProp:(t,n,r)=>{t.nodeType===3?t.nodeValue=r:n===on.EMPTY_FORM_SENTINEL?ag.add(t):t.setAttribute(n,r)},addChild:(t,n)=>{t.appendChild(n)}}}on.domEngine=TQ;function FR(e){for(let t=0;t<e.length;t+=1){let n=e.charCodeAt(t);if(n<=31&&n!==9&&n!==10&&n!==13||n===65534||n===65535)throw og(n);if(n>=55296&&n<=56319){let r=e.charCodeAt(t+1);if(!(r>=56320&&r<=57343))throw og(n);t+=1;continue}if(n>=56320&&n<=57343)throw og(n)}}function og(e){let t=e.toString(16).toUpperCase().padStart(4,"0");return new Ec.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 OQ(e){return FR(e),String(e).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/\r/g,"
").replace(/\n/g,"
").replace(/\t/g,"	")}function DQ(e){return FR(e),String(e).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}function PQ(e){return UR(e,0)}on.serializeNode=PQ;var LR=512;function UR(e,t){var n;if(t>LR)throw new Ec.InvalidArgumentError(`XML nesting exceeds the maximum supported depth of ${LR}`);if(e.nodeType===3)return DQ((n=e.nodeValue)!==null&&n!==void 0?n:"");let r=e,i="<"+r.tagName,o=r.attributes;for(let u=0;u<o.length;u+=1)i+=" "+o[u].name+'="'+OQ(o[u].value)+'"';let a=[],s=r.childNodes;for(let u=0;u<s.length;u+=1){let l=s[u];(l.nodeType===1||l.nodeType===3)&&a.push(l)}if(a.length===0)return ag.has(r)?i+"></"+r.tagName+">":i+" />";i+=">";for(let u of a)i+=UR(u,t+1);return i+"</"+r.tagName+">"}function RQ(e){let t=Gw(e);return{a:t.getAllProperties().map(n=>[n.key,n.value]),c:t.getAllChildren().map((n,r)=>({i:r,node:(0,gQ.rawFromNode)(n)}))}}on.projectElementBag=RQ});var Vi=C(hr=>{"use strict";Object.defineProperty(hr,"__esModule",{value:!0});hr.rejectUnknownKeys=hr.childObjects=hr.optionalGuidId=hr.optionalEnum=hr.eachObject=hr.issue=hr.isJsonObject=void 0;function qR(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}hr.isJsonObject=qR;function Ac(e,t,n,r){return r?{pointer:e,rule:t,message:n,fatal:r}:{pointer:e,rule:t,message:n}}hr.issue=Ac;function BR(e,t,n,r){if(!Array.isArray(e))return[];let i=[];return e.forEach((o,a)=>{qR(o)?i.push({node:o,index:a}):r.push(Ac(`${t}/${a}`,`${n}-must-be-object`,`a ${n} must be a JSON object, got ${o===null?"null":typeof o}`))}),i}hr.eachObject=BR;function kQ(e,t,n,r,i,o){let a=e[t];a!==void 0&&(typeof a!="string"||!n.includes(a))&&o.push(Ac(`${r}/${t}`,i,`${t} must be one of ${n.map(s=>`'${s}'`).join(", ")}, got ${JSON.stringify(a)}`))}hr.optionalEnum=kQ;var $Q=/^(?:\{[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 LQ(e,t,n,r,i){let o=e[t];typeof o=="string"&&o!==""&&!$Q.test(o)&&i.push(Ac(`${n}/${t}`,r,`${t} must be a GUID or empty, got '${o}'`))}hr.optionalGuidId=LQ;function MQ(e,t,n,r,i){let o=e[t],a=`${n}/${t}`;return o===void 0?[]:Array.isArray(o)?BR(o,a,r,i):(i.push(Ac(a,`${r}-list-must-be-array`,`${t} must be an array when present, got ${typeof o}`)),[])}hr.childObjects=MQ;function xQ(e,t,n,r,i,o={}){var a,s;for(let u of Object.keys(e)){if(t.has(u))continue;let l=(a=o.elsewhere)===null||a===void 0?void 0:a[u],c=(s=o.unsupported)===null||s===void 0?void 0:s[u],d=l?` '${u}' is a ${l} key \u2014 set it on the ${l} instead.`:c?` ${c}`:` Put values the typed layer does not model in '${r}.bag', which round-trips them verbatim.`;i.push(Ac(`${n}/${u}`,`${r}-unknown-key`,`'${u}' is not a ${r} property, and would be SILENTLY DROPPED at serialization.${d}`))}}hr.rejectUnknownKeys=xQ});var dg=C(J=>{"use strict";Object.defineProperty(J,"__esModule",{value:!0});J.genPageEmbedIssues=J.setUniqueId=J.mintEmbedIdentity=J.authoredUniqueId=J.hasGenPage=J.applyEmbedCellDefaults=J.applyEmbedControlDefaults=J.mayCommitEmbedState=J.commitEmbedState=J.reconcileEmbedDescriptions=J.embedAppendIndex=J.activeEmbedBindings=J.projectGenPageEmbeds=J.isRecognizedEmbed=J.isUnbound=J.effectiveClassId=J.effectiveFormType=J.inputDataFrom=J.classifyBinding=J.isStaticParameter=J.entryParameter=J.pageEntries=J.descriptionFor=J.descriptionsRegion=J.controlUniqueIds=J.controlUniqueId=J.typedCellSites=J.typedCells=J.rawText=J.rawAttr=J.normGuid=J.GENPAGE_FORM_FACTORS=J.GENPAGE_EMBED_ROWSPAN=J.GENPAGE_CONTROL_NAME=J.CUSTOM_CONTROL_CLASS_ID=void 0;var FQ=Ms(),UQ=ec(),jw=ft(),Gi=Vi();J.CUSTOM_CONTROL_CLASS_ID="F9A8A302-114E-466A-B582-6771B2AE0D92";J.GENPAGE_CONTROL_NAME="MscrmControls.UxAgentControl";J.GENPAGE_EMBED_ROWSPAN=6;J.GENPAGE_FORM_FACTORS=["2","0","1"];var qQ=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function ri(e){if(typeof e!="string")return"";let t=e.trim().toLowerCase();return t.startsWith("{")&&t.endsWith("}")&&(t=t.slice(1,-1)),qQ.test(t)?t:""}J.normGuid=ri;function qs(e,t){let n=et(e?.a).find(r=>Array.isArray(r)&&r[0]===t);return n?n[1]:void 0}J.rawAttr=qs;function Wf(e){return et(e?.c).filter(t=>typeof t?.n=="string"&&t.n.startsWith("<")).map(t=>t.n.slice(1)).join("")}J.rawText=Wf;function et(e){return Array.isArray(e)?e:[]}function Yw(e,t){let n=et(e?.a).find(r=>Array.isArray(r)&&r[0]===t);return n?n[1]:void 0}function jR(e){return typeof e=="string"?e.trim().replace(/^\{|\}$/g,"").toUpperCase():""}function WR(e){return go(e).map(t=>t.cell)}J.typedCells=WR;function go(e){let t=[];return et(e?.tabs).forEach((n,r)=>{et(pt(n)?n.columns:void 0).forEach((i,o)=>{et(pt(i)?i.sections:void 0).forEach((a,s)=>{et(pt(a)?a.rows:void 0).forEach((u,l)=>{et(pt(u)?u.cells:void 0).forEach((c,d)=>{pt(c)&&t.push({cell:c,pointer:`/tabs/${r}/columns/${o}/sections/${s}/rows/${l}/cells/${d}`})})})})})}),t}J.typedCellSites=go;function Wa(e){return pt(e)?ri(Yw(e.bag,"uniqueid")):""}J.controlUniqueId=Wa;function BQ(e){let t=new Set;for(let{cell:n}of go(e)){let r=Ku(n.control)?Wa(n.control):"";r&&t.add(r)}return t}function VQ(e){let t=new Map;for(let{cell:n}of go(e)){let r=pt(n.control)?Wa(n.control):"";r&&!t.has(r)&&t.set(r,n.control)}return t}function GQ(e){return e!==void 0&&e.genPage===void 0&&(Zw(e)!==J.CUSTOM_CONTROL_CLASS_ID||!cg(e))}function Ww(e,t){if(pt(e)){t(e);for(let n of et(e.c))Ww(n,t)}}function zu(e,t){var n;if(pt(e)){for(let r of et(e.c))Ww(r?.node,t);for(let r of et((n=e.w)===null||n===void 0?void 0:n.c))Ww(r?.node,t)}}function ug(e){let t=new Map,n=i=>{var o;i&&t.set(i,((o=t.get(i))!==null&&o!==void 0?o:0)+1)},r=i=>{i.n==="control"&&n(ri(qs(i,"uniqueid")))};return zu(e?.bag,r),et(e?.tabs).forEach(i=>{pt(i)&&(zu(i.bag,r),et(i.columns).forEach(o=>{pt(o)&&(zu(o.bag,r),et(o.sections).forEach(a=>{pt(a)&&(zu(a.bag,r),et(a.rows).forEach(s=>{pt(s)&&(zu(s.bag,r),et(s.cells).forEach(u=>{pt(u)&&(zu(u.bag,r),pt(u.control)&&(n(Wa(u.control)),zu(u.control.bag,r)))}))}))}))}))}),t}J.controlUniqueIds=ug;function Cc(e){return et(e?.c).find(t=>{var n;return((n=t?.node)===null||n===void 0?void 0:n.n)==="controlDescriptions"})}J.descriptionsRegion=Cc;function Hu(e,t){var n;let r=ri(t);if(r)return et((n=Cc(e))===null||n===void 0?void 0:n.node.c).find(i=>i?.n==="controlDescription"&&ri(qs(i,"forControl"))===r)}J.descriptionFor=Hu;function zf(e){return et(e.c).filter(zR)}J.pageEntries=zf;function zR(e){return e?.n==="customControl"&&qs(e,"name")===J.GENPAGE_CONTROL_NAME}function zw(e,t){let n=et(e.c).find(r=>r?.n==="parameters");return et(n?.c).find(r=>r?.n===t)}J.entryParameter=zw;function Hw(e){return qs(e,"static")==="true"}J.isStaticParameter=Hw;function Hf(e){let t=zf(e);if(t.length===0)return{kind:"none"};let n,r;for(let i=0;i<t.length;i+=1){let o=zw(t[i],"RefId");if(!o||!Hw(o))return{kind:"unsupported"};let a=ri(Wf(o));if(!a)return{kind:"unsupported"};let s=zw(t[i],"PageInput");if(s&&!Hw(s))return{kind:"unsupported"};let u=s?Wf(s):void 0;if(i===0)n=a,r=u;else if(a!==n||u!==r)return{kind:"unsupported"}}return r===void 0?{kind:"projectable",pageId:n}:{kind:"projectable",pageId:n,pageInputRaw:r}}J.classifyBinding=Hf;function pt(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Qw(e){if(e===void 0)return;let t;try{t=JSON.parse(e)}catch{return}return pt(t)&&pt(t.data)?t.data:void 0}J.inputDataFrom=Qw;function Xw(e){var t;return(t=e.formType)!==null&&t!==void 0?t:"Main"}J.effectiveFormType=Xw;function Zw(e){return jR(e.classId!==void 0?e.classId:Yw(e.bag,"classid"))}J.effectiveClassId=Zw;function cg(e){return!e.fieldName}J.isUnbound=cg;function eE(e,t){if(Xw(e)!=="Main"||!cg(t)||Zw(t)!==J.CUSTOM_CONTROL_CLASS_ID)return!1;let n=Wa(t),r=n?Hu(e.bag,n):void 0;return r!==void 0&&Hf(r).kind==="projectable"}J.isRecognizedEmbed=eE;function jQ(e){for(let t of WR(e)){let n=t.control;if(!n||!eE(e,n))continue;let r=Hf(Hu(e.bag,Wa(n)));if(r.kind!=="projectable")continue;let i=Qw(r.pageInputRaw);n.genPage=i===void 0?{pageId:r.pageId}:{pageId:r.pageId,inputData:i}}}J.projectGenPageEmbeds=jQ;var WQ=new Set(["pageId","inputData"]);function jf(e){let t=[];for(let n=0;n<e.childNodes.length;n+=1){let r=e.childNodes[n];r.nodeType===1&&t.push(r)}return t}function zQ(e){var t;let n=[],r=c=>d=>n.push(`${c}: ${d}`),i=new FQ.DOMParser({errorHandler:{warning:r("warning"),error:r("error"),fatalError:r("fatalError")}}).parseFromString(e,"text/xml"),o=(t=i?.documentElement)!==null&&t!==void 0?t:null;if(!o||n.length>0)throw new Error(`the formxml does not parse cleanly${n.length>0?` (${n[0]})`:""}`);let a=new Set,s=o.getElementsByTagName("control");for(let c=0;c<s.length;c+=1){let d=ri(s[c].getAttribute("uniqueid"));d&&a.add(d)}let u=jf(o).find(c=>c.nodeName==="controlDescriptions"),l=new Map;for(let c of u?jf(u):[]){let d=ri(c.getAttribute("forControl"));if(!(c.nodeName!=="controlDescription"||!d||!a.has(d)))for(let f of jf(c)){if(f.nodeName!=="customControl"||f.getAttribute("name")!==J.GENPAGE_CONTROL_NAME)continue;let p=jf(f).find(g=>g.nodeName==="parameters"),m=p?jf(p).find(g=>g.nodeName==="RefId"):void 0,h=m&&m.getAttribute("static")==="true"?ri(m.textContent):"";h&&l.set(`${d}|${h}`,[d,h])}}return[...l.values()]}J.activeEmbedBindings=zQ;function sg(e){return{n:`<${e}`,a:[],c:[]}}function Kw(e,t){return{n:e,a:[["type","SingleLine.Text"],["static","true"]],c:[sg(t)]}}function Jw(e,t){let n={};if(t!==void 0)try{let r=JSON.parse(t);pt(r)&&(n=r)}catch{}return JSON.stringify({...n,data:e})}function HQ(e,t,n){return{n:"controlDescription",a:[["forControl",e]],c:J.GENPAGE_FORM_FACTORS.map(r=>({n:"customControl",a:[["name",J.GENPAGE_CONTROL_NAME],["formFactor",r]],c:[{n:"parameters",a:[],c:[Kw("RefId",t),...n===void 0?[]:[Kw("PageInput",Jw(n))]]}]}))}}function lg(e,t){if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((n,r)=>lg(n,t[r]));if(pt(e)&&pt(t)){let n=Object.keys(e);return n.length===Object.keys(t).length&&n.every(r=>r in t&&lg(e[r],t[r]))}return e===t}function KQ(e,t,n){let r=et(e.c).find(l=>l?.n==="parameters");if(!r||!Array.isArray(r.c))return;let i=r.c.find(l=>l?.n==="RefId");i&&ri(Wf(i))!==t&&(i.c=[sg(t)]);let o=r.c.findIndex(l=>l?.n==="PageInput"),a=o>=0?r.c[o]:void 0,s=a?Wf(a):void 0;if(lg(Qw(s),n))return;if(n!==void 0){a?a.c=[sg(Jw(n,s))]:r.c.push(Kw("PageInput",Jw(n)));return}let u=JSON.parse(s);delete u.data,Object.keys(u).length===0?r.c.splice(o,1):a.c=[sg(JSON.stringify(u))]}function tE(e){let t=et(e?.c),n=t.reduce((r,i)=>i.i>r?i.i:r,-1);return Math.max(n,t.length)+1}J.embedAppendIndex=tE;function JQ(e,t){var n;let r=e.bag,i=Cc(r);if(i&&t){let o=ug(t),a=ug(e),s=BQ(t),u=VQ(e),l=et(i.node.c),c=[];for(let d of l){let f=d?.n==="controlDescription"&&zf(d).length>0?ri(qs(d,"forControl")):"";if(!f||!o.has(f))c.push(d);else if(a.has(f))if(s.has(f)&&GQ(u.get(f))&&lg(d,Hu(t.bag,f))){let p=et(d.c).filter(m=>!zR(m));p.length>0&&c.push({...d,c:p})}else c.push(d)}(c.length!==l.length||c.some((d,f)=>d!==l[f]))&&(i.node.c=c)}for(let{cell:o}of go(e)){let a=o.control;if(!Ku(a)||!pt(a.genPage))continue;let s=ri(a.genPage.pageId),u=a.genPage.inputData,l=Wa(a);if(!l){if(Kf(a)!==void 0)continue;l=nE(a)}let c=Hu(r,l);if(c){for(let p of zf(c))KQ(p,s,u);continue}i||(i={i:tE(r),node:{n:"controlDescriptions",a:[],c:[]}},r.c.push(i));let d=((n=Yw(a.bag,"uniqueid"))!==null&&n!==void 0?n:"").trim(),f=d.startsWith("{")?d:`{${l}}`;i.node.c.push(HQ(f,s,u))}}J.reconcileEmbedDescriptions=JQ;function YQ(e,t){let n=Cc(e.bag),r=t!==void 0&&(n===void 0||JSON.stringify(n.node)!==JSON.stringify(t)),i=go(e).some(({cell:a})=>Ku(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(!r&&!i)return e;let o=JSON.parse(JSON.stringify(e));if(r){let a=JSON.parse(JSON.stringify(t)),s=Cc(o.bag);s?s.node=a:(o.bag=pt(o.bag)?o.bag:{a:[],c:[]},o.bag.c=et(o.bag.c),o.bag.c.push({i:tE(e.bag),node:a}))}for(let{cell:a}of go(o))Ku(a.control)&&(HR(a.control),KR(a));return o}J.commitEmbedState=YQ;function QQ(e){if(go(e).some(({cell:n})=>Ku(n.control)))return!0;let t=Cc(e.bag);return et(t?.node.c).some(n=>n?.n==="controlDescription"&&zf(n).length>0)}J.mayCommitEmbedState=QQ;function HR(e){e.classId===void 0&&(e.classId=J.CUSTOM_CONTROL_CLASS_ID),e.showLabel===void 0&&(e.showLabel=!1),e.label===void 0&&(e.label=""),e.fieldName===void 0&&(e.fieldName=null)}J.applyEmbedControlDefaults=HR;function KR(e){e.rowspan===void 0&&(e.rowspan=J.GENPAGE_EMBED_ROWSPAN)}J.applyEmbedCellDefaults=KR;function Ku(e){return pt(e)&&e.genPage!==void 0}J.hasGenPage=Ku;function VR(e){return Ku(e.control)&&(!e.control.id||!e.id||Kf(e.control)===void 0)}function Kf(e){let t=et(pt(e.bag)?e.bag.a:void 0).find(r=>Array.isArray(r)&&r[0]==="uniqueid");if(!t)return;let n=t[1];return typeof n=="string"&&n.trim()===""?void 0:n}J.authoredUniqueId=Kf;function XQ(e){if(!go(e).some(({cell:n})=>VR(n)))return e;let t=JSON.parse(JSON.stringify(e));for(let{cell:n}of go(t)){if(!VR(n))continue;let r=n.control;r.id||(r.id=(0,jw.newId)()),n.id||(n.id=(0,jw.newId)()),Kf(r)===void 0&&nE(r)}return t}J.mintEmbedIdentity=XQ;function nE(e){let t=(0,jw.newId)(),n=`{${t}}`;if(!pt(e.bag))return e.bag={a:[["uniqueid",n]],c:[]},t;let r=et(e.bag.a),i=r.find(o=>Array.isArray(o)&&o[0]==="uniqueid");return i?i[1]=n:r.push(["uniqueid",n]),e.bag.a=r,e.bag.c=et(e.bag.c),t}J.setUniqueId=nE;function GR(e){return e===null?"null":Array.isArray(e)?"an array":typeof e}function ZQ(e){let t=et(e.c).filter(n=>n?.n==="customControl").map(n=>{var r,i;return(i=(r=qs(n,"name"))!==null&&r!==void 0?r:qs(n,"id"))!==null&&i!==void 0?i:"unnamed"});return[...new Set(t)].join(", ")||"no custom control"}function eX(e){let t=[],n;for(let{cell:r,pointer:i}of go(e)){let o=r.control;if(!pt(o))continue;let a=`${i}/control`;if(o.genPage===void 0){tX(e,o,a,t);continue}n=n??ug(e),nX(e,o,a,n,t)}return t}J.genPageEmbedIssues=eX;function tX(e,t,n,r){if(!eE(e,t))return;let i=Hf(Hu(e.bag,Wa(t)));r.push((0,Gi.issue)(n,"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 nX(e,t,n,r,i){var o;let a=`${n}/genPage`,s=t.genPage;if(!pt(s))i.push((0,Gi.issue)(a,"genpage-embed-shape",`genPage must be an object { pageId, inputData? }, got ${GR(s)}.`+(s===null?" To remove an embed, remove the cell (or set the cell's control to null).":"")));else{(typeof s.pageId!="string"||!ri(s.pageId))&&i.push((0,Gi.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&&!pt(s.inputData)&&i.push((0,Gi.issue)(`${a}/inputData`,"genpage-embed-shape",`genPage.inputData must be a JSON object \u2014 the page reads it as pageInput.data \u2014 got ${GR(s.inputData)}`));for(let p of Object.keys(s))WQ.has(p)||i.push((0,Gi.issue)(UQ.JsonPointer.append(a,p),"genpage-embed-unknown-key",`'${p}' is not a genPage property (pageId, inputData), and would be SILENTLY DROPPED at serialization.`))}cg(t)||i.push((0,Gi.issue)(`${n}/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&&jR(t.classId)!==J.CUSTOM_CONTROL_CLASS_ID&&i.push((0,Gi.issue)(`${n}/classId`,"genpage-embed-class-id",`a generative-page embed is the custom control {${J.CUSTOM_CONTROL_CLASS_ID}}, but classId is ${JSON.stringify(t.classId)}. Omit classId (the SDK defaults it) or set it to that class.`));let u=Xw(e);u!=="Main"&&i.push((0,Gi.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 ${u} form.`));let l=Kf(t);l!==void 0&&!ri(l)&&i.push((0,Gi.issue)(`${n}/bag`,"genpage-embed-unique-id",`this embed's uniqueid ${JSON.stringify(l)} 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=Wa(t);if(!c)return;let d=Hu(e.bag,c),f=d?Hf(d):void 0;d&&f?.kind==="none"?i.push((0,Gi.issue)(a,"genpage-embed-other-control",`this control is already bound to another custom control (${ZQ(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,Gi.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=r.get(c))!==null&&o!==void 0?o:0)>1&&i.push((0,Gi.issue)(`${n}/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 Sc=C(hn=>{"use strict";Object.defineProperty(hn,"__esModule",{value:!0});hn.isKnownSystemFormType=hn.assertSystemFormKind=hn.readSystemFormType=hn.decodeCode=hn.assertSystemFormRecordKind=hn.describeSystemFormType=hn.systemFormKindOf=hn.SYSTEMFORM_KIND_MISMATCH_CODE=void 0;var YR=Y(),rX=pe(),JR=ae();hn.SYSTEMFORM_KIND_MISMATCH_CODE="SYSTEMFORM_KIND_MISMATCH";var iX={0:"dashboard",10:"dashboard",2:"form",6:"form",7:"form",11:"form"},QR={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 fg(e){return Number.isInteger(e)?iX[e]:void 0}hn.systemFormKindOf=fg;function XR(e){var t;return Number.isFinite(e)?`a ${(t=QR[e])!==null&&t!==void 0?t:"systemform"} (type ${e})`:"a systemform whose type could not be read"}hn.describeSystemFormType=XR;function ZR(e,t,n,r){let i=XR(n),o=fg(n);switch(r){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(n)?"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 ${r} systemform '${e}': it is ${i}, not a ${t}.`+(r==="set the security roles of"?" Nothing was written.":"")+" Check the id."}}function oX(e,t,n,r){let i=rE(e?.type);if(fg(i)!==n)throw new YR.SdkError(hn.SYSTEMFORM_KIND_MISMATCH_CODE,ZR(t,n,i,r));return i}hn.assertSystemFormRecordKind=oX;function rE(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}hn.decodeCode=rE;async function aX(e,t){return await ek(e,t,!1)}hn.readSystemFormType=aX;async function sX(e,t){return ek(e,t,!0)}async function ek(e,t,n){var r;let o=`/systemforms(${(0,JR.normalizeGuid)(t,"formId")})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,JR.odataQuery)([["$select","type"]]),a=await e.get(o);if(!(n&&a.status===404))return(0,rX.ensureSuccess)(a,e.apiUrl(o)),rE((r=a.body)===null||r===void 0?void 0:r.type)}async function uX(e,t,n){let r=await sX(e,t);if(!(r===void 0||fg(r)===n))throw new YR.SdkError(hn.SYSTEMFORM_KIND_MISMATCH_CODE,ZR(t,n,r,"delete"))}hn.assertSystemFormKind=uX;function lX(e){return Number.isInteger(e)&&QR[e]!==void 0}hn.isKnownSystemFormType=lX});var oE=C(Di=>{"use strict";Object.defineProperty(Di,"__esModule",{value:!0});Di.patchSystemForm=Di.assertSystemFormContentUnchanged=Di.readSystemFormRowEtag=Di.unpublishedSystemFormPath=Di.FORM_TYPE_IMMUTABLE_CODE=void 0;var ii=pe(),Jf=qi(),cX=ae(),pg=Y(),Bs=Sc();Di.FORM_TYPE_IMMUTABLE_CODE="FORM_TYPE_IMMUTABLE";function iE(e,t="formid"){return`/systemforms(${e})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,cX.odataQuery)([["$select",t]])}Di.unpublishedSystemFormPath=iE;function tk(e,t){return(0,ii.readRowEtag)(e,"systemforms","formid",t)}Di.readSystemFormRowEtag=tk;async function nk(e,t,n,r,i,o){let a={guard:"contentToken",componentName:"SystemForm",componentId:t};o&&!(0,ii.isVersionToken)(i)&&o.observe({...a,held:i,status:"missingHeld"}),(0,ii.requireEtag)(i,n,t);let s;try{s=(0,ii.ensureSuccess)(await e.get(r),e.apiUrl(r))}catch(c){throw o?.observe({...a,held:i,status:(0,Jf.failedReadStatus)(c),detail:(0,Jf.failureDetail)(c)}),c}let u=(0,Bs.assertSystemFormRecordKind)(s.body,t,n,"write"),l=(0,ii.readEtag)(s);if(o?.observe({...a,held:i,server:l,status:(0,Jf.compareTokens)(i,l)}),l===null)throw new pg.SdkError(ii.VERSION_CONFLICT_CODE,`Refusing to write ${n} '${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(l!==i)throw new pg.SdkError(ii.VERSION_CONFLICT_CODE,`Version conflict writing ${n} '${t}': its formxml changed on the server since it was read (held ${i}, server ${l}). Re-fetch the ${n} and re-apply the change.`);return u}Di.assertSystemFormContentUnchanged=nk;async function dX(e,t,n,r,i,o,a){a&&!(0,ii.isVersionToken)(i)&&a.observe({guard:"contentToken",componentName:"SystemForm",componentId:t,held:i,status:"missingHeld"}),(0,ii.requireEtag)(i,n,t);let s;try{s=await tk(e,t)}catch(d){throw a?.observe({guard:"rowToken",componentName:"SystemForm",componentId:t,status:(0,Jf.failedReadStatus)(d),detail:(0,Jf.failureDetail)(d)}),d}if(s===null)throw a?.observe({guard:"rowToken",componentName:"SystemForm",componentId:t,status:"missingServer"}),new pg.SdkError(ii.VERSION_CONFLICT_CODE,`Refusing to write ${n} '${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 u=await nk(e,t,n,iE(t,"formid,type"),i,a);if(r.type!==void 0&&(0,Bs.decodeCode)(r.type)!==u)throw new pg.SdkError(Di.FORM_TYPE_IMMUTABLE_CODE,`Refusing to push ${n} '${t}': it would change it from ${(0,Bs.describeSystemFormType)(u)} to ${(0,Bs.describeSystemFormType)((0,Bs.decodeCode)(r.type))}. The platform ignores a type change on an existing ${n}, so the push would report a change that did not happen. Nothing was written. Create a new ${n} of that type instead.`);if(a)return a.reached({effects:[{componentName:"SystemForm",componentId:t,identity:"known",operation:"update"}],attemptsWrite:!0});let l=(0,ii.echoWrite)("formid",{"If-Match":s}),c=`/systemforms(${t})${l.query}`;return(0,ii.ensureSuccess)(await e.patch(c,r,l.options),e.apiUrl(c)),fX(e,t,n,o)}Di.patchSystemForm=dX;async function fX(e,t,n,r){let i;try{let o=iE(t,r.select),a=(0,ii.ensureSuccess)(await e.get(o),e.apiUrl(o)),s=a.body,u=(0,ii.readEtag)(a),l=typeof s?.formid=="string"&&s.formid.replace(/[{}]/g,"").toLowerCase()===t,c=typeof s?.formxml=="string"&&s.formxml.trim()!=="",d=r.required.filter(m=>s?.[m]===void 0||s?.[m]===null),f=(0,Bs.decodeCode)(s?.type),p=(0,Bs.systemFormKindOf)(f)===n;if(u&&l&&c&&d.length===0&&p)return{id:t,etag:u,readBack:s};i=u?!l||!c?`the read did not return this ${n}'s document`:d.length>0?`the read did not return its ${d.join(", ")}`:`the read returned ${(0,Bs.describeSystemFormType)(f)}, not a ${n}`:"the read returned no version"}catch(o){i=o instanceof Error?o.message:String(o)}return{id:t,etag:null,warnings:[`The ${n} 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 ${n} before editing it again.`]}}});var mg=C(jn=>{"use strict";Object.defineProperty(jn,"__esModule",{value:!0});jn.getFormSecurityRoles=jn.setFormSecurityRoles=jn.formApi=jn.readPrimaryCreateRefusal=jn.FORM_GENPAGE_TARGET_UNVERIFIABLE=jn.FORM_GENPAGE_TARGET_NOT_FOUND=void 0;var pX=Ke(),Nn=pe(),Pi=ae(),Ju=Y(),aE=ja(),ok=dg(),rk=Vh(),sE=oE(),Qf=Sc(),Yf=qi();jn.FORM_GENPAGE_TARGET_NOT_FOUND="FORM_GENPAGE_TARGET_NOT_FOUND";jn.FORM_GENPAGE_TARGET_UNVERIFIABLE="FORM_GENPAGE_TARGET_UNVERIFIABLE";var ak="formid,formxml,name,type,objecttypecode,formpresentation,formactivationstate,uniquename,description,versionnumber",mX={select:ak,required:["name","type","objecttypecode"]},hX="formid,name,type,objecttypecode",gX=2,yX={Main:gX,QuickView:6,QuickCreate:7,Card:11},sk=new WeakMap;function bX(e){return typeof e=="object"&&e!==null?sk.get(e):void 0}jn.readPrimaryCreateRefusal=bX;jn.formApi={async get(e,t){let n=(0,Pi.normalizeGuid)(t,"id"),r=`/systemforms(${n})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,Pi.odataQuery)([["$select",ak]]),i=(0,Nn.ensureSuccess)(await e.get(r),e.apiUrl(r));return(0,Qf.assertSystemFormRecordKind)(i.body,n,"form","fetch"),{raw:i.body,etag:(0,Nn.readEtag)(i)}},async list(e,t){var n;let r=!((n=t?.formTypes)===null||n===void 0)&&n.length?t.formTypes:["Main"],i=[...new Set(r.map(l=>yX[l]))],a=[i.length===1?`type eq ${i[0]}`:`(${i.map(l=>`type eq ${l}`).join(" or ")})`];t?.entityLogicalName&&a.push(`objecttypecode eq '${(0,Pi.odataLiteral)(t.entityLogicalName)}'`);let s=`/systemforms${(0,Pi.odataQuery)([["$select",hX],["$filter",a.join(" and ")]])}`;return(await(0,pX.collectPages)(e,s,"listArtifacts('form')")).map(l=>{var c,d;return{type:"form",id:(c=l.formid)!==null&&c!==void 0?c:"",name:(d=l.name)!==null&&d!==void 0?d:"",entityLogicalName:l.objecttypecode,isDirty:!1}})},async create(e,t,n,r=void 0){let i=ik(t);i!==void 0&&await uk(e,lE(i,"payload"),[],r);let o=(0,Nn.echoWrite)("formid"),a=`/systemforms${o.query}`,s=(0,Nn.withClientMintedId)(t,"formid",n),u=Object.freeze({...s});if(r){let c=n?(0,Pi.normalizeGuid)(n,"formid"):void 0;return r.reached({effects:[{componentName:"SystemForm",componentId:c,identity:"known",operation:"create"}],attemptsWrite:!0},c?()=>(0,Yf.existsByKey)(e,r,{collection:"/systemforms",key:"formid",id:c,componentName:"SystemForm"}):void 0)}let l=await(0,Nn.resendDeadlockVictim)(()=>e.post(a,{...u},o.options));try{(0,Nn.ensureSuccess)(l,e.apiUrl(a))}catch(c){throw typeof c=="object"&&c!==null&&sk.set(c,{status:l.status,sent:u,desiredId:n}),c}return{id:(0,Nn.resolveCreatedId)(l,"formid","form",n),etag:(0,Nn.readEtag)(l)}},async update(e,t,n,r,i=void 0,o,a){let s=(0,Pi.normalizeGuid)(t,"id"),u=ik(n);return u!==void 0&&await wX(e,s,u,r,a),(0,sE.patchSystemForm)(e,s,"form",n,r,mX,a)},readContentThenToken(e,t){return jn.formApi.get(e,t)},planPush(e,t,n){return(0,Yf.planPushThrough)(jn.formApi,e,t,n)},async delete(e,t){let n=(0,Pi.normalizeGuid)(t,"id");return await(0,Qf.assertSystemFormKind)(e,n,"form"),(0,Nn.deleteRecord)(e,"systemforms",n)}};var uE="DisplayConditions";async function vX(e,t,n){var r,i,o,a;if(n.everyone&&n.roleIds&&n.roleIds.length>0)throw new Ju.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,Pi.normalizeGuid)(t,"formId"),u=`/systemforms(${s})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,Pi.odataQuery)([["$select","formid,formxml,type"]]),l=(0,Nn.ensureSuccess)(await e.get(u),e.apiUrl(u));(0,Qf.assertSystemFormRecordKind)(l.body,s,"form","set the security roles of");let c=(0,Nn.readEtag)(l),d=l.body,f=d?.formxml;if(!f)throw new Ju.InvalidArgumentError(`form '${s}' returned no formxml, so its roles cannot be set`);let p=(0,aE.parseXmlRoot)(f,"<form/>"),m=p.ownerDocument;if(!m)throw new Ju.InvalidArgumentError(`form '${s}' produced no owner document`);let h=lk(p,uE),g=h?.hasAttribute("Order")&&(r=h.getAttribute("Order"))!==null&&r!==void 0?r:void 0,y=h?.getAttribute("FallbackForm")||void 0;h&&p.removeChild(h);let b=!!n.everyone||((o=(i=n.roleIds)===null||i===void 0?void 0:i.length)!==null&&o!==void 0?o:0)>0;if(!b&&(n.order!==void 0||n.fallbackForm!==void 0)){if(!h)throw new Ju.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.");n.order!==void 0&&h.setAttribute("Order",String(n.order)),n.fallbackForm!==void 0&&h.setAttribute("FallbackForm",String(n.fallbackForm)),p.appendChild(h)}else if(b){let T=m.createElement(uE),O=n.order!==void 0?String(n.order):g;O!==void 0&&T.setAttribute("Order",O);let v=n.fallbackForm!==void 0?String(n.fallbackForm):y??"false";if(T.setAttribute("FallbackForm",v),n.everyone)T.appendChild(m.createElement("Everyone"));else for(let N of(a=n.roleIds)!==null&&a!==void 0?a:[]){let S=m.createElement("Role");S.setAttribute("Id",`{${(0,Pi.normalizeGuid)(N,"roleId")}}`),T.appendChild(S)}p.appendChild(T)}let w=(0,aE.serializeNode)(p);await(0,sE.assertSystemFormContentUnchanged)(e,s,"form",u,c);let _=await(0,sE.readSystemFormRowEtag)(e,s),I=`/systemforms(${s})`;(0,Nn.ensureSuccess)(await e.patch(I,{formxml:w},{headers:{"Content-Type":"application/json","If-Match":(0,Nn.requireEtag)(_,"form",s)}}),e.apiUrl(I))}jn.setFormSecurityRoles=vX;function ik(e){let t=e?.formxml;return typeof t=="string"&&t.includes(ok.GENPAGE_CONTROL_NAME)?t:void 0}function lE(e,t){try{return(0,ok.activeEmbedBindings)(e)}catch(n){throw new Ju.SdkError(jn.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 (${n instanceof Error?n.message:String(n)}).`)}}async function uk(e,t,n,r){let i=new Set(n.map(([s,u])=>`${s}|${u}`)),o=t.filter(([s,u])=>!i.has(`${s}|${u}`)).map(([,s])=>s);if(o.length===0)return;let a=await(0,rk.findMissingGenPages)(e,o,"form generative-page preflight");if((0,rk.observeGenPageTargets)(r,o,a),a.length>0)throw new Ju.SdkError(jn.FORM_GENPAGE_TARGET_NOT_FOUND,`Refusing to push the form: it embeds generative page(s) ${a.map(s=>`'${s}'`).join(", ")} that do not exist in this environment. Push the page before the form that embeds it.`)}async function wX(e,t,n,r,i){var o;let a={guard:"contentToken",componentName:"SystemForm",componentId:t};i&&!(0,Nn.isVersionToken)(r)&&i.observe({...a,held:r,status:"missingHeld"}),(0,Nn.requireEtag)(r,"form",t);let s=`/systemforms(${t})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,Pi.odataQuery)([["$select","formid,formxml,type"]]),u;try{u=(0,Nn.ensureSuccess)(await e.get(s),e.apiUrl(s))}catch(f){throw i?.observe({...a,held:r,status:(0,Yf.failedReadStatus)(f),detail:(0,Yf.failureDetail)(f)}),f}(0,Qf.assertSystemFormRecordKind)(u.body,t,"form","write");let l=(0,Nn.readEtag)(u);if(i?.observe({...a,held:r,server:l,status:(0,Yf.compareTokens)(r,l)}),l===null||l!==r)throw new Ju.SdkError(Nn.VERSION_CONFLICT_CODE,`Version conflict writing form '${t}': its formxml changed on the server since it was read (held ${r}, server ${l??"(unreadable)"}). Re-fetch the form and re-apply the change.`);let c=(o=u.body)===null||o===void 0?void 0:o.formxml,d=typeof c=="string"&&c!==""?lE(c,"server"):[];await uk(e,lE(n,"payload"),d,i)}function lk(e,t){let n=e.childNodes;for(let r=0;r<n.length;r+=1){let i=n[r];if(i.nodeType===1&&i.tagName===t)return i}}async function EX(e,t){var n,r;let i=(0,Pi.normalizeGuid)(t,"formId"),o=`/systemforms(${i})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,Pi.odataQuery)([["$select","formid,formxml,type"]]),a=(0,Nn.ensureSuccess)(await e.get(o),e.apiUrl(o));(0,Qf.assertSystemFormRecordKind)(a.body,i,"form","read the security roles of");let s=(n=a.body)===null||n===void 0?void 0:n.formxml;if(!s)return;let u=(0,aE.parseXmlRoot)(s,"<form/>"),l=lk(u,uE);if(!l)return;let c=[],d=!1,f=l.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 y=(r=g.getAttribute("Id"))!==null&&r!==void 0?r:"";y&&c.push(y.replace(/[{}]/g,"").toLowerCase())}}let p=l.getAttribute("Order");return{...d?{everyone:!0}:{},...c.length>0?{roleIds:c}:{},fallbackForm:l.getAttribute("FallbackForm")==="true",...p!==null&&p!==""?{order:Number(p)}:{}}}jn.getFormSecurityRoles=EX});var hk=C(Gs=>{"use strict";Object.defineProperty(Gs,"__esModule",{value:!0});Gs.judgeBatchDependencies=Gs.previewArtifact=Gs.readTargetSolution=void 0;var AX=vc(),CX=mg(),SX=Vh(),hg=qi(),dE=Y(),NX=pe(),_X=Rs(),Vs=ae(),mk=["writePlan","concurrency","existence","createAnswer","deleteOfManaged","solution","managedSolutionTarget","batchDependency"],cE=new Set([CX.FORM_GENPAGE_TARGET_NOT_FOUND,AX.SITEMAP_TARGET_NOT_FOUND_CODE]),IX={[SX.GENPAGE_COMPONENT_NAME]:"genPage"},TX=new Set(["view","form","chart","dashboard","app"]),OX=/^1900-01-01T00:00:00/,DX=new Set(["different","goneOnServer","addedOnServer"]),PX=new Set(["missingHeld","missingServer","readFailed"]);async function RX(e,t){var n;let r=`/solutions${(0,Vs.odataQuery)([["$select","solutionid,ismanaged"],["$filter",`uniquename eq '${(0,Vs.odataLiteral)(t)}'`]])}`;try{let i=await e.get(r),o=(n=i.body)===null||n===void 0?void 0:n.value;if(i.status<200||i.status>=300||!Array.isArray(o))return{uniqueName:t,status:"unreadable",detail:`HTTP ${i.status}`};let a=o[0];return a?typeof a.solutionid!="string"?{uniqueName:t,status:"unreadable",detail:"the solution row carried no solutionid"}:{uniqueName:t,status:a.ismanaged===!0?"managed":"found",solutionId:(0,Vs.normalizeGuid)(a.solutionid,"solutionid")}:{uniqueName:t,status:"missing"}}catch(i){return{uniqueName:t,status:"unreadable",detail:(0,hg.failureDetail)(i)}}}Gs.readTargetSolution=RX;function ck(e){return!(e instanceof dE.SdkError)||e.code==="PREVIEW_WRITE_REFUSED"||e.code==="PREVIEW_PLAN_INCOMPLETE"}function dk(e){return{code:e.code,message:e.message,...e instanceof dE.ValidationError?{issues:e.issues}:{}}}function kX(e,t,n){if(e){if(!t)return"notEvaluated";switch(t.existence){case"absent":return"absent";case"present":return"exists";case"unread":return"unknown";default:return"notApplicable"}}let r=n.filter(i=>i.guard!=="dependency");return r.some(i=>DX.has(i.status))?"stale":r.some(i=>PX.has(i.status))?"unknown":t||r.length>0?"current":"notEvaluated"}async function $X(e,t,n){var r;let i=`/msdyn_componentlayers${(0,Vs.odataQuery)([["$select","msdyn_order,msdyn_solutionname,msdyn_publishername,msdyn_overwritetime"],["$filter",`(msdyn_componentid eq '${(0,Vs.normalizeGuid)(n,"componentId")}' and msdyn_solutioncomponentname eq '${(0,Vs.odataLiteral)(t)}')`]])}`,o;try{let s=await e.get(i);if(o=(r=s.body)===null||r===void 0?void 0:r.value,s.status<200||s.status>=300||!Array.isArray(o))return{failed:`HTTP ${s.status}`}}catch(s){return{failed:(0,hg.failureDetail)(s)}}let a=o.map(s=>{var u,l;let c=typeof s.msdyn_overwritetime=="string"?s.msdyn_overwritetime:void 0;return{order:Number(s.msdyn_order),solutionName:String((u=s.msdyn_solutionname)!==null&&u!==void 0?u:""),publisherName:String((l=s.msdyn_publishername)!==null&&l!==void 0?l:""),...c&&!OX.test(c)?{overwriteTime:c}:{}}}).sort((s,u)=>u.order-s.order);return a.length===0?{status:"empty"}:{status:"read",layers:a,hasManagedLayers:a.some(s=>s.solutionName!=="Active")}}async function LX(e,t,n){var r;let i=`/solutioncomponents${(0,Vs.odataQuery)([["$select","objectid"],["$filter",`_solutionid_value eq ${t} and (${n.map(o=>`objectid eq ${o}`).join(" or ")})`]])}`;try{let o=await e.get(i),a=(r=o.body)===null||r===void 0?void 0:r.value;return o.status<200||o.status>=300||!Array.isArray(a)?{failed:`HTTP ${o.status}`}:new Set(a.map(s=>typeof s.objectid=="string"?(0,Vs.normalizeGuid)(s.objectid,"objectid"):"").filter(s=>s!==""))}catch(o){return{failed:(0,hg.failureDetail)(o)}}}function fk(e){return e.status==="read"?e.layers.filter(t=>t.solutionName!=="Active").map(t=>t.solutionName).join(", "):""}async function MX(e){var t,n,r,i,o,a;let{type:s,id:u,reg:l,client:c,guard:d,meta:f}=e,p=d.gets,m=[],h=[],g=new Set,y=[],b=f===null,E=b?"create":e.localChanges.length>0?"update":"noChange",w;try{w=await e.prepare()}catch(M){if(ck(M))throw M;m.push(dk(M)),g.add("writePlan")}let _;if(w&&!l.api.planPush)g.add("writePlan");else if(w&&l.api.planPush)try{_=await l.api.planPush(c,{id:u,payload:w.payload,...f?{held:{etag:f.etag,memberEtags:f.memberEtags,siblingEtags:f.siblingEtags}}:{}},M=>y.push(M))}catch(M){if(ck(M))throw M;m.push(dk(M))}for(let M of(t=_?.warnings)!==null&&t!==void 0?t:[])h.push(M);let I=kX(b,_,y);for(let M of y)M.guard==="ifMatch"&&M.status==="different"?m.push({code:NX.VERSION_CONFLICT_CODE,message:`The push's write to ${M.componentName} '${M.componentId}' is conditioned on If-Match ${M.held}, but the row is now at ${M.server}: another writer changed it since it was read, and the platform refuses the write (412). Re-fetch and re-apply the change.`}):M.guard==="ifMatch"&&M.status==="goneOnServer"&&m.push({code:"CONNECTION_ERROR",message:`${M.componentName} '${M.componentId}' no longer exists on the server (a read of it answered 404): the push's conditional write to it fails. Re-fetch the artifact.`});I==="unknown"&&!b&&m.length===0&&g.add("concurrency");let T={verdict:I,observations:y};if(I==="stale")try{let M=await l.api.get(c,u),q=X=>{var ye,Ve,_e;return(_e=(Ve=(ye=l.adapter).baselineContent)===null||Ve===void 0?void 0:Ve.call(ye,X))!==null&&_e!==void 0?_e:X};T.remoteChanges=(0,_X.deepDiff)(q(f?.snapshot),q(l.adapter.fromApiResponse(M.raw)))}catch(M){if(M instanceof dE.SdkError&&M.code==="PREVIEW_WRITE_REFUSED")throw M;let q={code:"PREVIEW_REMOTE_CHANGES_UNAVAILABLE",message:`The server changed since the last fetch or push, but reading what changed failed: ${(0,hg.failureDetail)(M)}`};T.remoteChangesError=q,h.push(q)}let O=b&&_?.existence==="present";if(b&&_?.existence==="unread"&&g.add("existence"),O&&w)if(e.judgeAdoption){let M=await e.judgeAdoption(w.payload,w.json);"eligible"in M?(h.push({code:"PREVIEW_CREATE_ADOPTION_ELIGIBLE",message:`A record already exists at '${u}' and matches what this create would write: the push ADOPTS it if its create is answered 412, and reports ARTIFACT_ALREADY_EXISTS if it is answered 404 (both are measured platform answers to a replayed create).`}),g.add("createAnswer")):m.push({code:"ARTIFACT_ALREADY_EXISTS",message:e.alreadyExists(M.refused)})}else m.push({code:"ARTIFACT_ALREADY_EXISTS",message:e.alreadyExists()});let v=O?[]:(n=_?.effects)!==null&&n!==void 0?n:[],N=[],S=!1;for(let M of v){let q;if(M.operation==="create"||M.identity==="assignedAtWrite"||!M.componentId)q={status:"notRead",reason:"new"};else if(((r=e.options)===null||r===void 0?void 0:r.layers)===!1)q={status:"notRead",reason:"disabled"};else{let X=await $X(c,M.componentName,M.componentId);"failed"in X?(q={status:"notRead",reason:"failed"},h.push({code:"PREVIEW_READ_FAILED",message:`The solution layers of ${M.componentName} '${M.componentId}' could not be read: ${X.failed}`})):q=X}M.operation==="update"&&q.status==="read"&&q.hasManagedLayers&&h.push({code:"PREVIEW_LAYER_OVER_MANAGED",message:`This push saves an unmanaged change to ${M.componentName} '${M.componentId}', which carries managed layers from ${fk(q)}. Once published, the change sits in the Active (unmanaged) layer ABOVE them, masking their values for what it changes \u2014 later updates of those solutions do not show through for those values until the active customization is removed. Removing the solution that introduced a component removes the component with its unmanaged changes (measured where that solution was the component's only managed layer); removing a solution layered above another exposes the layer below instead. This lists layers; it does not compute which properties conflict.`}),M.operation==="delete"&&(q.status==="read"&&!q.hasManagedLayers||(S=!0,h.push({code:"PREVIEW_DELETE_OF_MANAGED",message:`This push DELETES ${M.componentName} '${M.componentId}', which is not proven unmanaged (`+(q.status==="read"?`managed layers from ${fk(q)}`:q.status==="empty"?"its layer read answered no rows":`its layers were not read: ${q.reason}`)+"). The platform refuses to delete a managed form (measured); for other components it was not measured."}))),N.push({componentName:M.componentName,...M.componentId?{componentId:M.componentId}:{},identity:M.identity,operation:M.operation,layers:q})}S&&g.add("deleteOfManaged");let R,x=await e.solution();if(x){let M=_?.attemptsWrite===!0;R={uniqueName:x.uniqueName,status:x.status,appliesToPush:M},M&&await xX(c,s,x,N,m,h,g)}let G=w?((i=l.publishesOnPush)===null||i===void 0?void 0:i.call(l,w.payload,b))===!0:!1,U=(o=l.publishScope)===null||o===void 0?void 0:o.call(l,u,(a=w?.json)!==null&&a!==void 0?a:e.json);return{type:s,id:u,action:E,outcome:m.length>0?"refused":g.size>0?"unknown":"ready",refusals:m,warnings:h,notEvaluated:mk.filter(M=>g.has(M)),localChanges:e.localChanges,concurrency:T,components:N,...R?{solution:R}:{},publish:{byPush:G,...U?{scope:U}:{}},requests:d.gets-p}}Gs.previewArtifact=MX;async function xX(e,t,n,r,i,o,a){var s;let u=r.filter(d=>d.operation!=="delete");if(n.status==="missing"){i.push({code:"PREVIEW_SOLUTION_NOT_FOUND",message:`The configured solution '${n.uniqueName}' does not exist, and the platform refuses every write that names it: the push fails with HTTP 404 0x80040217 (a ConnectionError \u2014 the push has no code of its own for it).`});return}if(n.status==="unreadable"){a.add("solution"),o.push({code:"PREVIEW_READ_FAILED",message:`The configured solution '${n.uniqueName}' could not be read: ${(s=n.detail)!==null&&s!==void 0?s:"unknown failure"}`});return}if(n.status==="managed"){let d=TX.has(t);if(o.push({code:"PREVIEW_SOLUTION_MANAGED",message:d?`The configured solution '${n.uniqueName}' is MANAGED: the push saves, and what it writes does not join that solution (measured for this kind).`:`The configured solution '${n.uniqueName}' is MANAGED, and what a push of this kind does then was not measured.`}),d)for(let f of u)f.joinsSolution=!1;else a.add("managedSolutionTarget");return}let l=u.filter(d=>d.operation==="update"&&d.componentId),c=l.length>0&&n.solutionId?await LX(e,n.solutionId,l.map(d=>d.componentId)):new Set;c instanceof Set||o.push({code:"PREVIEW_READ_FAILED",message:`The membership of the configured solution '${n.uniqueName}' could not be read: ${c.failed}`});for(let d of u)d.operation==="create"?d.joinsSolution=!0:c instanceof Set&&d.componentId&&(d.joinsSolution=!c.has(d.componentId))}function pk(e){return e.replace(/[{}]/g,"").toLowerCase()}function FX(e){e.forEach((t,n)=>{let r=t.concurrency.observations.filter(u=>u.guard==="dependency"&&u.status==="absent");if(r.length===0||!t.refusals.some(u=>cE.has(u.code)))return;let i=e.slice(0,n).filter(u=>u.action==="create"&&u.outcome!=="refused"),o=[];for(let u of r){let l=i.find(c=>c.type===IX[u.componentName]&&u.componentId!==void 0&&pk(c.id)===pk(u.componentId));if(!l)return;o.push(l)}let a=t.refusals.filter(u=>cE.has(u.code)).map(u=>u.code);t.refusals=t.refusals.filter(u=>!cE.has(u.code)),t.warnings.push({code:"PREVIEW_BATCH_DEPENDENCY",message:`This push needs ${r.map(u=>`${u.componentName} '${u.componentId}'`).join(", ")}, missing on the server now, which ${o.map(u=>`${u.type} '${u.id}' (${u.outcome})`).join(", ")} creates earlier in this batch. Its check for it, and every check after that, were not evaluated; if that create fails, this push is refused (${a.join(", ")}).`});let s=new Set([...t.notEvaluated,"writePlan","batchDependency"]);t.notEvaluated=mk.filter(u=>s.has(u)),t.outcome=t.refusals.length>0?"refused":"unknown"})}Gs.judgeBatchDependencies=FX});var wk=C($r=>{"use strict";Object.defineProperty($r,"__esModule",{value:!0});$r.findColumns=$r.findTables=$r.readCheckColumns=$r.readColumnHints=$r.fetchEntityMetadataFromApi=$r.COLUMN_DETAIL_VERSION=void 0;var bk=Ke(),vk=pe(),oi=ae();function ji(e){var t,n;return(n=(t=e?.UserLocalizedLabel)===null||t===void 0?void 0:t.Label)!==null&&n!==void 0?n:""}$r.COLUMN_DETAIL_VERSION=2;function fE(e){var t,n;return typeof((t=e?.UserLocalizedLabel)===null||t===void 0?void 0:t.Label)=="string"||((n=e?.LocalizedLabels)!==null&&n!==void 0?n:[]).some(r=>typeof r?.Label=="string")}function Yu(e){let t=e?.LocalizedLabels;if(!Array.isArray(t)||t.length<2)return;let n={};for(let r of t)typeof r?.LanguageCode=="number"&&typeof r.Label=="string"&&(n[r.LanguageCode]=r.Label);return Object.keys(n).length?n:void 0}async function gg(e,t){return(await bg(e,t)).rows}async function bg(e,t){var n,r;let i=await e.get(t);return i.status<200||i.status>=300?{rows:[],ok:!1}:{rows:(r=(n=i.body)===null||n===void 0?void 0:n.value)!==null&&r!==void 0?r:[],ok:!0}}function Ri(e){return`/EntityDefinitions(LogicalName='${(0,oi.odataPathLiteral)(e)}')`}async function UX(e,t,n){let r=await gg(e,`${Ri(t)}/Attributes/Microsoft.Dynamics.CRM.StringAttributeMetadata${(0,oi.odataQuery)([["$select","LogicalName,MaxLength"]])}`);for(let i of r){let o=n.get(i.LogicalName);o&&typeof i.MaxLength=="number"&&(o.maxLength=i.MaxLength)}}function qX(e){return`${Ri(e)}/Attributes/Microsoft.Dynamics.CRM.PicklistAttributeMetadata${(0,oi.odataQuery)([["$select","LogicalName"],["$expand","OptionSet($select=Options)"]])}`}async function BX(e,t){var n;let{rows:r}=await e;for(let i of r){let o=t.get(i.LogicalName);o&&(!((n=i.OptionSet)===null||n===void 0)&&n.Options)&&(o.options=i.OptionSet.Options.map(a=>{var s;return{value:(s=a.Value)!==null&&s!==void 0?s:0,label:ji(a.Label),...Yu(a.Label)?{localizedLabel:Yu(a.Label)}:{}}}))}}function pE(e){var t;return{value:(t=e.Value)!==null&&t!==void 0?t:0,label:ji(e.Label),...e.InvariantName?{invariantName:e.InvariantName}:{},...e.Color?{color:e.Color}:{}}}async function VX(e,t,n){var r;let i=c=>bg(e,c).catch(()=>({rows:[],ok:!1})),o=["MultiSelectPicklistAttributeMetadata","StateAttributeMetadata","StatusAttributeMetadata"],a=await Promise.all([n.catch(()=>({rows:[],ok:!1})),...o.map(c=>i(`${Ri(t)}/Attributes/Microsoft.Dynamics.CRM.${c}${(0,oi.odataQuery)([["$select","LogicalName"],["$expand","OptionSet($select=Options)"]])}`))]),s=new Map,u=!0;for(let{rows:c}of a)for(let d of c)!((r=d.OptionSet)===null||r===void 0)&&r.Options&&(u=u&&d.OptionSet.Options.every(f=>fE(f.Label)),s.set(d.LogicalName,d.OptionSet.Options.map(pE)));let l=await i(`${Ri(t)}/Attributes/Microsoft.Dynamics.CRM.BooleanAttributeMetadata${(0,oi.odataQuery)([["$select","LogicalName"],["$expand","OptionSet($select=TrueOption,FalseOption)"]])}`);for(let c of l.rows){let d=c.OptionSet;d?.TrueOption&&d.FalseOption&&(u=u&&fE(d.TrueOption.Label)&&fE(d.FalseOption.Label),s.set(c.LogicalName,[pE(d.FalseOption),pE(d.TrueOption)]))}return{byColumn:s,complete:u&&l.ok&&a.every(c=>c.ok)}}async function GX(e,t,n){let{rows:r,ok:i}=await bg(e,`${Ri(t)}/Attributes/Microsoft.Dynamics.CRM.LookupAttributeMetadata${(0,oi.odataQuery)([["$select","LogicalName,Targets"]])}`);for(let o of r){let a=n.get(o.LogicalName);a&&o.Targets&&(a.targets=o.Targets)}return i}function yg(e,t){return e<t?-1:e>t?1:0}var gk={OneToMany:0,ManyToOne:1,ManyToMany:2};function jX(e,t){return gk[e.type]-gk[t.type]||yg(e.schemaName,t.schemaName)||yg(e.relatedEntity,t.relatedEntity)||yg(e.relatedAttribute,t.relatedAttribute)}async function WX(e,t){var n,r,i,o;let a=[],s=await gg(e,`${Ri(t)}/OneToManyRelationships${(0,oi.odataQuery)([["$select","SchemaName,ReferencingEntity,ReferencingAttribute"]])}`);for(let c of s)a.push({schemaName:c.SchemaName,type:"OneToMany",relatedEntity:(n=c.ReferencingEntity)!==null&&n!==void 0?n:"",relatedAttribute:(r=c.ReferencingAttribute)!==null&&r!==void 0?r:""});let u=await gg(e,`${Ri(t)}/ManyToOneRelationships${(0,oi.odataQuery)([["$select","SchemaName,ReferencedEntity,ReferencedAttribute"]])}`);for(let c of u)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 l=await gg(e,`${Ri(t)}/ManyToManyRelationships${(0,oi.odataQuery)([["$select","SchemaName,Entity1LogicalName,Entity2LogicalName"]])}`);for(let c of l){let d=c.Entity1LogicalName===t?c.Entity2LogicalName:c.Entity1LogicalName;a.push({schemaName:c.SchemaName,type:"ManyToMany",relatedEntity:d??"",relatedAttribute:""})}return a.sort(jX)}async function zX(e,t){var n,r,i,o,a;let s=`${Ri(t)}`+(0,oi.odataQuery)([["$select","LogicalName,SchemaName,DisplayName,Description,EntitySetName,IsCustomEntity,PrimaryNameAttribute,PrimaryIdAttribute,PrimaryImageAttribute"],["$expand","Attributes($select=LogicalName,DisplayName,Description,AttributeType,AttributeTypeName,IsCustomAttribute,IsValidForUpdate,IsValidForRead,AttributeOf)"]]),l=(0,vk.ensureSuccess)(await e.get(s),e.apiUrl(s)).body,c=((n=l.Attributes)!==null&&n!==void 0?n:[]).map(g=>{var y,b,E;return{logicalName:g.LogicalName,displayName:ji(g.DisplayName),...Yu(g.DisplayName)?{localizedDisplayName:Yu(g.DisplayName)}:{},attributeType:(y=g.AttributeType)!==null&&y!==void 0?y:"Unknown",isCustomAttribute:!!g.IsCustomAttribute,attributeTypeName:(E=(b=g.AttributeTypeName)===null||b===void 0?void 0:b.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}:{},...ji(g.Description)?{description:ji(g.Description)}:{}}}).sort((g,y)=>yg(g.logicalName,y.logicalName)),d=new Map(c.map(g=>[g.logicalName,g])),f=bg(e,qX(t)),[,,p,m,h]=await Promise.all([UX(e,t,d),BX(f,d),VX(e,t,f),GX(e,t,d),WX(e,t)]);for(let g of c){let y=p.byColumn.get(g.logicalName);y&&(g.choices=y)}return{logicalName:l.LogicalName,schemaName:(r=l.SchemaName)!==null&&r!==void 0?r:l.LogicalName,displayName:ji(l.DisplayName),...Yu(l.DisplayName)?{localizedDisplayName:Yu(l.DisplayName)}:{},entitySetName:(i=l.EntitySetName)!==null&&i!==void 0?i:"",primaryNameAttribute:(o=l.PrimaryNameAttribute)!==null&&o!==void 0?o:"",primaryIdAttribute:(a=l.PrimaryIdAttribute)!==null&&a!==void 0?a:"",...l.PrimaryImageAttribute?{primaryImageAttribute:l.PrimaryImageAttribute}:{},isCustomEntity:!!l.IsCustomEntity,...ji(l.Description)?{description:ji(l.Description)}:{},columnDetailComplete:p.complete&&m,columnDetailVersion:$r.COLUMN_DETAIL_VERSION,attributes:c,relationships:h}}$r.fetchEntityMetadataFromApi=zX;var yk=40;async function mE(e,t,n,r){var i,o;let a=[...new Set(r.filter(u=>u!==""))],s=[];for(let u=0;u<a.length;u+=yk){let l=a.slice(u,u+yk).map(f=>`LogicalName eq '${(0,oi.odataLiteral)(f)}'`).join(" or "),c=t+(0,oi.odataQuery)([["$select",n],["$filter",l]]),d=(0,vk.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 HX(e,t,n){return(await mE(e,`${Ri(t)}/Attributes`,"LogicalName,AttributeType,DisplayName",n)).map(i=>{var o;let a=Yu(i.DisplayName);return{logicalName:i.LogicalName,displayName:ji(i.DisplayName),...a?{localizedDisplayName:a}:{},attributeType:(o=i.AttributeType)!==null&&o!==void 0?o:"Unknown"}})}$r.readColumnHints=HX;async function KX(e,t,n){let i=(await mE(e,`${Ri(t)}/Attributes`,"LogicalName,AttributeType,DisplayName,IsCustomAttribute",n)).map(s=>{var u;return{logicalName:s.LogicalName,displayName:ji(s.DisplayName),attributeType:(u=s.AttributeType)!==null&&u!==void 0?u:"Unknown",isCustomAttribute:!!s.IsCustomAttribute}}),o=new Map(i.filter(s=>s.attributeType==="String").map(s=>[s.logicalName,s])),a=await mE(e,`${Ri(t)}/Attributes/Microsoft.Dynamics.CRM.StringAttributeMetadata`,"LogicalName,MaxLength",[...o.keys()]);for(let s of a){let u=o.get(s.LogicalName);u&&typeof s.MaxLength=="number"&&(u.maxLength=s.MaxLength)}return i}$r.readCheckColumns=KX;async function JX(e,t,n){let r=`/EntityDefinitions${(0,oi.odataQuery)([["$select","LogicalName,SchemaName,EntitySetName,DisplayName,IsCustomEntity"]])}`,i=await(0,bk.collectPages)(e,r,"findTables"),o=(t??"").toLowerCase(),a=i.filter(s=>!n?.customOnly||s.IsCustomEntity).map(s=>{var u,l;return{logicalName:s.LogicalName,schemaName:(u=s.SchemaName)!==null&&u!==void 0?u:s.LogicalName,displayName:ji(s.DisplayName),entitySetName:(l=s.EntitySetName)!==null&&l!==void 0?l:"",isCustom:!!s.IsCustomEntity}}).filter(s=>s.logicalName.toLowerCase().includes(o)||s.schemaName.toLowerCase().includes(o)||s.displayName.toLowerCase().includes(o));return typeof n?.top=="number"?a.slice(0,n.top):a}$r.findTables=JX;async function YX(e,t,n,r){let i=`${Ri(t)}/Attributes`+(0,oi.odataQuery)([["$select","LogicalName,SchemaName,DisplayName,AttributeType,IsCustomAttribute"]]),o=await(0,bk.collectPages)(e,i,"findColumns"),a=(n??"").toLowerCase(),s=o.map(u=>{var l,c;return{logicalName:u.LogicalName,schemaName:(l=u.SchemaName)!==null&&l!==void 0?l:u.LogicalName,displayName:ji(u.DisplayName),attributeType:(c=u.AttributeType)!==null&&c!==void 0?c:"Unknown",isCustom:!!u.IsCustomAttribute}}).filter(u=>u.logicalName.toLowerCase().includes(a)||u.schemaName.toLowerCase().includes(a)||u.displayName.toLowerCase().includes(a));return typeof r?.top=="number"?s.slice(0,r.top):s}$r.findColumns=YX});var yE=C(ai=>{"use strict";Object.defineProperty(ai,"__esModule",{value:!0});ai.renderTypeRegistrations=ai.buildGenPageLegacyEnums=ai.renderGenPageAuthoringTypes=ai.buildGenPageRuntimeTypes=ai.toDesignerEntity=ai.TABLE_LOGICAL_NAME=void 0;ai.TABLE_LOGICAL_NAME=/^[a-z_][a-z0-9_]*$/;function hE(e){return e.replace(/[\r\n\u2028\u2029]+/g," ")}var QX=new Set(["createdby","createdon","createdonbehalfby","importsequencenumber","modifiedby","modifiedon","modifiedonbehalfby","overriddencreatedon","ownerid","owningbusinessunit","owningteam","owninguser","timezoneruleversionnumber","utcconversiontimezonecode","versionnumber"]);function vg(e){var t;return((t=e.attributeTypeName)!==null&&t!==void 0?t:"").replace(/Type$/,"").toLowerCase()}function Ck(e){var t,n;let r=e.choices;if(!r||r.length===0)return;let i=vg(e)==="boolean",o={};for(let a of r)o[a.value]={text:(n=(t=a.invariantName)!==null&&t!==void 0?t:a.label)!==null&&n!==void 0?n:"",value:a.value,...!i&&a.color?{color:a.color}:{}};return o}function Ek(e,t){return e.logicalName<t.logicalName?-1:e.logicalName>t.logicalName?1:0}function Sk(e){return!QX.has(e.logicalName)&&(!e.attributeOf||vg(e)==="image")&&e.isValidForRead!==!1}var Ak=new Set(["boolean","picklist","multiselectpicklist","state","status"]);function Nk(e){let t=e.primaryImageAttribute,n=new Set([e.primaryIdAttribute,e.primaryNameAttribute,t,t?`${t}_url`:void 0,"processid","statecode","statuscode"].filter(o=>!!o)),r=e.attributes.filter(o=>n.has(o.logicalName)).sort(Ek),i=e.attributes.filter(o=>!n.has(o.logicalName)).sort(Ek);return[...r,...i]}function gE(e){var t;let n=[],r=new Set,i=Nk(e);for(let o of i){let a=vg(o),s=a==="image";Sk(o)&&(s&&o.attributeOf&&r.add(o.attributeOf),n.push({AttributeTypeName:a,IsReadOnly:!o.isValidForUpdate,LogicalName:o.logicalName,OptionSet:Ck(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:n.filter(o=>!r.has(o.LogicalName))}}ai.toDesignerEntity=gE;function _k(e,t="None"){let n={};for(let r of e)n[r.logicalName]=gE(r);return Ok(n,t)}ai.buildGenPageRuntimeTypes=_k;var Ik=`export interface TableRegistrations extends BaseTableRegistrations {+`,Tk=`export interface EnumRegistrations extends BaseEnumRegistrations {+`;function XX(e,t){return e.length>0?_k(e,t).text:Pk(`${Ik}}+`,`${Tk}}+`,"","")}ai.renderGenPageAuthoringTypes=XX;function ZX(e){let t=new Set;for(let r of e)for(let i of gE(r).Attributes)Ak.has(i.AttributeTypeName)&&t.add(`${r.logicalName}_${i.LogicalName}`);let n=new Map;for(let r of e)for(let i of Nk(r)){let o=`${r.logicalName}_${i.logicalName}`,a=Ck(i);if(Sk(i)||!Ak.has(vg(i))||!a||t.has(o)||n.has(o))continue;let s={name:o,runtime:{},labels:new Map};n.set(o,{declaration:Dk(o,a,!1,s),model:s})}return n}ai.buildGenPageLegacyEnums=ZX;function Ok(e,t="None"){var n,r;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",u=Ik,l=Tk,c="",d="";for(let f of o){s&&f.Description&&(c+=`// ${hE(f.Description)}`),c+=`export type ${f.LogicalName} = TableRow<{// Primary Key Columnreadonly ${f.PrimaryIdAttribute}: string,-`,l+=` "${f.LogicalName}": ${f.LogicalName},-`;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+=PE(g,m.OptionSet,a,b),u+=` "${f.LogicalName}-${m.LogicalName}": ${g},+`,u+=` "${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=(n=p.Targets)!==null&&n!==void 0?n:p.AttributeTypeName==="customer"?["account","contact"]:void 0;if(!g||g.length===0){h=!1;break}m=` // Foreign Key Column+ ${p.IsReadOnly||g.every(b=>!e[b])?" readonly ":""}_${p.LogicalName}_value: `;let y="";for(let b of g)y+=`${y.length===0?"":" | "}\`/${b}(\${string})\``;m+=`${y},+`;break}case"boolean":case"picklist":case"multiselectpicklist":case"state":case"status":{let g=`${f.LogicalName}_${p.LogicalName}`;m+=`: ${g},+`;let y=(r=i.get(g))!==null&&r!==void 0?r:{name:g,runtime:{},labels:new Map};i.set(g,y),d+=Dk(g,p.OptionSet,a,y),l+=` "${f.LogicalName}-${p.LogicalName}": ${g},`;break}case"image":c+=` // This is an image encoded as a base64 string-`,p+=`: string,-`;break;default:h=!1}h&&(s&&m.Description&&(c+=` // ${eh(m.Description)}-`),a&&m.MaxLength&&(c+=" // Maximum length: "+m.MaxLength+`-`),c+=` ${p}`)}c+=`}>-`}return l+=`}-`,u+=`}-`,{text:RE(l,u,c,d),enums:i}}vr.renderTypeRegistrations=OE;function PE(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: ${eh(a.color)}+`,m+=`: string,+`;break;default:h=!1}h&&(s&&p.Description&&(c+=` // ${hE(p.Description)}+`),a&&p.MaxLength&&(c+=" // Maximum length: "+p.MaxLength+`+`),c+=` ${m}`)}c+=`}>+`}return u+=`}+`,l+=`}+`,{text:Pk(u,l,c,d),enums:i}}ai.renderTypeRegistrations=Ok;function Dk(e,t,n,r){var i;let o=`const enum ${e} {+`;for(let a of Object.values(t??{}))if(a){n&&(o+=`${a.color?`// Option Color: ${hE(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 RE(e,t,r,n){return`+`,r.runtime[a.text]=a.value,r.runtime[String(a.value)]=a.text;let s=(i=r.labels.get(a.text))!==null&&i!==void 0?i:[];s.includes(a.value)||s.push(a.value),r.labels.set(a.text,s)}return`${o}}+`}function Pk(e,t,n,r){return`// ---------------- Type Definitions which can be imported from ./RuntimeTypes -------------------------${e}${t}-${r}${n}+${r}/*** Possible scalar values of a data column in a data row.@@ -345,23 +362,10 @@ export interface GeneratedComponentProps {dataApi: UxAgentDataApi;pageInput?: PageInput;}-`}});var $E=v(Wc=>{"use strict";Object.defineProperty(Wc,"__esModule",{value:!0});Wc.generateGenPageRuntimeTypes=void 0;var LE=rh(),Uo=Q(),kE=new Set(["None","ColorsDefaultsConstraints","ColorsDefaultsConstraintsDescriptions"]),Bo="generateGenPageRuntimeTypes";async function IV(e,t,r){let n=OV(t),i=PV(r),o=[];for(let a of n){let s=await e(a);if(s.columnDetailComplete!==!0)throw new Uo.SdkError("GENPAGE_DATA_SOURCE_INCOMPLETE",`${Bo}: 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,LE.renderGenPageAuthoringTypes)(o,i)}Wc.generateGenPageRuntimeTypes=IV;function OV(e){if(!Array.isArray(e))throw new Uo.InvalidArgumentError(`${Bo}: dataSources must be an array of table logical names`);let t=new Set;for(let r of e){if(typeof r!="string"||!LE.TABLE_LOGICAL_NAME.test(r))throw new Uo.InvalidArgumentError(`${Bo}: a data source must be a table logical name (lowercase, e.g. 'account'), got '${String(r)}'`);if(t.has(r))throw new Uo.InvalidArgumentError(`${Bo}: data source '${r}' is listed twice; a page's dataSources hold each table once`);t.add(r)}return[...t]}function PV(e){if(e===void 0)return"None";if(e===null||typeof e!="object"||Array.isArray(e))throw new Uo.InvalidArgumentError(`${Bo}: options must be an object`);let t=Object.keys(e).filter(n=>n!=="detail");if(t.length>0)throw new Uo.InvalidArgumentError(`${Bo}: unknown option '${t[0]}' (the only option is 'detail')`);let r=e.detail===void 0?"None":e.detail;if(typeof r!="string"||!kE.has(r))throw new Uo.InvalidArgumentError(`${Bo}: detail must be one of ${[...kE].map(n=>`'${n}'`).join(", ")}, got '${String(r)}'`);return r}});var qE=v(qo=>{"use strict";Object.defineProperty(qo,"__esModule",{value:!0});qo.getEnvironmentLanguages=qo.ENVIRONMENT_LANGUAGES_UNREADABLE_CODE=void 0;var RV=Q(),ME=ye();qo.ENVIRONMENT_LANGUAGES_UNREADABLE_CODE="ENVIRONMENT_LANGUAGES_UNREADABLE";var xE="/organizations?$select=languagecode",kV="/RetrieveProvisionedLanguages()",LV="/RetrieveAvailableLanguages()";function UE(e,t){return new RV.SdkError(qo.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 BE(e){return typeof e=="number"&&Number.isInteger(e)&&e>0}async function FE(e,t,r,n){let i=(0,ME.ensureSuccess)(await e.get(t),e.apiUrl(t)).body,o=i?.[r];if(!Array.isArray(o)||o.length===0||!o.every(BE))throw UE(n,`answered no list of language codes in '${r}'`);return[...new Set(o)]}async function $V(e){var t;let r=(0,ME.ensureSuccess)(await e.get(xE),e.apiUrl(xE)).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(!BE(i))throw UE("the organization read","did not answer one row with a language code");let o=await FE(e,kV,"RetrieveProvisionedLanguages","RetrieveProvisionedLanguages"),a=await FE(e,LV,"LocaleIds","RetrieveAvailableLanguages");return{baseLanguage:i,available:a,provisioned:o}}qo.getEnvironmentLanguages=$V});var Tl=v(it=>{"use strict";Object.defineProperty(it,"__esModule",{value:!0});it.projectConnectorOperationSchema=it.projectConnectorOperations=it.validateConnectorSwagger=it.CONNECTOR_SCHEMA_TOO_LARGE_CODE=it.CONNECTOR_OPERATION_NOT_FOUND_CODE=it.CONNECTOR_SWAGGER_UNSUPPORTED_CODE=it.CONNECTIVITY_RESPONSE_UNREADABLE_CODE=void 0;var _l=Q();it.CONNECTIVITY_RESPONSE_UNREADABLE_CODE="CONNECTIVITY_RESPONSE_UNREADABLE";it.CONNECTOR_SWAGGER_UNSUPPORTED_CODE="CONNECTOR_SWAGGER_UNSUPPORTED";it.CONNECTOR_OPERATION_NOT_FOUND_CODE="CONNECTOR_OPERATION_NOT_FOUND";it.CONNECTOR_SCHEMA_TOO_LARGE_CODE="CONNECTOR_SCHEMA_TOO_LARGE";var VE=64,GE=128,WE=2e5,zE=4e6,xV=new Set(["get","put","post","delete","patch","head","options"]),FV=new Set(["query","header","path","formData","body"]);function Zr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function wn(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function At(e){return e===void 0?"absent":e===null?"null":Array.isArray(e)?"an array":`a ${typeof e}`}function Ze(e){return e.length>80?`'${e.slice(0,80)}\u2026'`:`'${e}'`}function Le(e,t){return new _l.SdkError(it.CONNECTIVITY_RESPONSE_UNREADABLE_CODE,`The connector's swagger could not be read: ${e} ${t}. Nothing was skipped or assumed in its place.`)}function eo(e,t){return new _l.SdkError(it.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 MV(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||!wn(r,i))return{found:!1};r=r[i]}return{found:!0,value:r}}function oh(e,t,r){if(!t.startsWith("#/"))throw eo(r,`has a $ref that is not a local '#/\u2026' pointer (${Ze(t)})`);if(t.includes("%"))throw eo(r,`has a $ref with a percent-encoded character (${Ze(t)}), which is not decoded`);if(/~(?![01])/.test(t))throw Le(r,`has a $ref with a malformed escape (${Ze(t)}): a '~' not followed by 0 or 1`);let n=MV(e,t);if(!n.found)throw Le(r,`has a $ref that does not resolve (${Ze(t)})`);return n.value}function zc(e,t){if(wn(e,"$ref")){if(typeof e.$ref!="string")throw Le(t,`has a $ref that is ${At(e.$ref)}, not a string`);return e.$ref}}function UV(e,t,r){if(!Zr(t))throw Le(r,`is ${At(t)}, not a parameter object`);let n=t,i=zc(t,r);if(i!==void 0){let s=oh(e,i,r);if(!Zr(s))throw Le(r,`has a $ref (${Ze(i)}) that resolves to ${At(s)}, not a parameter object`);if(zc(s,`${r} \u2192 ${Ze(i)}`)!==void 0)throw eo(r,`has a $ref (${Ze(i)}) to a parameter that is itself a $ref`);n=s}if(typeof n.name!="string")throw Le(r,"has no string name");let o=n.in;if(typeof o!="string"||!FV.has(o))throw Le(r,`has an in that is ${typeof o=="string"?Ze(o):At(o)}, not one of query, header, path, formData or body`);if(wn(n,"required")&&typeof n.required!="boolean")throw Le(r,`has a required that is ${At(n.required)}, not a boolean`);let a=n["x-ms-visibility"];if(wn(n,"x-ms-visibility")&&typeof a!="string")throw Le(r,`has an x-ms-visibility that is ${At(a)}, not a string`);return{name:n.name,in:o,required:n.required===!0,internal:a==="internal"}}function nh(e){return`${e.in}:${e.name}`}function HE(e,t,r){if(!wn(t,"parameters"))return[];let n=t.parameters;if(!Array.isArray(n))throw Le(r,`has parameters that are ${At(n)}, not an array`);let i=new Set;return n.map((o,a)=>{let s=`${r} parameters[${a}]`,l=UV(e,o,s),u=nh(l);if(i.has(u))throw Le(s,`repeats the parameter ${Ze(l.name)} in ${Ze(l.in)}, which must be unique in its list`);return i.add(u),l})}function KE(e,t,r){let n=t.responses;if(!wn(n,"200"))return;let i=`${r} response 200`,o=n[200];if(!Zr(o))throw Le(i,`is ${At(o)}, not a response object`);let a=o,s=zc(o,i);if(s!==void 0){if(s.startsWith("#/")&&!/^#\/responses\/[^/]+$/.test(s))throw Le(i,`has a $ref (${Ze(s)}) that does not name a response ('#/responses/<name>')`);let l=oh(e,s,i);if(!Zr(l))throw Le(i,`has a $ref (${Ze(s)}) that resolves to ${At(l)}, not a response object`);if(zc(l,`${i} \u2192 ${Ze(s)}`)!==void 0)throw eo(i,`has a $ref (${Ze(s)}) to a response that is itself a $ref`);a=l}if(wn(a,"content"))throw eo(i,"is an OpenAPI 3 response (it has content), not a Swagger 2.0 one");if(wn(a,"schema")){if(!Zr(a.schema))throw Le(i,`has a schema that is ${At(a.schema)}, not an object`);return a.schema}}function jE(e,t,r){if(!wn(e,t))return;let n=e[t];if(typeof n!="string")throw Le(r,`has a ${t} that is ${At(n)}, not a string`);return n}function BV(e,t,r,n,i){if(!Zr(t))throw Le(r,`is ${At(t)}, not an operation object`);let o=t.operationId;if(typeof o!="string")throw Le(r,`has no string operationId (${At(o)})`);if(n.has(o))throw Le(r,`repeats the operationId ${Ze(o)}, which must be unique in the document`);n.add(o);let a=jE(t,"summary",r),s=jE(t,"description",r),l=HE(e,t,r);if(!Zr(t.responses))throw Le(r,`has no responses object (${At(t.responses)})`);return KE(e,t,r),{id:o,summary:a,description:s,node:t,where:r,parameters:l,pathParameters:i}}function ah(e){if(!Zr(e))throw Le("the document",`is ${At(e)}, not an object`);if(wn(e,"openapi"))throw eo("the document","is OpenAPI 3 (it has an openapi member), not Swagger 2.0");if(!wn(e,"swagger"))throw Le("the document","names no Swagger version");if(e.swagger!=="2.0")throw eo("the document",`declares swagger ${Ze(String(e.swagger))}, not 2.0`);let t=e.paths;if(!Zr(t))throw Le("the document",`has paths that are ${At(t)}, not an object`);let r=[],n=new Set;for(let i of Object.keys(t)){let o=t[i],a=`paths[${Ze(i)}]`;if(!Zr(o))throw Le(a,`is ${At(o)}, not a path item object`);let s=[];for(let l of Object.keys(o))if(xV.has(l.toLowerCase()))r.push(BV(e,o[l],`${a}.${l}`,n,s));else if(l==="parameters")for(let u of HE(e,o,a))s.push(u);else if(!l.startsWith("x-"))throw eo(a,`has a ${Ze(l)} member; a path item may hold only HTTP methods, parameters and x- extensions`)}return{document:e,operations:r}}function qV(e){ah(e)}it.validateConnectorSwagger=qV;var ih=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 _l.SdkError(it.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>WE)throw this.tooLarge(`more than ${WE} nodes`)}text(t){if(this.characters+=t,this.characters>zE)throw this.tooLarge(`more than ${zE} characters of strings and keys`)}checkDepth(t){if(t>GE)throw this.tooLarge(`nesting deeper than ${GE} 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(Zr(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>=VE)throw this.tooLarge(`a $ref chain of more than ${VE} references`);let n=oh(this.root,t,this.where);if(!Zr(n))throw Le(this.where,`has a schema $ref (${Ze(t)}) that resolves to ${At(n)}, not a schema object`);this.path.push(t);let i=this.visit(n,r);return this.path.pop(),i}};function VV(e){let{operations:t}=ah(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}})}}it.projectConnectorOperations=VV;function GV(e,t){if(typeof t!="string"||t==="")throw new _l.InvalidArgumentError("operationId must be a non-empty string.");let{document:r,operations:n}=ah(e),i=n.find(u=>u.id===t);if(!i)throw new _l.SdkError(it.CONNECTOR_OPERATION_NOT_FOUND_CODE,`The connector has no operation with the id ${Ze(t)} (ids are matched exactly, case included). List the connector\u2019s operations to see its ids.`);let o=new Set(i.parameters.map(nh)),a=[...i.parameters,...i.pathParameters.filter(u=>!o.has(nh(u)))].filter(u=>!u.internal).map(({name:u,required:c})=>({name:u,required:c})),s=KE(r,i.node,i.where),l=s===void 0?{}:new ih(r,`${i.where} (${Ze(i.id)})`).run(s);return{operation:i.id,parameters:a,response:l}}it.projectConnectorOperationSchema=GV});var Vo=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 Dl=Q(),WV=ye(),zV=Tl();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 wr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}J.isObject=wr;function Ga(e){return e===void 0?"absent":e===null?"null":Array.isArray(e)?"an array":`a ${typeof e}`}J.kindOf=Ga;function Wa(e,t=200){return e.length>t?`${e.slice(0,t)}\u2026`:e}J.bounded=Wa;function YE(e){try{let t=new URL(e);return{protocol:t.protocol,host:t.host,origin:t.origin}}catch{return}}J.parseUrl=YE;function jV(e,t){return e.protocol===t.protocol&&e.host.toLowerCase()===t.host.toLowerCase()}J.sameOrigin=jV;var HV=/^[a-z0-9-]+\.crm(\d*)\.dynamics\.com$/,KV=/^[a-z0-9-]+\.crmtest\.dynamics\.com$/;function JV(e){let t=YE(e),r=t?t.host.toLowerCase():"";if(KV.test(r))return"Test";let n=HV.exec(r);return n&&n[1]!=="9"?"Public":"Unsupported"}J.connectivityCloudOf=JV;function Gn(e,t){return new Dl.SdkError(zV.CONNECTIVITY_RESPONSE_UNREADABLE_CODE,`${e} could not be read: ${t}. Nothing was skipped or assumed in its place.`)}J.unreadable=Gn;function YV(e){return encodeURIComponent(`environment eq '${e.replace(/'/g,"''")}'`)}J.environmentFilter=YV;function QV(e){if(typeof e=="string"&&e.length>0)return Wa(e,500);if(wr(e)){let t=wr(e.error)?e.error.message:void 0;for(let r of[t,e.Message,e.message])if(typeof r=="string")return Wa(r,500)}return"request failed"}J.messageOf=QV;function QE(e){return wr(e)&&wr(e.error)?e.error.code:void 0}J.errorCodeOf=QE;function XV(e){if(wr(e)&&wr(e.error)&&wr(e.error.innererror))return e.error.innererror.code}function ZV(e,t,r){let n=[],i=QE(t);typeof i=="string"&&i.length>0&&n.push(Wa(i,80));let o=XV(t);typeof o=="string"&&o.length>0&&n.push(Wa(o,80));let a=n.length>0?` (${n.join("; ")})`:"";return(0,Dl.attachCause)(new Dl.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=ZV;J.CONNECTOR_PREFIX="/providers/Microsoft.PowerApps/apis/";var e4=/^[A-Za-z0-9_.-]{1,128}$/,t4=new Set(["shared_logicflows","shared_powerflows","shared_pqogenericconnector"]);function r4(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(e4.test(r)&&!/^\.{1,2}$/.test(r))return r}throw new Dl.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"?`'${Wa(e,80)}'`:Ga(e)}.`)}J.connectorShortName=r4;function n4(e,t,r){let n=`Connection row ${t}`;if(!wr(e))throw Gn(n,`it is ${Ga(e)}, not an object`);let i=e.properties;if(!wr(i))throw Gn(n,`its properties are ${Ga(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 Gn(n,`its apiId is not '${J.CONNECTOR_PREFIX}<connector>'`);let a=o.slice(J.CONNECTOR_PREFIX.length);if(a===""||a.includes("/"))throw Gn(n,"its apiId names no single connector");if(t4.has(a.toLowerCase()))return;let s=e.name;if(typeof s!="string"||s==="")throw Gn(n,"it has no name");let l=i.environment,u=wr(l)?l.name:void 0;if(typeof u!="string"||u.toLowerCase()!==r.toLowerCase())throw Gn(n,"it is not a connection of this environment (properties.environment.name)");let c=i.displayName;if(typeof c!="string")throw Gn(n,`its displayName is ${Ga(c)}, not a string`);let d=i.statuses;if(!Array.isArray(d))throw Gn(n,`its statuses are ${Ga(d)}, not an array`);return{connectionId:s,displayName:c,connectorId:o,connectorName:a,statuses:d.map(f=>{let m=wr(f)?f.status:void 0;if(typeof m!="string")throw Gn(n,"one of its statuses has no string status");return m})}}J.readConnection=n4;var JE="/RetrieveCurrentOrganization(AccessType=@p1)?@p1=Microsoft.Dynamics.CRM.EndpointAccessType'Default'";async function i4(e){let t=(0,WV.ensureSuccess)(await e.get(JE),e.apiUrl(JE)).body,r=wr(t)?t.Detail:void 0,n=wr(r)?r.EnvironmentId:void 0;if(typeof n!="string"||n==="")throw new Dl.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=i4});var iA=v(Cr=>{"use strict";Object.defineProperty(Cr,"__esModule",{value:!0});Cr.ConnectivityApi=Cr.CONNECTIVITY_UNAUTHORIZED_CODE=Cr.CONNECTIVITY_ROUTE_DECOMMISSIONED_CODE=Cr.CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE=Cr.CONNECTIVITY_CLOUD_UNSUPPORTED_CODE=Cr.CONNECTIVITY_NOT_CONFIGURED_CODE=void 0;var zt=Q(),o4=ye(),Hc=Tl(),Ol=Vo(),Pl=Vo();Object.defineProperty(Cr,"CONNECTIVITY_NOT_CONFIGURED_CODE",{enumerable:!0,get:function(){return Pl.CONNECTIVITY_NOT_CONFIGURED_CODE}});Object.defineProperty(Cr,"CONNECTIVITY_CLOUD_UNSUPPORTED_CODE",{enumerable:!0,get:function(){return Pl.CONNECTIVITY_CLOUD_UNSUPPORTED_CODE}});Object.defineProperty(Cr,"CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE",{enumerable:!0,get:function(){return Pl.CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE}});Object.defineProperty(Cr,"CONNECTIVITY_ROUTE_DECOMMISSIONED_CODE",{enumerable:!0,get:function(){return Pl.CONNECTIVITY_ROUTE_DECOMMISSIONED_CODE}});Object.defineProperty(Cr,"CONNECTIVITY_UNAUTHORIZED_CODE",{enumerable:!0,get:function(){return Pl.CONNECTIVITY_UNAUTHORIZED_CODE}});var XE="2016-11-01",a4="2021-04-01",s4="https://api.bap.microsoft.com",l4="https://test.api.bap.microsoft.com",u4=/^[a-z0-9-]+\.crm(\d*)\.dynamics\.com$/,c4=/^[a-z0-9-]+\.crmtest\.dynamics\.com$/,ZE="/RetrieveCurrentOrganization(AccessType=@p1)?@p1=Microsoft.Dynamics.CRM.EndpointAccessType'Default'",vi="/providers/Microsoft.PowerApps/apis/",d4=/^[A-Za-z0-9_.-]{1,128}$/,f4=new Set(["shared_logicflows","shared_powerflows","shared_pqogenericconnector"]),p4="ServiceDecommissioned";function ft(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function to(e){return e===void 0?"absent":e===null?"null":Array.isArray(e)?"an array":`a ${typeof e}`}function Wn(e,t=200){return e.length>t?`${e.slice(0,t)}\u2026`:e}function Il(e){try{let t=new URL(e);return{protocol:t.protocol,host:t.host,origin:t.origin}}catch{return}}function eA(e,t){return e.protocol===t.protocol&&e.host.toLowerCase()===t.host.toLowerCase()}function m4(e){return/^[a-z0-9][a-z0-9.-]*$/.test(e)&&(e==="api.powerapps.com"||e.endsWith(".api.powerapps.com"))}function en(e,t){return new zt.SdkError(Hc.CONNECTIVITY_RESPONSE_UNREADABLE_CODE,`${e} could not be read: ${t}. Nothing was skipped or assumed in its place.`)}function jc(e){return new zt.SdkError(Ol.CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE,`The environment of this org could not be verified: ${e}. The Power Apps service was not asked about it.`)}function tA(e){return encodeURIComponent(`environment eq '${e.replace(/'/g,"''")}'`)}function rA(e){if(typeof e=="string"&&e.length>0)return Wn(e,500);if(ft(e)){let t=ft(e.error)?e.error.message:void 0;for(let r of[t,e.Message,e.message])if(typeof r=="string")return Wn(r,500)}return"request failed"}function h4(e){return ft(e)&&ft(e.error)?e.error.code:void 0}function nA(e){if(typeof e=="string"){let r=e.slice(0,vi.length).toLowerCase()===vi.toLowerCase()?e.slice(vi.length):e;if(d4.test(r)&&!/^\.{1,2}$/.test(r))return r}throw new zt.InvalidArgumentError(`connector must be a connector's short name ('shared_office365users') or its full API id ('${vi}shared_office365users'); got ${typeof e=="string"?`'${Wn(e,80)}'`:to(e)}.`)}function g4(e,t,r){let n=`Connection row ${t}`;if(!ft(e))throw en(n,`it is ${to(e)}, not an object`);let i=e.properties;if(!ft(i))throw en(n,`its properties are ${to(i)}, not an object`);let o=i.apiId;if(typeof o!="string"||o.slice(0,vi.length).toLowerCase()!==vi.toLowerCase())throw en(n,`its apiId is not '${vi}<connector>'`);let a=o.slice(vi.length);if(a===""||a.includes("/"))throw en(n,"its apiId names no single connector");if(f4.has(a.toLowerCase()))return;let s=e.name;if(typeof s!="string"||s==="")throw en(n,"it has no name");let l=i.environment,u=ft(l)?l.name:void 0;if(typeof u!="string"||u.toLowerCase()!==r.toLowerCase())throw en(n,"it is not a connection of this environment (properties.environment.name)");let c=i.displayName;if(typeof c!="string")throw en(n,`its displayName is ${to(c)}, not a string`);let d=i.statuses;if(!Array.isArray(d))throw en(n,`its statuses are ${to(d)}, not an array`);return{connectionId:s,displayName:c,connectorId:o,connectorName:a,statuses:d.map(f=>{let m=ft(f)?f.status:void 0;if(typeof m!="string")throw en(n,"one of its statuses has no string status");return m})}}var sh=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=${tA(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 en(u,`its value is ${to(d)}, not an array`);for(let m of d){let p=g4(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 en(u,`its nextLink is ${f===""?"an empty string":to(f)}, not a non-empty string`);if(i.has(f))throw new zt.InvalidArgumentError(`listConnections: aborting pagination \u2014 the server returned a repeated nextLink ('${Wn(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=nA(t);return(0,Hc.projectConnectorOperations)(await this.swagger(r,n))}async getConnectorOperationSchema(t,r){let n=this.requireService(),i=nA(t);if(typeof r!="string"||r==="")throw new zt.InvalidArgumentError("operationId must be a non-empty string.");return(0,Hc.projectConnectorOperationSchema)(await this.swagger(n,i),r)}requireService(){if(!this.service)throw new zt.SdkError(Ol.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=${a4}`,o=(await this.send(t,i,!1)).body,a=ft(o)?o.properties:void 0,s=ft(o)?o.name:void 0;if(typeof s!="string"||s.toLowerCase()!==n.toLowerCase())throw jc(`BAP's environment row is not the one named '${Wn(n,80)}' (its name)`);let l=ft(a)&&ft(a.linkedEnvironmentMetadata)?a.linkedEnvironmentMetadata.instanceUrl:void 0,u=typeof l=="string"?Il(l):void 0,c=Il(this.instanceUrl);if(!u||!c||!eA(u,c))throw jc("BAP's row is not linked to this org (its linkedEnvironmentMetadata.instanceUrl is another origin)");let d=ft(a)?a.runtimeEndpoints:void 0,f=ft(d)?d["microsoft.PowerApps"]:void 0,m=typeof f=="string"?Il(f):void 0;if(!m||m.protocol!=="https:"||!m4(m.host.toLowerCase()))throw jc("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=Il(this.instanceUrl),r=t?t.host.toLowerCase():"",n=u4.exec(r);if(n&&n[1]!=="9")return s4;if(c4.test(r))return l4;throw new zt.SdkError(Ol.CONNECTIVITY_CLOUD_UNSUPPORTED_CODE,`The org's host is not one of the clouds this reads in (${t?`'${Wn(t.host,80)}'`:`'${Wn(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,o4.ensureSuccess)(await this.org.get(ZE),this.org.apiUrl(ZE)).body,r=ft(t)?t.Detail:void 0,n=ft(r)?r.EnvironmentId:void 0;if(typeof n!="string"||n==="")throw jc("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}${vi}${i}?api-version=${XE}&$filter=${tA(n.id)}`,a=(await this.send(t,o,!0)).body,s=ft(a)?a.properties:void 0,l=ft(s)?s.swagger:void 0;if(!ft(l))throw en(`The connector '${Wn(r,80)}'`,`its properties.swagger is ${to(l)}, not an object`);return(0,Hc.validateConnectorSwagger)(l),l}assertSameOrigin(t,r){let n=Il(t);if(!n)throw new zt.InvalidArgumentError(`Refusing to follow a malformed absolute URL: '${Wn(t)}'`);if(!eA(n,r))throw new zt.InvalidArgumentError(`Refusing to follow a cross-origin link ('${Wn(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 zt.ConnectionError&&typeof o.statusCode=="number"&&o.statusCode>0?this.mapNon2xx(r,o.statusCode,void 0,n,o):o instanceof zt.SdkError?o:new zt.ConnectionError(r,0,o instanceof Error?o.message:String(o),o)}if(!i||typeof i.status!="number")throw new zt.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 zt.ConnectionError(t,r,rA(n),n);return i&&r===410&&h4(n)===p4?(0,zt.attachCause)(new zt.SdkError(Ol.CONNECTIVITY_ROUTE_DECOMMISSIONED_CODE,`The Power Apps API this reads through is decommissioned for this environment: ${rA(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,Ol.connectivityUnauthorized)(r,n,a):a}};Cr.ConnectivityApi=sh});var fh=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 Go=Q(),M=Vo(),y4=/^[A-Za-z0-9_.-]{1,128}$/,Wo=/^\.{1,2}$/,b4="shared_sharepointonline",v4=/^[0-9]{1,9}$/,w4=/^[A-Za-z0-9._~-]+$/,C4=/^\/apim\/([A-Za-z0-9._-]+)\/?$/,E4=/^\/connectors\/runtime\/invoke\/scalegroups\/([A-Za-z0-9._-]+)\/(scaleunits|shards)\/([A-Za-z0-9._-]+)\/apis\/([A-Za-z0-9._-]+)\/connections\/?$/,A4=/^[A-Za-z0-9._~!'()*-]$/,S4=/^[0-9A-Fa-f]{2}$/;function wi(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Rl(e){return typeof e=="string"?`'${(0,M.bounded)(e,80)}'`:(0,M.kindOf)(e)}function lh(e,t){return new Go.SdkError(M.CONNECTOR_NOT_TABULAR_CODE,`The connector '${(0,M.bounded)(e,80)}' has no tables: ${t}.`)}function Kc(e,t){return new Go.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 N4(e){if(typeof e=="string"&&y4.test(e)&&!Wo.test(e))return e;throw new Go.InvalidArgumentError(`connectionId must be a connection's name (letters, digits, '_', '.', '-'; at most 128; not '.' or '..'); got ${Rl(e)}.`)}function _4(e){if(e!=null){if(typeof e=="string"&&e!==""&&e.split(",").find(r=>r===""||Wo.test(r))===void 0)return e;throw new Go.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 ${Rl(e)}.`)}}function T4(e){if(typeof e=="string"&&e!==""&&!Wo.test(e))return e;throw new Go.InvalidArgumentError(`table must be a non-empty string other than '.' and '..'; got ${Rl(e)}.`)}function aA(e,t,r){return{short:(0,M.connectorShortName)(e),connectionId:N4(t),dataset:_4(r)}}Me.checkListTablesArguments=aA;function D4(e,t,r,n){return{...aA(e,t,r),table:T4(n)}}Me.checkTableSchemaArguments=D4;function I4(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(!wi(n,"interfaces"))throw lh(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(!wi(i,"CDPTabular1"))throw lh(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(!v4.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=O4(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 lh(t,"its CDPTabular1 interface has no Production revision");return s.revision}Me.tabularRevision=I4;function O4(e){if(typeof e!="string")return;let t=e.replace(/^\/+/,"").replace(/\/+$/,"");return t===""?"":t.split("/").every(i=>w4.test(i)&&!Wo.test(i))?t:void 0}function P4(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 Kc(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 Kc(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:C4.exec(l);if(!c||Wo.test(c[1]))throw Kc(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:E4.exec(l);if(!u||[u[1],u[3],u[4]].some(c=>Wo.test(c)))throw Kc(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=P4;function R4(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 ${Rl(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 ${Rl(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=R4;function oA(e){return encodeURIComponent(e).replace(/[!'()*]/g,t=>`%${t.charCodeAt(0).toString(16).toUpperCase()}`)}function k4(e){if(e==="")return!1;for(let t=0;t<e.length;t+=1)if(e[t]==="%"){if(!S4.test(e.slice(t+1,t+3)))return!1;t+=2}else if(!A4.test(e[t]))return!1;return!0}function sA(e,t){let r,n,i;try{r=oA(e),n=oA(r),i=decodeURIComponent(n)}catch{throw new Go.InvalidArgumentError(`${t} is not well-formed Unicode (it has a lone surrogate), so it cannot be sent.`)}if(!k4(n)||Wo.test(n)||i!==r)throw new Go.InvalidArgumentError(`${t} cannot be sent as one path segment.`);return n}function dh(e){return e.split(",").map((t,r)=>sA(t,`dataset part ${r}`)).join(",")}Me.encodeDataset=dh;function lA(e){return sA(e,"table")}Me.encodeTable=lA;function L4(e,t){if(t===void 0)return"/tables";let r=e.toLowerCase()===b4?"allTables":"tables";return`/datasets/${dh(t)}/${r}`}Me.tablesSuffix=L4;function $4(e,t){return`/$metadata.json${e===void 0?"":`/datasets/${dh(e)}`}/tables/${lA(t)}`}Me.tableSchemaSuffix=$4;function za(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 x4(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(za(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=za(e,"value"),i=n.found?n:za(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)=>F4(n,i))}}Me.projectConnectorTables=x4;function F4(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=za(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=za(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=za(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 uh(e,t,r){if(!wi(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 ch(e,t,r){if(!wi(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 M4(e,t){var r,n;if(wi(e,"$ref"))throw(0,M.unreadable)(t,"it is a $ref, whose type is not guessed");let i=ch(e,"type",t),o=ch(e,"format",t),a=(r=i??o)!==null&&r!==void 0?r:"object";if(!wi(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(wi(s,"$ref"))throw(0,M.unreadable)(t,"its items are a $ref, whose type is not guessed");return`${a}<${(n=ch(s,"type",`${t} items`))!==null&&n!==void 0?n:"object"}>`}function U4(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=uh(e,"items","items"),i=uh(e,"schema","schema"),o=i?uh(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&&wi(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&&wi(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:M4(f,d),required:s.has(c.toLowerCase())}});return{table:t,columns:u}}Me.projectConnectorTableSchema=U4});var uA=v(Jc=>{"use strict";Object.defineProperty(Jc,"__esModule",{value:!0});Jc.PowerPlatformApiDiscovery=void 0;var ph=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}`)}}};Jc.PowerPlatformApiDiscovery=ph});var cA=v(Yc=>{"use strict";Object.defineProperty(Yc,"__esModule",{value:!0});Yc.PowerPlatformApiDiscovery=void 0;var B4=uA();Object.defineProperty(Yc,"PowerPlatformApiDiscovery",{enumerable:!0,get:function(){return B4.PowerPlatformApiDiscovery}})});var mA=v(ro=>{"use strict";Object.defineProperty(ro,"__esModule",{value:!0});ro.platformTokenAudience=ro.platformEnvironment=ro.platformClusterOf=void 0;var dA=cA(),fA=Q(),pA=Vo(),q4=/^[a-z0-9-]+\.crm(\d*)\.dynamics\.com$/,V4=/^[a-z0-9-]+\.crmtest\.dynamics\.com$/,G4=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,W4=/^default-/i;function mh(e,t=80){return e.length>t?`${e.slice(0,t)}\u2026`:e}function z4(e){try{return new URL(e).host.toLowerCase()}catch{return}}function j4(e){let t=z4(e);if(t){if(V4.test(t))return{cloud:"Test",category:"test"};let r=q4.exec(t);if(r&&r[1]!=="9")return{cloud:"Public",category:"prod"}}throw new fA.SdkError(pA.CONNECTIVITY_CLOUD_UNSUPPORTED_CODE,`The Power Platform API route is built for the Test and Public clouds; this org (${t?`'${mh(t)}'`:`'${mh(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.`)}ro.platformClusterOf=j4;function H4(e,t){let r=W4.test(e)?e.slice(8):e;if(!G4.test(r))throw new fA.SdkError(pA.CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE,`The environment of this org could not be verified: its name ('${mh(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 dA.PowerPlatformApiDiscovery(t).getEnvironmentEndpoint(e)}`,guid:r.toLowerCase()}}ro.platformEnvironment=H4;function K4(e){return new dA.PowerPlatformApiDiscovery(e).getTokenAudience()}ro.platformTokenAudience=K4});var gA=v(ja=>{"use strict";Object.defineProperty(ja,"__esModule",{value:!0});ja.PlatformConnectivityApi=ja.assertTabularCloud=void 0;var Cn=Q(),hh=Tl(),me=Vo(),hA=mA(),Ci=fh(),gh="1";function yh(e){let t=(0,me.connectivityCloudOf)(e);if(t!=="Test"&&t!=="Public")throw new Cn.SdkError(me.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.")}ja.assertTabularCloud=yh;var bh=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=${gh}`,[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,me.unreadable)(s,`its value is ${(0,me.kindOf)(u)}, not an array`);for(let d of u){let f=(0,me.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,me.unreadable)(s,`its nextLink is ${c===""?"an empty string":(0,me.kindOf)(c)}, not a non-empty string`);if(n.has(c))throw new Cn.InvalidArgumentError(`listConnections: aborting pagination \u2014 the server returned a repeated nextLink ('${(0,me.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,me.connectorShortName)(t);return(0,hh.projectConnectorOperations)(await this.swagger(r))}async getConnectorOperationSchema(t,r){let n=(0,me.connectorShortName)(t);if(typeof r!="string"||r==="")throw new Cn.InvalidArgumentError("operationId must be a non-empty string.");return(0,hh.projectConnectorOperationSchema)(await this.swagger(n),r)}async listConnectorTables(t,r,n){yh(this.instanceUrl);let i=(0,Ci.checkListTablesArguments)(t,r,n),o=(0,Ci.tablesSuffix)(i.short,i.dataset);return(0,Ci.projectConnectorTables)(await this.invokeTabular(i,o))}async getConnectorTableSchema(t,r,n,i){yh(this.instanceUrl);let o=(0,Ci.checkTableSchemaArguments)(t,r,n,i),a=(0,Ci.tableSchemaSuffix)(o.dataset,o.table);return(0,Ci.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,Ci.tabularRevision)(o,t.short),s=(0,Ci.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,me.environmentFilter)(i.name)}&api-version=${gh}`,u=(await this.send(this.client,"GET",l,[401,403])).body,c=(0,Ci.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 Cn.SdkError(me.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,hA.platformClusterOf)(this.instanceUrl),n=await(0,me.readEnvironmentName)(this.org),{origin:i,guid:o}=(0,hA.platformEnvironment)(n,r),a=(0,me.parseUrl)(i);if(!a)throw(0,me.unreadable)("The Power Platform API origin",`'${(0,me.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,me.environmentFilter)(r.name)}&api-version=${gh}`,i=(await this.send(this.client,"GET",n,[401,403])).body,o=(0,me.isObject)(i)?i.name:void 0;if(!(0,me.isObject)(i)||typeof o!="string"||o.toLowerCase()!==t.toLowerCase())throw(0,me.unreadable)(`The connector '${(0,me.bounded)(t,80)}'`,`the record's name is ${typeof o=="string"?`'${(0,me.bounded)(o,80)}'`:(0,me.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,me.isObject)(n)?n.swagger:void 0;if(!(0,me.isObject)(i))throw(0,me.unreadable)(`The connector '${(0,me.bounded)(t,80)}'`,`its properties.swagger is ${(0,me.kindOf)(i)}, not an object`);return(0,hh.validateConnectorSwagger)(i),i})}assertSameOrigin(t,r){let n=(0,me.parseUrl)(t);if(!n)throw new Cn.InvalidArgumentError(`Refusing to follow a malformed absolute URL: '${(0,me.bounded)(t)}'`);if(!(0,me.sameOrigin)(n,r))throw new Cn.InvalidArgumentError(`Refusing to follow a cross-origin link ('${(0,me.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 Cn.ConnectionError&&typeof s.statusCode=="number"&&s.statusCode>0?this.non2xx(n,s.statusCode,void 0,i,s):s instanceof Cn.SdkError?s:new Cn.ConnectionError(n,0,s instanceof Error?s.message:String(s),s)}if(!a||typeof a.status!="number")throw new Cn.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 Cn.ConnectionError(t,r,(0,me.messageOf)(n),n);return i.includes(r)?(0,me.connectivityUnauthorized)(r,n,a):a}};ja.PlatformConnectivityApi=bh});var bA=v(Xc=>{"use strict";Object.defineProperty(Xc,"__esModule",{value:!0});Xc.ConnectivityRouter=void 0;var vh=Q(),J4=iA(),Qc=Vo(),yA=fh(),wh=gA(),Ch=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,wh.assertTabularCloud)(this.instanceUrl),(0,yA.checkListTablesArguments)(t,r,n),this.tabularRoute().listConnectorTables(t,r,n)}async getConnectorTableSchema(t,r,n,i){return(0,wh.assertTabularCloud)(this.instanceUrl),(0,yA.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 wh.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 vh.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 vh.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 J4.ConnectivityApi(this.org,this.instanceUrl,r);throw new vh.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.")}};Xc.ConnectivityRouter=Ch});var Ha=v(Ei=>{"use strict";function Y4(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 Ah(e,t){return t===void 0&&(t=Object),t&&typeof t.freeze=="function"?t.freeze(e):e}function Q4(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 vA=Ah({HTML:"text/html",isHTML:function(e){return e===vA.HTML},XML_APPLICATION:"application/xml",XML_TEXT:"text/xml",XML_XHTML_APPLICATION:"application/xhtml+xml",XML_SVG_IMAGE:"image/svg+xml"}),wA=Ah({HTML:"http://www.w3.org/1999/xhtml",isHTML:function(e){return e===wA.HTML},SVG:"http://www.w3.org/2000/svg",XML:"http://www.w3.org/XML/1998/namespace",XMLNS:"http://www.w3.org/2000/xmlns/"}),Zc=/[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]/,Eh=new RegExp("[\\-\\.0-9"+Zc.source.slice(1,-1)+"\\u00B7\\u0300-\\u036F\\u203F-\\u2040]"),X4=new RegExp("^"+Zc.source+Eh.source+"*(?::"+Zc.source+Eh.source+"*)?$");Ei.assign=Q4;Ei.find=Y4;Ei.freeze=Ah;Ei.MIME_TYPE=vA;Ei.NAMESPACE=wA;Ei.nameStartChar=Zc;Ei.nameChar=Eh;Ei.tagNamePattern=X4});var $h=v(_i=>{var Sh=Ha(),zn=Sh.find,Ll=Sh.NAMESPACE,Ka=Sh.tagNamePattern;function Z4(e){return e!==""}function eG(e){return e?e.split(/[\t\n\f\r ]+/).filter(Z4):[]}function tG(e,t){return e.hasOwnProperty(t)||(e[t]=!0),e}function CA(e){if(!e)return[];var t=eG(e);return Object.keys(t.reduce(tG,{}))}function rG(e){return function(t){return e&&e.indexOf(t)!==-1}}function xl(e,t){for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r])}function Ar(e,t){var r=e.prototype;if(!(r instanceof t)){let i=function(){};var n=i;i.prototype=t.prototype,i=new i,xl(r,i),e.prototype=r=i}r.constructor!=e&&(typeof e!="function"&&console.error("unknown Class:"+e),r.constructor=e)}var Sr={},tn=Sr.ELEMENT_NODE=1,Ja=Sr.ATTRIBUTE_NODE=2,kl=Sr.TEXT_NODE=3,IA=Sr.CDATA_SECTION_NODE=4,OA=Sr.ENTITY_REFERENCE_NODE=5,nG=Sr.ENTITY_NODE=6,Nh=Sr.PROCESSING_INSTRUCTION_NODE=7,_h=Sr.COMMENT_NODE=8,PA=Sr.DOCUMENT_NODE=9,RA=Sr.DOCUMENT_TYPE_NODE=10,Ai=Sr.DOCUMENT_FRAGMENT_NODE=11,iG=Sr.NOTATION_NODE=12,jt={},Nt={},qse=jt.INDEX_SIZE_ERR=(Nt[1]="Index size error",1),Vse=jt.DOMSTRING_SIZE_ERR=(Nt[2]="DOMString size error",2),Er=jt.HIERARCHY_REQUEST_ERR=(Nt[3]="Hierarchy request error",3),Gse=jt.WRONG_DOCUMENT_ERR=(Nt[4]="Wrong document",4),EA=jt.INVALID_CHARACTER_ERR=(Nt[5]="Invalid character",5),Wse=jt.NO_DATA_ALLOWED_ERR=(Nt[6]="No data allowed",6),zse=jt.NO_MODIFICATION_ALLOWED_ERR=(Nt[7]="No modification allowed",7),kA=jt.NOT_FOUND_ERR=(Nt[8]="Not found",8),jse=jt.NOT_SUPPORTED_ERR=(Nt[9]="Not supported",9),AA=jt.INUSE_ATTRIBUTE_ERR=(Nt[10]="Attribute in use",10),En=jt.INVALID_STATE_ERR=(Nt[11]="Invalid state",11),Hse=jt.SYNTAX_ERR=(Nt[12]="Syntax error",12),Kse=jt.INVALID_MODIFICATION_ERR=(Nt[13]="Invalid modification",13),Jse=jt.NAMESPACE_ERR=(Nt[14]="Invalid namespace",14),Yse=jt.INVALID_ACCESS_ERR=(Nt[15]="Invalid access",15);function he(e,t){if(t instanceof Error)var r=t;else r=this,Error.call(this,Nt[e]),this.message=Nt[e],Error.captureStackTrace&&Error.captureStackTrace(this,he);return r.code=e,t&&(this.message=this.message+": "+t),r}he.prototype=Error.prototype;xl(jt,he);function Si(){}Si.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++)Lh(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 Ya(e,t){this._node=e,this._refresh=t,Th(this)}function Th(e){var t=e._node._inc||e._node.ownerDocument._inc;if(e._inc!==t){var r=e._refresh(e._node);if(jA(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];xl(r,e),e._inc=t}}Ya.prototype.item=function(e){return Th(this),this[e]||null};Ar(Ya,Si);function td(){this._nameIndex=Object.create(null)}function LA(e,t){for(var r=e.length;r--;)if(e[r]===t)return r}function oG(e,t){e._nameIndex[t.nodeName]=t}function $A(e,t){e._nameIndex[t.nodeName]===t&&delete e._nameIndex[t.nodeName]}function SA(e,t,r,n){if(n?(t[LA(t,n)]=r,$A(t,n)):t[t.length++]=r,oG(t,r),e){r.ownerElement=e;var i=e.ownerDocument;i&&(n&&MA(i,e,n),aG(i,e,r))}}function NA(e,t,r){var n=LA(t,r);if(n>=0){for(var i=t.length-1;n<i;)t[n]=t[++n];if(t.length=i,$A(t,r),e){var o=e.ownerDocument;o&&(MA(o,e,r),r.ownerElement=null)}}else throw new he(kA,new Error(e.tagName+"@"+r))}td.prototype={length:0,item:Si.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 he(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 he(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 NA(this._ownerElement,this,t),t},removeNamedItemNS:function(e,t){var r=this.getNamedItemNS(e,t);return NA(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 xA(){}xA.prototype={hasFeature:function(e,t){return!0},createDocument:function(e,t,r){var n=new Fl;if(n.implementation=this,n.childNodes=new Si,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 ad;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 nd(this,e,t)},replaceChild:function(e,t){nd(this,e,t,BA),t&&this.removeChild(t)},removeChild:function(e){return UA(this,e)},appendChild:function(e){return this.insertBefore(e,null)},hasChildNodes:function(){return this.firstChild!=null},cloneNode:function(e){return zA(this.ownerDocument||this,this,e)},normalize:function(){St(this,null,{enter:function(e){for(var t=e.firstChild;t;){var r=t.nextSibling;if(r!==null&&r.nodeType===kl&&t.nodeType===kl){for(var n=[],i=r;i!==null&&i.nodeType===kl;)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("")),od(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==Ja?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==Ja?t.ownerDocument:t.parentNode}return null},isDefaultNamespace:function(e){var t=this.lookupPrefix(e);return t==null}};function FA(e){return e=="<"&&"<"||e==">"&&">"||e=="&"&&"&"||e=='"'&&"""||"&#"+e.charCodeAt()+";"}xl(Sr,De);xl(Sr,De.prototype);function rd(e,t){return St(e,null,{enter:function(r){return t(r)?St.STOP:!0}})===St.STOP}function St(e,t,r){for(var n=[{node:e,context:t,phase:St.ENTER}];n.length>0;){var i=n.pop();if(i.phase===St.ENTER){var o=r.enter(i.node,i.context);if(o===St.STOP)return St.STOP;if(n.push({node:i.node,context:o,phase:St.EXIT}),o==null)continue;for(var a=i.node.lastChild;a;)n.push({node:a,context:o,phase:St.ENTER}),a=a.previousSibling}else r.exit&&r.exit(i.node,i.context)}}St.STOP=Symbol("walkDOM.STOP");St.ENTER=0;St.EXIT=1;function Fl(){this.ownerDocument=this}function aG(e,t,r){e&&e._inc++;var n=r.namespaceURI;n===Ll.XMLNS&&(t._nsMap[r.prefix?r.localName:""]=r.value)}function MA(e,t,r,n){e&&e._inc++;var i=r.namespaceURI;i===Ll.XMLNS&&delete t._nsMap[r.prefix?r.localName:""]}function od(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 UA(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,od(e.ownerDocument,e),t}function sG(e){return e&&(e.nodeType===De.DOCUMENT_NODE||e.nodeType===De.DOCUMENT_FRAGMENT_NODE||e.nodeType===De.ELEMENT_NODE)}function lG(e){return e&&(jn(e)||Dh(e)||Ni(e)||e.nodeType===De.DOCUMENT_FRAGMENT_NODE||e.nodeType===De.COMMENT_NODE||e.nodeType===De.PROCESSING_INSTRUCTION_NODE)}function Ni(e){return e&&e.nodeType===De.DOCUMENT_TYPE_NODE}function jn(e){return e&&e.nodeType===De.ELEMENT_NODE}function Dh(e){return e&&e.nodeType===De.TEXT_NODE}function _A(e,t){var r=e.childNodes||[];if(zn(r,jn)||Ni(t))return!1;var n=zn(r,Ni);return!(t&&n&&r.indexOf(n)>r.indexOf(t))}function TA(e,t){var r=e.childNodes||[];function n(o){return jn(o)&&o!==t}if(zn(r,n))return!1;var i=zn(r,Ni);return!(t&&i&&r.indexOf(i)>r.indexOf(t))}function uG(e,t,r){if(!sG(e))throw new he(Er,"Unexpected parent node type "+e.nodeType);if(r&&r.parentNode!==e)throw new he(kA,"child not in parent");if(!lG(t)||Ni(t)&&e.nodeType!==De.DOCUMENT_NODE)throw new he(Er,"Unexpected node type "+t.nodeType+" for parent node type "+e.nodeType)}function cG(e,t,r){var n=e.childNodes||[],i=t.childNodes||[];if(t.nodeType===De.DOCUMENT_FRAGMENT_NODE){var o=i.filter(jn);if(o.length>1||zn(i,Dh))throw new he(Er,"More than one element or text in fragment");if(o.length===1&&!_A(e,r))throw new he(Er,"Element in fragment can not be inserted before doctype")}if(jn(t)&&!_A(e,r))throw new he(Er,"Only one element can be added and only after doctype");if(Ni(t)){if(zn(n,Ni))throw new he(Er,"Only one doctype is allowed");var a=zn(n,jn);if(r&&n.indexOf(a)<n.indexOf(r))throw new he(Er,"Doctype can only be inserted before an element");if(!r&&a)throw new he(Er,"Doctype can not be appended since element is present")}}function BA(e,t,r){var n=e.childNodes||[],i=t.childNodes||[];if(t.nodeType===De.DOCUMENT_FRAGMENT_NODE){var o=i.filter(jn);if(o.length>1||zn(i,Dh))throw new he(Er,"More than one element or text in fragment");if(o.length===1&&!TA(e,r))throw new he(Er,"Element in fragment can not be inserted before doctype")}if(jn(t)&&!TA(e,r))throw new he(Er,"Only one element can be added and only after doctype");if(Ni(t)){let l=function(u){return Ni(u)&&u!==r};var s=l;if(zn(n,l))throw new he(Er,"Only one doctype is allowed");var a=zn(n,jn);if(r&&n.indexOf(a)<n.indexOf(r))throw new he(Er,"Doctype can only be inserted before an element")}}function nd(e,t,r,n){uG(e,t,r),e.nodeType===De.DOCUMENT_NODE&&(n||cG)(e,t,r);var i=t.parentNode;if(i&&i.removeChild(t),t.nodeType===Ai){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;$l(o,l)}while(o!==a&&(o=o.nextSibling));return od(e.ownerDocument||e,e),t.nodeType==Ai&&(t.firstChild=t.lastChild=null),t}function $l(e,t){if(e.ownerDocument!==t){if(e.ownerDocument=t,e.nodeType===tn&&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;)$l(i,t),i=i.nextSibling}}function dG(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,od(e.ownerDocument,e,t);var r=e.ownerDocument||e;return $l(t,r),t}Fl.prototype={nodeName:"#document",nodeType:PA,doctype:null,documentElement:null,_inc:1,insertBefore:function(e,t){if(e.nodeType==Ai){for(var r=e.firstChild;r;){var n=r.nextSibling;this.insertBefore(r,t),r=n}return e}return nd(this,e,t),$l(e,this),this.documentElement===null&&e.nodeType===tn&&(this.documentElement=e),e},removeChild:function(e){return this.documentElement==e&&(this.documentElement=null),UA(this,e)},replaceChild:function(e,t){nd(this,e,t,BA),$l(e,this),t&&this.removeChild(t),jn(e)&&(this.documentElement=e)},importNode:function(e,t){return fG(this,e,t)},getElementById:function(e){var t=null;return rd(this.documentElement,function(r){if(r.nodeType==tn&&r.getAttribute("id")==e)return t=r,!0}),t},getElementsByClassName:function(e){var t=CA(e);return new Ya(this,function(r){var n=[];return t.length>0&&rd(r.documentElement,function(i){if(i!==r&&i.nodeType===tn){var o=i.getAttribute("class");if(o){var a=e===o;if(!a){var s=CA(o);a=t.every(rG(s))}a&&n.push(i)}}}),n})},createElement:function(e){var t=new zo;t.ownerDocument=this,t.nodeName=e,t.tagName=e,t.localName=e,t.childNodes=new Si;var r=t.attributes=new td;return r._ownerElement=t,t},createDocumentFragment:function(){var e=new sd;return e.ownerDocument=this,e.childNodes=new Si,e},createTextNode:function(e){var t=new Ih;return t.ownerDocument=this,t.appendData(e),t},createComment:function(e){var t=new Oh;return t.ownerDocument=this,t.appendData(e),t},createCDATASection:function(e){if(e.indexOf("]]>")!==-1)throw new he(EA,'data contains "]]>"');var t=new Ph;return t.ownerDocument=this,t.appendData(e),t},createProcessingInstruction:function(e,t){var r=new kh;return r.ownerDocument=this,r.tagName=r.nodeName=r.target=e,r.nodeValue=r.data=t,r},createAttribute:function(e){var t=new id;return t.ownerDocument=this,t.name=e,t.nodeName=e,t.localName=e,t.specified=!0,t},createEntityReference:function(e){if(!Ka.test(e))throw new he(EA,'not a valid xml name "'+e+'"');var t=new Rh;return t.ownerDocument=this,t.nodeName=e,t},createElementNS:function(e,t){var r=new zo,n=t.split(":"),i=r.attributes=new td;return r.childNodes=new Si,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 id,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}};Ar(Fl,De);function zo(){this._nsMap={}}zo.prototype={nodeType:tn,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===Ai?this.insertBefore(e,null):dG(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 Ya(this,function(t){var r=[];return rd(t,function(n){n!==t&&n.nodeType==tn&&(e==="*"||n.tagName==e)&&r.push(n)}),r})},getElementsByTagNameNS:function(e,t){return new Ya(this,function(r){var n=[];return rd(r,function(i){i!==r&&i.nodeType===tn&&(e==="*"||i.namespaceURI===e)&&(t==="*"||i.localName==t)&&n.push(i)}),n})}};Fl.prototype.getElementsByTagName=zo.prototype.getElementsByTagName;Fl.prototype.getElementsByTagNameNS=zo.prototype.getElementsByTagNameNS;Ar(zo,De);function id(){}id.prototype.nodeType=Ja;Ar(id,De);function Ml(){}Ml.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(Nt[Er])},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}};Ar(Ml,De);function Ih(){}Ih.prototype={nodeName:"#text",nodeType:kl,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}};Ar(Ih,Ml);function Oh(){}Oh.prototype={nodeName:"#comment",nodeType:_h};Ar(Oh,Ml);function Ph(){}Ph.prototype={nodeName:"#cdata-section",nodeType:IA};Ar(Ph,Ml);function ad(){}ad.prototype.nodeType=RA;Ar(ad,De);function qA(){}qA.prototype.nodeType=iG;Ar(qA,De);function VA(){}VA.prototype.nodeType=nG;Ar(VA,De);function Rh(){}Rh.prototype.nodeType=OA;Ar(Rh,De);function sd(){}sd.prototype.nodeName="#document-fragment";sd.prototype.nodeType=Ai;Ar(sd,De);function kh(){}kh.prototype.nodeType=Nh;Ar(kh,De);function GA(){}GA.prototype.serializeToString=function(e,t,r,n){return WA.call(e,t,r,n)};De.prototype.toString=WA;function WA(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 Lh(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===Ll.XML||i===Ll.XMLNS)return!1;for(var o=r.length;o--;){var a=r[o];if(a.prefix===n)return a.namespace!==i}return!0}function ed(e,t,r,n){if(n&&!Ka.test(t))throw new he(En,'The attribute name "'+t+'" is not a valid XML QName');e.push(" ",t,'="',r.replace(/[<>&"\t\n\r]/g,FA),'"')}function Lh(e,t,r,n,i,o){i||(i=[]),St(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 tn:var c=a.attributes,d=c.length,f=a.tagName;u=Ll.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&&!Ka.test(m))throw new he(En,'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(DA(S,u,w)){var O=S.prefix||"",k=S.namespaceURI;ed(t,O?"xmlns:"+O:"xmlns",k,o),w.push({prefix:O,namespace:k})}var I=n?n(S):S;I&&(typeof I=="string"?t.push(I):ed(t,I.name,I.value,o))}if(f===m&&DA(a,u,w)){var D=a.prefix||"",k=a.namespaceURI;ed(t,D?"xmlns:"+D:"xmlns",k,o),w.push({prefix:D,namespace:k})}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):Lh(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 PA:case Ai:return{ns:l.slice(),isHTML:u,tag:null};case Ja:return ed(t,a.name,a.value,o),null;case kl:return t.push(a.data.replace(/[<&>]/g,FA)),null;case IA:if(o&&a.data.indexOf("]]>")!==-1)throw new he(En,'The CDATASection data contains "]]>"');return t.push("<![CDATA[",a.data.replace(/]]>/g,"]]]]><![CDATA[>"),"]]>"),null;case _h:if(o&&a.data.indexOf("-->")!==-1)throw new he(En,'The comment node data contains "-->"');return t.push("<!--",a.data,"-->"),null;case RA:if(o){if(!Ka.test(a.name))throw new he(En,'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 he(En,"DocumentType publicId is not a valid PubidLiteral");if(a.systemId&&!/^("[^"]*"|'[^']*')$/.test(a.systemId))throw new he(En,"DocumentType systemId is not a valid SystemLiteral");if(a.internalSubset&&a.internalSubset.indexOf("]>")!==-1)throw new he(En,'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 Oe=a.internalSubset;Oe&&t.push(" [",Oe,"]"),t.push(">")}return null;case Nh:if(o){if(!Ka.test(a.target)||a.target.indexOf(":")!==-1||a.target.toLowerCase()==="xml")throw new he(En,'The processing instruction target "'+a.target+'" is not a valid XML NCName or is reserved');if(a.data.indexOf("?>")!==-1)throw new he(En,'The ProcessingInstruction data contains "?>"')}return t.push("<?",a.target," ",a.data,"?>"),null;case OA:if(o&&!Ka.test(a.nodeName))throw new he(En,'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 fG(e,t,r){var n;return St(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===Ja||r;return s?a:null}}),n}function zA(e,t,r){var n;return St(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 Si),a.ownerDocument=e;var u=r;switch(a.nodeType){case tn:var c=i.attributes,d=a.attributes=new td,f=c.length;d._ownerElement=a;for(var m=0;m<f;m++)a.setAttributeNode(zA(e,c.item(m),!0));break;case Ja:u=!0}return o!==null?o.appendChild(a):n=a,u?a:null}}),n}function jA(e,t,r){e[t]=r}try{Object.defineProperty&&(Object.defineProperty(Ya.prototype,"length",{get:function(){return Th(this),this.$$length}}),Object.defineProperty(De.prototype,"textContent",{get:function(){if(this.nodeType===tn||this.nodeType===Ai){var e=[];return St(this,null,{enter:function(t){if(t.nodeType===tn||t.nodeType===Ai)return!0;if(t.nodeType===Nh||t.nodeType===_h)return null;e.push(t.nodeValue)}}),e.join("")}return this.nodeValue},set:function(e){switch(this.nodeType){case tn:case Ai: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}}}),jA=function(e,t,r){e["$$"+t]=r})}catch{}_i.DocumentType=ad;_i.DOMException=he;_i.DOMImplementation=xA;_i.Element=zo;_i.Node=De;_i.NodeList=Si;_i.walkDOM=St;_i.XMLSerializer=GA});var KA=v(Ul=>{"use strict";var HA=Ha().freeze;Ul.XML_ENTITIES=HA({amp:"&",apos:"'",gt:">",lt:"<",quot:'"'});Ul.HTML_ENTITIES=HA({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"});Ul.entityMap=Ul.HTML_ENTITIES});var ZA=v(Fh=>{var Vl=Ha().NAMESPACE,xh=Ha().tagNamePattern,Qa=0,no=1,Xa=2,Bl=3,Za=4,es=5,ql=6,ld=7;function ts(e,t){this.message=e,this.locator=t,Error.captureStackTrace&&Error.captureStackTrace(this,ts)}ts.prototype=new Error;ts.prototype.name=ts.name;function QA(){}QA.prototype={parse:function(e,t,r){var n=this.domBuilder;n.startDocument(),yG(t,t={}),pG(e,t,r,n,this.errorHandler),n.endDocument()}};function pG(e,t,r,n,i){function o(se){if(se>65535){se-=65536;var We=55296+(se>>10),ir=56320+(se&1023);return String.fromCharCode(We,ir)}else return String.fromCharCode(se)}function a(se){var We=se.slice(1,-1);return Object.hasOwnProperty.call(r,We)?r[We]:We.charAt(0)==="#"?o(parseInt(We.substr(1).replace("x","0x"))):(i.error("entity not found:"+se),se)}function s(se){if(se>h){var We=e.substring(h,se).replace(/&#?\w+;/g,a);f&&l(h),n.characters(We,0,se-h),h=se}}function l(se,We){for(;se>=c&&(We=d.exec(e));)u=We.index,c=u+We[0].length,f.lineNumber++;f.columnNumber=se-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)&&xh.test(C.split(/[ \t\n\r]/)[0])&&i.error('end tag name is followed by whitespace and trailing content: "'+C+'"');var O=S.localNSMap,k=S.tagName==C,I=k||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);k||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=vG(e,g,n);break;case"!":f&&l(g),K=bG(e,g,n,i);break;default:f&&l(g);var P=new XA,x=m[m.length-1].currentNSMap,K=mG(e,g,P,x,a,i),Oe=P.length;if(!P.closed&&gG(e,K,P.tagName,p)&&(P.closed=!0,r.nbsp||i.warning("unclosed xml attribute")),f&&Oe){for(var Vt=JA(f,{}),Xe=0;Xe<Oe;Xe++){var Ne=P[Xe];l(Ne.offset),Ne.locator=JA(f,{})}n.locator=Vt,YA(P,n,x)&&m.push(P),n.locator=f}else YA(P,n,x)&&m.push(P);Vl.isHTML(P.uri)&&!P.closed?K=hG(e,K,P.tagName,a,n):K++}}catch(se){if(se instanceof ts)throw se;i.error("element parse error: "+se),K=-1}K>h?h=K:s(Math.max(g,h)+1)}}function JA(e,t){return t.lineNumber=e.lineNumber,t.columnNumber=e.columnNumber,t}function mG(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=Qa;;){var d=e.charAt(u);if(c===Qa&&d==="<")throw new Error("unexpected < in tag name: "+e.slice(t,u));switch(d){case"=":if(c===no)s=e.slice(t,u),c=Bl;else if(c===Xa)c=Bl;else throw new Error("attribute equal must after attrName");break;case"'":case'"':if(c===Bl||c===no)if(c===no&&(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=es;else throw new Error("attribute value no end '"+d+"' match");else if(c==Za)l=e.slice(t,u),a(s,l,t),o.warning('attribute "'+s+'" missed start quot('+d+")!!"),t=u+1,c=es;else throw new Error('attribute value must after "="');break;case"/":switch(c){case Qa:r.setTagName(e.slice(t,u));case es:case ql:case ld:c=ld,r.closed=!0;case Za:case no:break;case Xa:r.closed=!0;break;default:throw new Error("attribute invalid close char('/')")}break;case"":return o.error("unexpected end of input"),c==Qa&&r.setTagName(e.slice(t,u)),u;case">":switch(c){case Qa:r.setTagName(e.slice(t,u));case es:case ql:case ld:break;case Za:case no:l=e.slice(t,u),l.slice(-1)==="/"&&(r.closed=!0,l=l.slice(0,-1));case Xa:c===Xa&&(l=s),c==Za?(o.warning('attribute "'+l+'" missed quot(")!'),a(s,l,t)):((!Vl.isHTML(n[""])||!l.match(/^(?:disabled|checked|selected)$/i))&&o.warning('attribute "'+l+'" missed value!! "'+l+'" instead!!'),a(l,l,t));break;case Bl:throw new Error("attribute value missed!!")}return u;case"\x80":d=" ";default:if(d<=" ")switch(c){case Qa:r.setTagName(e.slice(t,u)),c=ql;break;case no:s=e.slice(t,u),c=Xa;break;case Za:var l=e.slice(t,u);o.warning('attribute "'+l+'" missed quot(")!!'),a(s,l,t);case es:c=ql;break}else switch(c){case Xa:var f=r.tagName;(!Vl.isHTML(n[""])||!s.match(/^(?:disabled|checked|selected)$/i))&&o.warning('attribute "'+s+'" missed value!! "'+s+'" instead2!!'),a(s,s,t),t=u,c=no;break;case es:o.warning('attribute space is required"'+s+'"!!');case ql:c=no,t=u;break;case Bl:c=Za,t=u;break;case ld:throw new Error("elements closed character '/' and '>' must be connected to")}}u++}}function YA(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=Vl.XMLNS,t.startPrefixMapping(c,s))}for(var d=e.length;d--;){o=e[d];var l=o.prefix;l&&(l==="xml"&&(o.uri=Vl.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 hG(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 gG(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 yG(e,t){for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r])}function bG(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=wG(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 vG(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(!xh.test(e))throw new Error("invalid tagName:"+e);this.tagName=e},addValue:function(e,t,r){if(!xh.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 wG(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}Fh.XMLReader=QA;Fh.ParseError=ts});var aS=v(cd=>{var CG=Ha(),EG=$h(),eS=KA(),nS=ZA(),AG=EG.DOMImplementation,tS=CG.NAMESPACE,SG=nS.ParseError,NG=nS.XMLReader;function iS(e){return e.replace(/\r[\n\u0085]/g,`-`).replace(/[\r\u0085\u2028]/g,`-`)}function oS(e){this.options=e||{locator:{}}}oS.prototype.parseFromString=function(e,t){var r=this.options,n=new NG,i=r.domBuilder||new Gl,o=r.errorHandler,a=r.locator,s=r.xmlns||{},l=/\/x?html?$/.test(t),u=l?eS.HTML_ENTITIES:eS.XML_ENTITIES;a&&i.setDocumentLocator(a),n.errorHandler=_G(o,i,a),n.domBuilder=r.domBuilder||i,l&&(s[""]=tS.HTML),s.xml=s.xml||tS.XML;var c=r.normalizeLineEndings||iS;return e&&typeof e=="string"?n.parse(c(e),s,u):n.errorHandler.error("invalid doc source"),i.doc};function _G(e,t,r){if(!e){if(t instanceof Gl)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+Mh(r))}||function(){}}return o("warning"),o("error"),o("fatalError"),n}function Gl(){this.cdata=!1}function rs(e,t){t.lineNumber=e.lineNumber,t.columnNumber=e.columnNumber}Gl.prototype={startDocument:function(){this.doc=new AG().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;ud(this,o),this.currentElement=o,this.locator&&rs(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&&rs(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&&rs(this.locator,r),ud(this,r)},ignorableWhitespace:function(e,t,r){},characters:function(e,t,r){if(e=rS.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&&rs(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=rS.apply(this,arguments);var n=this.doc.createComment(e);this.locator&&rs(this.locator,n),ud(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&&rs(this.locator,i),ud(this,i),this.doc.doctype=i}},warning:function(e){console.warn("[xmldom warning] "+e,Mh(this.locator))},error:function(e){console.error("[xmldom error] "+e,Mh(this.locator))},fatalError:function(e){throw new SG(e,this.locator)}};function Mh(e){if(e)return`-@`+(e.systemId||"")+"#[line:"+e.lineNumber+",col:"+e.columnNumber+"]"}function rS(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){Gl.prototype[e]=function(){return null}});function ud(e,t){e.currentElement?e.currentElement.appendChild(t):e.doc.appendChild(t)}cd.__DOMHandler=Gl;cd.normalizeLineEndings=iS;cd.DOMParser=oS});var ns=v(dd=>{var sS=$h();dd.DOMImplementation=sS.DOMImplementation;dd.XMLSerializer=sS.XMLSerializer;dd.DOMParser=aS().DOMParser});var uS={};Jr(uS,{CCFControlConstants:()=>lS,CCFPropertyConstants:()=>Bh,CustomControlDataType:()=>F,CustomControlNames:()=>Ti,DefaultControlNameKeys:()=>Uh,ICCModeEnum:()=>io,JSONParametersConstants:()=>qh,LookUpType:()=>fd,ManifestXMLConstants:()=>Ht,NumberType:()=>pd,Usage:()=>jo});var lS,Bh,qh,Ht,F,Uh,Ti,io,jo,fd,pd,Ho=L(()=>{"use strict";lS={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"},Bh={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"},qh={GroupDefinition:"GroupDefinition"},Ht={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"})(Uh||(Uh={}));(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"})(Ti||(Ti={}));(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"})(io||(io={}));(function(e){e[e.Bound=0]="Bound",e[e.Input=1]="Input",e[e.Output=2]="Output"})(jo||(jo={}));fd=[F.LookupCustomer,F.LookupOwner,F.LookupPartyList,F.LookupRegarding,F.LookupSimple],pd=[F.WholeNone,F.WholeDuration,F.WholeLanguage,F.WholeTimeZone,F.FP,F.Decimal]});var is,ar,Wl=L(()=>{"use strict";is=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}},ar=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 cS={};Jr(cS,{AttributeDataSourceType:()=>zl,AttributeDataSourceTypeMask:()=>md,AttributePrecisionSource:()=>jl,EntityAttributeDataSourceType:()=>Ko,EntityAttributeDateTimeBehavior:()=>Wh,EntityAttributeImeMode:()=>Gh,EntityAttributePrecisionSource:()=>zh,EntityAttributeRequiredLevel:()=>oo,EntityAttributeType:()=>$,EntityAttributeTypeFormat:()=>W,EntityMetadataLookUpBase:()=>Di,EntityResxKeyLookUp:()=>hd,SourceTypeMask:()=>Vh});var Di,$,W,oo,Ko,Vh,zl,md,Gh,Wh,zh,jl,hd,os=L(()=>{"use strict";Wl();Di=class{name;constructor(t){this.name=t}toString(){return this.name}getName(){return this.name}getDisplayNameResourceKey(){return hd.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={}));oo=class extends Di{constructor(t){super(t)}static get None(){return"None"}static get SystemRequired(){return"SystemRequired"}static get ApplicationRequired(){return"ApplicationRequired"}static get Recommended(){return"Recommended"}},Ko=class e extends Di{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?zl.Persistent:parseInt(zl[this.name])}},Vh=class e extends Di{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(md[this.name])}};(function(e){e[e.Persistent=0]="Persistent",e[e.Calculated=1]="Calculated",e[e.Rollup=2]="Rollup"})(zl||(zl={}));(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"})(md||(md={}));Gh=class e extends Di{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"}},Wh=class e extends Di{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"}},zh=class e extends Di{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?jl.Currency:parseInt(jl[this.name])}};(function(e){e[e.Attribute=0]="Attribute",e[e.Organization=1]="Organization",e[e.Currency=2]="Currency"})(jl||(jl={}));hd=class e{static resourceKeyMap=e.initResourceKeyMap();static initResourceKeyMap(){let t=new is;return t.add($.TwoOptions,"SystemCustomization.type.bit.label"),t.add($.Customer,"SystemCustomization.type.customer.label"),t.add($.CustomerType,"SystemCustomization.type.customer.label"),t.add($.DateTime,"SystemCustomization.type.datetime.label"),t.add($.DecimalNumber,"SystemCustomization.type.decimal.label"),t.add($.FloatingPointNumber,"SystemCustomization.type.float.label"),t.add($.WholeNumber,"SystemCustomization.type.int.label"),t.add($.LookupType,"SystemCustomization.type.lookup.label"),t.add($.Lookup,"SystemCustomization.type.lookup.label"),t.add($.MultipleLineofText,"SystemCustomization.type.ntext.label"),t.add($.Currency,"SystemCustomization.type.money.label"),t.add($.Owner,"SystemCustomization.type.owner.label"),t.add($.OwnerType,"SystemCustomization.type.owner.label"),t.add($.PartyList,"SystemCustomization.type.partylist.label"),t.add($.PartyListType,"SystemCustomization.type.partylist.label"),t.add($.OptionSet,"SystemCustomization.type.picklist.label"),t.add($.State,"SystemCustomization.type.state.label"),t.add($.Status,"SystemCustomization.type.status.label"),t.add($.SingleLineofText,"SystemCustomization.type.nvarchar.label"),t.add($.UniqueIdentifier,"SystemCustomization.type.uniqueidentifier.label"),t.add($.UniqueIdentifierType,"SystemCustomization.type.uniqueidentifiertype.label"),t.add($.CalendarRulesType,"SystemCustomization.type.calendarrules.label"),t.add($.VirtualType,"SystemCustomization.type.virtual.label"),t.add($.BigInt,"SystemCustomization.type.bigint.label"),t.add($.ManagedPropertyType,"SystemCustomization.type.managedproperty.label"),t.add($.EntityNameType,"SystemCustomization.type.entityname.label"),t.add($.Image,"SystemCustomization.type.image.label"),t.add($.MultiSelectOptionSet,"SystemCustomization.type.multiselectpicklist.label"),t.add($.PrimaryNameAttributeType,"SystemCustomization.type.primaryname.label"),t.add($.LookupType,"SystemCustomization.type.lookuptype.label"),t.add($.Subject,"SystemCustomization.type.subject.label"),t.add(W.Email,"SystemCustomization.String.Format.email"),t.add(W.Text,"SystemCustomization.String.Format.text"),t.add(W.TextArea,"SystemCustomization.String.Format.textarea"),t.add(W.Url,"SystemCustomization.String.Format.url"),t.add(W.TickerSymbol,"SystemCustomization.String.Format.tickersymbol"),t.add(W.PhoneticGuide,"SystemCustomization.String.Format.phoneticguide"),t.add(W.VersionNumber,"SystemCustomization.String.Format.versionnumber"),t.add(W.Phone,"SystemCustomization.String.Format.phone"),t.add(W.None,"SystemCustomization.Integer.Format."),t.add(W.Duration,"SystemCustomization.Integer.Format.duration"),t.add(W.TimeZone,"SystemCustomization.Integer.Format.timezone"),t.add(W.Language,"SystemCustomization.Integer.Format.language"),t.add(W.Locale,"SystemCustomization.Integer.Format.language"),t.add(W.DateOnly,"SystemCustomization.DateTime.Format.date"),t.add(W.DateAndTime,"SystemCustomization.DateTime.Format.datetime"),t.add(W.Regarding,"SystemCustomization.Lookup.Format.regarding"),t.add(Ko.Persistent,"SystemCustomization.String.Source.persistent"),t.add(Ko.Calculated,"SystemCustomization.String.Source.calculated"),t.add(Ko.Rollup,"SystemCustomization.String.Source.rollup"),t.add(Ko.None,"SystemCustomization.String.Source.none"),t}static getDisplayNameResourceKey(t){return e.resourceKeyMap.getValue(t)}}});var Hh=v(ot=>{"use strict";Object.defineProperty(ot,"__esModule",{value:!0});ot.parsePcfManifest=ot.parseControlElement=ot.parseManifestRoot=ot.firstLevel=ot.attr=ot.elementChildren=ot.manifestTypesForColumn=ot.DEFAULT_TYPE_GROUPS=void 0;var TG=ns(),H=(Ho(),Br(uS)),we=(os(),Br(cS));ot.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 DG="Phone";function IG(e,t,r){switch(e){case we.EntityAttributeType.TwoOptions:return[H.CustomControlDataType.TwoOptions,H.CustomControlDataType.Boolean];case we.EntityAttributeType.Customer:case we.EntityAttributeType.CustomerType:return[H.CustomControlDataType.LookupCustomer];case we.EntityAttributeType.DateTime:return t===we.EntityAttributeTypeFormat.DateAndTime?[H.CustomControlDataType.DateAndTimeDateAndTime]:[H.CustomControlDataType.DateAndTimeDateOnly];case we.EntityAttributeType.DecimalNumber:return[H.CustomControlDataType.Decimal];case we.EntityAttributeType.FloatingPointNumber:return[H.CustomControlDataType.FP];case we.EntityAttributeType.File:return[H.CustomControlDataType.File];case we.EntityAttributeType.Image:return[H.CustomControlDataType.Image];case we.EntityAttributeType.WholeNumber:return t===we.EntityAttributeTypeFormat.Duration?[H.CustomControlDataType.WholeDuration]:t===we.EntityAttributeTypeFormat.Language?[H.CustomControlDataType.WholeLanguage]:t===we.EntityAttributeTypeFormat.TimeZone?[H.CustomControlDataType.WholeTimeZone]:[H.CustomControlDataType.WholeNone];case we.EntityAttributeType.LookupType:case we.EntityAttributeType.Lookup:return t===we.EntityAttributeTypeFormat.Regarding?[H.CustomControlDataType.LookupRegarding]:[H.CustomControlDataType.LookupSimple];case we.EntityAttributeType.MultipleLineofText:return[H.CustomControlDataType.Multiple];case we.EntityAttributeType.Currency:return[H.CustomControlDataType.Currency];case we.EntityAttributeType.Owner:case we.EntityAttributeType.OwnerType:return[H.CustomControlDataType.LookupOwner];case we.EntityAttributeType.PartyList:case we.EntityAttributeType.PartyListType:return[H.CustomControlDataType.LookupPartyList];case we.EntityAttributeType.Status:case we.EntityAttributeType.OptionSet:return[H.CustomControlDataType.OptionSet];case we.EntityAttributeType.SingleLineofText:switch(t){case we.EntityAttributeTypeFormat.Email:return[H.CustomControlDataType.SingleLineEmail];case we.EntityAttributeTypeFormat.Phone:return[H.CustomControlDataType.SingleLinePhone];case we.EntityAttributeTypeFormat.Text:return r===DG?[H.CustomControlDataType.SingleLinePhone]:[H.CustomControlDataType.SingleLineText];case we.EntityAttributeTypeFormat.TextArea:return[H.CustomControlDataType.SingleLineTextArea];case we.EntityAttributeTypeFormat.TickerSymbol:return[H.CustomControlDataType.SingleLineTickerSymbol];case we.EntityAttributeTypeFormat.Url:return[H.CustomControlDataType.SingleLineURL];default:return[H.CustomControlDataType.SingleLineText]}case we.EntityAttributeType.MultiSelectOptionSet:return[H.CustomControlDataType.MultiSelectOptionSet];default:return null}}ot.manifestTypesForColumn=IG;function jh(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}ot.elementChildren=jh;function An(e,t){return e.hasAttribute(t)?e.getAttribute(t):null}ot.attr=An;function Hn(e,...t){return jh(e).filter(r=>t.includes(r.tagName))}ot.firstLevel=Hn;function OG(e){let t=new Map;for(let r of Hn(e,"type-group"))t.set(String(An(r,"name")),Hn(r,"type").map(n=>String(n.textContent)));for(let[r,n]of t)t.set(r,n.sort());return t}function PG(e){let t=e.getElementsByTagName("AvailableOn")[0];if(!t)return{web:!0,phone:!0,tablet:!0};let r=new Set(jh(t).map(n=>n.tagName));return{web:r.has("web"),phone:r.has("phone"),tablet:r.has("tablet")}}var RG={input:"input",bound:"bound",output:"output"};function kG(e,t,r){let n=An(e,"usage"),i=n!==null&&RG[n]||"input",o=An(e,"default-value"),a=Hn(e,"value").map(m=>{let p={name:An(m,"name"),value:String(m.textContent),isDefault:An(m,"default")==="true"};return p.isDefault&&(o=p.value),p}),s=An(e,"of-type-group"),l=s!==null?t.get(s):void 0,u=s!==null&&Object.prototype.hasOwnProperty.call(ot.DEFAULT_TYPE_GROUPS,s)?ot.DEFAULT_TYPE_GROUPS[s]:void 0,c=l?[...l]:u?[...u]:[],d=An(e,"of-type"),f=d!==null?d:c.length>0?c[0]:null;return{name:An(e,"name"),usage:i,ofType:d,typeGroupName:s,ofTypeGroup:c,defaultType:f||void 0,required:An(e,"required")==="true",hidden:An(e,"hidden")==="true",defaultValue:o,enumValues:a,isPrimary:r&&i==="bound"}}function dS(e){var t;let r=[],n=a=>s=>r.push(`${a}: ${s}`),i=new TG.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}ot.parseManifestRoot=dS;function fS(e){let t=Hn(dS(e),"control")[0];if(!t)throw new Error("the control manifest has no <control> element");return t}ot.parseControlElement=fS;function LG(e){let t=fS(e),r=OG(t),n=Hn(t,"data-set"),i=Hn(t,"property"),o=Hn(t,"groups"),a=[],s=!1;for(let u of i){let c=kG(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=>Hn(u,"group").some(c=>Hn(c,"data-set","property").length>0)));return{properties:a,hasDataset:n.length>0,hasGroups:o.length>0,isBound:l,availableOn:PG(t)}}ot.parsePcfManifest=LG});var mS=v(ss=>{"use strict";Object.defineProperty(ss,"__esModule",{value:!0});ss.readPcfColumn=ss.readControlManifest=void 0;var as=le(),$G=Hh();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 xG(e,t){var r;let n="/customcontrols"+(0,as.odataQuery)([["$select","name,manifest"],["$filter",`name eq '${(0,as.odataLiteral)(t)}'`]]);try{let i=await e.get(n);if(i.status<200||i.status>=300)return{kind:"unavailable",error:Kh(`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,$G.parsePcfManifest)(s)}}catch(i){return{kind:"unavailable",error:i instanceof Error?i:new Error(String(i))}}}ss.readControlManifest=xG;var FG=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 pS(e){let t=e?.Value;return typeof t=="string"?t:void 0}async function MG(e,t,r,n){var i;let o=`/EntityDefinitions(LogicalName='${(0,as.odataPathLiteral)(t)}')/Attributes(LogicalName='${(0,as.odataPathLiteral)(r)}')`,a=n?.requireCreateEligibility===!0;try{let s=await e.get(o+(0,as.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:Kh(`reading column "${r}"`,s.status,s.body)};let l=(i=s.body)!==null&&i!==void 0?i:{},u=pS(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=FG.get(u);if(d){let f=await e.get(`${o}/Microsoft.Dynamics.CRM.${d.cast}`+(0,as.odataQuery)([["$select",d.select]]));if(f.status<200||f.status>=300)return{kind:"unavailable",error:Kh(`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=pS(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))}}}ss.readPcfColumn=MG});var Jo=v(gd=>{"use strict";Object.defineProperty(gd,"__esModule",{value:!0});gd.DEFAULT_LCID=void 0;gd.DEFAULT_LCID=1033});var pt=v(Kn=>{"use strict";Object.defineProperty(Kn,"__esModule",{value:!0});Kn.assignMissingIds=Kn.pointerTouchesValueMap=Kn.isValueMapKey=Kn.newId=void 0;var UG=Ma();function hS(){return globalThis.crypto.randomUUID().toLowerCase()}Kn.newId=hS;function BG(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}var Yh=new Set(["parameters","bag","expression","rawExpression","lookupValue","stepLabels","genPage","inputData","customControl"]);function qG(e){return Yh.has(e)}Kn.isValueMapKey=qG;function VG(e){return UG.JsonPointer.parse(e).some(t=>Yh.has(t))}Kn.pointerTouchesValueMap=VG;function GG(e){return Jh(e),e}Kn.assignMissingIds=GG;function Jh(e){if(Array.isArray(e)){e.forEach(t=>Jh(t));return}if(BG(e)){(typeof e.id!="string"||e.id.length===0)&&(e.id=hS());for(let t of Object.keys(e))t==="id"||Yh.has(t)||Jh(e[t])}}});var Kl=v(Kt=>{"use strict";Object.defineProperty(Kt,"__esModule",{value:!0});Kt.sendChangeSet=Kt.isChangeSetLockRefusal=Kt.partResponse=Kt.postChangeSet=Kt.parseChangeSetParts=Kt.parseChangeSetStatuses=Kt.renderChangeSet=void 0;var Ii=Q(),Yo=ye(),gS=pt(),Hl=le();function Qh(e,t){let r=`batch_${(0,gS.newId)()}`,n=`changeset_${(0,gS.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 Ii.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 Ii.InvalidArgumentError(`batch operation ${s.method} ${s.path} has a body containing the batch boundary`);(0,Hl.assertNoControlChars)(s.path,"batch operation path"),s.etag&&(0,Hl.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,Hl.assertNoControlChars)(m,"batch operation header name"),(0,Hl.assertNoControlChars)(p,"batch operation header value"),!/^[A-Za-z0-9!#$%&'*+.^_`|~-]+$/.test(m))throw new Ii.InvalidArgumentError(`batch operation header name '${m}' is not a valid HTTP token`);return s.contentType!==void 0&&(0,Hl.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}}Kt.renderChangeSet=Qh;function bS(e,t){var r;return(r=yd(e,t))===null||r===void 0?void 0:r.map(n=>n.status)}Kt.parseChangeSetStatuses=bS;function yd(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(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}Kt.parseChangeSetParts=yd;async function WG(e,t,r){if(t.length===0)return;let{body:n,batchId:i,contentIds:o}=Qh(e,t),a=await e.postBatch(n,i),s=e.apiUrl("/$batch");if((0,Yo.ensureSuccess)(a,s),typeof a.body!="string"||a.body.length===0)throw new Ii.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=bS(a.body,o);if(l===void 0)throw new Ii.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 Ii.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 Ii.ConnectionError(s,u,`atomic write of ${r} was rolled back: the change set reported HTTP ${u}`)}Kt.postChangeSet=WG;function Xh(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}}Kt.partResponse=Xh;function yS(e){let t=e.path.indexOf("?");return t===-1?e.path:e.path.slice(0,t)}function zG(e,t){let r=e.find(n=>(0,Yo.isVersionToken)(n.etag));if(!r||e.some(n=>yS(n)!==yS(r)))throw new Ii.InvalidArgumentError(`the change set writing ${t} cannot be re-sent under the customization lock: it needs an operation conditioned on a version token and every operation writing that operation's row`)}function vS(e,t){var r;if(e.status!==429&&(e.status<200||e.status>=300))return!1;let n=(r=yd(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=>(0,Yo.isConcurrencyLockRefusal)(Xh(i)))}Kt.isChangeSetLockRefusal=vS;async function jG(e,t,r,n={}){n.resendWhileLockRefused&&zG(t,r);let{body:i,batchId:o,contentIds:a}=Qh(e,t),s=()=>e.postBatch(i,o),l=n.resendWhileLockRefused?await(0,Yo.resendWhile)(f=>vS(f,a),s,Yo.LOCK_BACKOFF_MS):await s(),u=e.apiUrl("/$batch"),c=yd(l.body,a),d=c?.find(f=>f.status<200||f.status>=300);if(d&&(0,Yo.ensureSuccess)(Xh(d),e.apiUrl(t[a.indexOf(d.contentId)].path)),(0,Yo.ensureSuccess)(l,u),!c||c.length!==t.length)throw new Ii.ConnectionError(u,l.status,`atomic write of ${r} cannot be confirmed: the $batch response ${c?`reported ${c.length} result(s) for ${t.length} operation(s)`:"could not be parsed"}, so the outcome is unknown`);return a.map(f=>c.find(m=>m.contentId===f))}Kt.sendChangeSet=jG});var bd=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 _e=ye(),te=le(),Jn=Jo(),ge=Q(),HG=Kl(),KG={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 et(e,t){return{"@odata.type":"Microsoft.Dynamics.CRM.Label",LocalizedLabels:JG(e,t)}}var wS=65535;function JG(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 ge.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 ge.InvalidArgumentError(`localized label key '${o}' is not an LCID (expected a canonical positive integer, e.g. 1033)`);let s=Number(o);if(s>wS)throw new ge.InvalidArgumentError(`localized label LCID ${s} is out of range (1-${wS})`);if(i.has(s))throw new ge.InvalidArgumentError(`localized label LCID ${s} is specified more than once`);if(i.add(s),typeof a!="string")throw new ge.InvalidArgumentError(`localized label for LCID ${s} must be a string`);return r(a,s)})}function NS(e){return typeof e=="string"?`${e}s`:Object.fromEntries(Object.entries(e).map(([t,r])=>{if(typeof r!="string")throw new ge.InvalidArgumentError(`localized label for LCID ${t} must be a string`);return[t,`${r}s`]}))}ie.pluralFallback=NS;function Jl(e){return{Value:e,CanBeChanged:!0,ManagedPropertyLogicalName:"canmodifyrequirementlevelsettings"}}var CS=["None","ApplicationRequired","Recommended"];function tg(e){let t=e.indexOf("_");return t>0?e.slice(0,t):e}function ES(e,t,r){let n=e[t];n&&typeof n=="object"?n.Value=r:e[t]={Value:r}}function Yl(e){let t=(0,_e.readCreatedId)(e,"MetadataId");if(!t)throw new ge.InvalidArgumentError("Dataverse did not return a MetadataId for the created metadata component");return t}function YG(e,t,r){var n,i,o,a,s,l,u,c,d,f,m,p,h,g,b,w,C,S,O,k,I,D,P,x;if(t.defaultValue!==void 0&&e!=="boolean")throw new ge.InvalidArgumentError(`createColumn: 'defaultValue' applies to boolean columns, but '${t.schemaName}' is of type '${e}'.`);if(t.integerFormat!==void 0&&e!=="integer")throw new ge.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:et((C=t.trueLabel)!==null&&C!==void 0?C:"Yes",r)},FalseOption:{Value:0,Label:et((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 AS(t,r,!1);case"multiChoice":return AS(t,r,!0);case"file":return{"@odata.type":"Microsoft.Dynamics.CRM.FileAttributeMetadata",AttributeType:"Virtual",AttributeTypeName:{Value:"FileType"},MaxSizeInKB:(k=t.maxSizeKb)!==null&&k!==void 0?k: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 ge.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 ge.InvalidArgumentError(`unsupported column type '${String(e)}'`)}}function AS(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 ge.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:et(o.label,t)}))},i}var Zh=new WeakMap;async function QG(e,t){var r,n;let i=(r=Zh.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,_e.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||n===void 0?void 0:n.EntitySetName;if(!s)throw new ge.InvalidArgumentError(`could not resolve EntitySetName for '${t}'`);(0,te.assertODataName)(s,`server-derived EntitySetName for '${t}'`);let l=Zh.get(e);return l||(l=new Map,Zh.set(e,l)),l.set(t,s),s}ie.resolveEntitySetName=QG;async function XG(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&&!CS.includes(b))throw new ge.InvalidArgumentError(`createTable: 'primaryColumnRequired' must be one of ${CS.join(", ")}; got '${String(b)}'.`);let w=b!==void 0&&b!=="None";if(w&&!t.primaryColumnAutoNumberFormat&&!e.supportsPut)throw new ge.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:Jn.DEFAULT_LCID,S=tg(t.schemaName),O=(n=t.primaryColumnSchemaName)!==null&&n!==void 0?n:`${S}_Name`,k={"@odata.type":"Microsoft.Dynamics.CRM.StringAttributeMetadata",AttributeType:"String",AttributeTypeName:{Value:"StringType"},SchemaName:O,RequiredLevel:Jl(b??"None"),MaxLength:(i=t.primaryColumnMaxLength)!==null&&i!==void 0?i:100,FormatName:{Value:"Text"},DisplayName:et((o=t.primaryColumnDisplayName)!==null&&o!==void 0?o:"Name",C),IsPrimaryName:!0};t.primaryColumnAutoNumberFormat&&(k.AutoNumberFormat=t.primaryColumnAutoNumberFormat),t.columns&&IS(t.columns,"createTable");let I={"@odata.type":"Microsoft.Dynamics.CRM.EntityMetadata",SchemaName:t.schemaName,DisplayName:et(t.displayName,C),DisplayCollectionName:et((a=t.pluralName)!==null&&a!==void 0?a:NS(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:[k,...((c=t.columns)!==null&&c!==void 0?c:[]).map(ir=>rg(ir,C))]};t.description&&(I.Description=et(t.description,C));let D="/EntityDefinitions",P=(0,_e.ensureSuccess)(await e.post(D,I),e.apiUrl(D)),x=Yl(P),K=`/EntityDefinitions(${x})`+(0,te.odataQuery)([["$select","LogicalName,EntitySetName,PrimaryIdAttribute,PrimaryNameAttribute"]]),Oe=Math.max(1,Math.trunc((d=t.readBackAttempts)!==null&&d!==void 0?d:6)),Vt=Math.max(0,(f=t.readBackDelayMs)!==null&&f!==void 0?f:1e3),Xe=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}' }).`:"",Ne;try{Ne=await _S(e,K,Oe,Vt)}catch(ir){throw w?(0,ge.attachCause)(new ge.SdkError("PRIMARY_COLUMN_REQUIRED_NOT_APPLIED",`Table '${t.schemaName}' WAS CREATED (MetadataId ${x}), but reading it back failed (${ir instanceof Error?ir.message:String(ir)}).${Xe} Do NOT re-run the create \u2014 it will collide on the schema name.`),ir):ir}if(!Ne)throw new ge.SdkError("TABLE_METADATA_NOT_VISIBLE",`Table '${t.schemaName}' WAS CREATED (MetadataId ${x}) but its metadata was still not readable after ${Oe} 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'.${Xe}`);let se=Ne.body,We={logicalName:(m=se.LogicalName)!==null&&m!==void 0?m:t.schemaName.toLowerCase(),metadataId:x,entitySetName:(p=se.EntitySetName)!==null&&p!==void 0?p:"",primaryIdAttribute:(h=se.PrimaryIdAttribute)!==null&&h!==void 0?h:`${t.schemaName.toLowerCase()}id`,primaryNameAttribute:(g=se.PrimaryNameAttribute)!==null&&g!==void 0?g:O.toLowerCase()};return w&&(We.primaryColumnRequired=await ZG(e,t.schemaName,We,b,Oe,Vt)),We}ie.createTable=XG;async function _S(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,_e.ensureSuccess)(o,e.apiUrl(t)),i<r&&n>0&&await new Promise(a=>setTimeout(a,n))}}async function ZG(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 _S(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 ge.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 kS(e,r.logicalName,r.primaryNameAttribute,{required:n}),l="verify",u=await s())}catch(d){throw l==="verify"&&(u=void 0),(0,ge.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 rg(e,t){var r,n;let i=(r=e.languageCode)!==null&&r!==void 0?r:t,o={...YG(e.type,e,i),SchemaName:e.schemaName,RequiredLevel:Jl((n=e.required)!==null&&n!==void 0?n:"None"),DisplayName:et(e.displayName,i)};return e.description&&(o.Description=et(e.description,i)),e.sourceType&&e.sourceType!=="Simple"&&(o.SourceType=e.sourceType==="Rollup"?2:1,e.formulaDefinition&&(o.FormulaDefinition=e.formulaDefinition)),TS(o,e),o}function TS(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 e9(e,t,r){var n;let i=rg(r,(n=r.languageCode)!==null&&n!==void 0?n:Jn.DEFAULT_LCID),o=`/EntityDefinitions(LogicalName='${(0,te.odataPathLiteral)(t)}')/Attributes`,a=(0,_e.ensureSuccess)(await e.post(o,i),e.apiUrl(o)),s={logicalName:r.schemaName.toLowerCase(),metadataId:Yl(a)};if(r.visualization&&r.visualization!=="None")try{await RS(e,t,s.logicalName,s.metadataId,r.visualization)}catch(l){let u=new ge.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,ge.attachCause)(u,l),u}return s}ie.createColumn=e9;var ls="/controlconfigurations",DS="CustomRenderersConfiguration",eg={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 IS(e,t){let r=e.find(n=>n.visualization&&n.visualization!=="None");if(r)throw new ge.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 OS(e){return JSON.stringify({type:eg[e]})}function t9(e){if(!e)return"None";let t;try{t=JSON.parse(e)}catch{return"None"}let r=t?.type,n=Object.keys(eg).find(i=>eg[i]===r);return n??"None"}async function PS(e,t,r){var n,i;let o=`entitylogicalname eq '${(0,te.odataLiteral)(t)}' and Attribute/logicalname eq '${(0,te.odataLiteral)(r)}'`,a=`${ls}${(0,te.odataQuery)([["$select","name,uniquename,metadatajson"],["$expand","Attribute($select=name,logicalname)"],["$filter",o]])}`,l=(i=(n=(0,_e.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 r9(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,_e.ensureSuccess)(await e.get(i),e.apiUrl(i)).body)===null||n===void 0?void 0:n.MetadataId;if(!a)throw new ge.InvalidArgumentError(`cannot resolve column '${r}' on '${t}' to set its visualization`);return(0,te.normalizeGuid)(a,"MetadataId")}async function RS(e,t,r,n,i){let o={name:DS,uniquename:`msdyn_${t}_${r}_customrenderers`,metadatajson:OS(i),"[email protected]":`/attributes(${(0,te.normalizeGuid)(n,"MetadataId")})`,entitylogicalname:t};(0,_e.ensureSuccess)(await e.post(ls,o),e.apiUrl(ls))}async function n9(e,t,r){var n;let i=await PS(e,t,r);return t9((n=i[0])===null||n===void 0?void 0:n.metadatajson)}ie.getColumnVisualization=n9;async function i9(e,t,r,n){let o=(await PS(e,t,r)).map(u=>u.controlconfigurationid).filter(u=>!!u);if(n==="None"){for(let u of o){let c=`${ls}(${(0,te.normalizeGuid)(u,"controlconfigurationid")})`;(0,_e.ensureSuccess)(await e.delete(c),e.apiUrl(c))}return}let[a,...s]=o,l=await r9(e,t,r);if(a){let u=`${ls}(${(0,te.normalizeGuid)(a,"controlconfigurationid")})`,c={name:DS,metadatajson:OS(n),"[email protected]":`/attributes(${l})`,entitylogicalname:t};(0,_e.ensureSuccess)(await e.patch(u,c),e.apiUrl(u))}else await RS(e,t,r,l,n);for(let u of s){let c=`${ls}(${(0,te.normalizeGuid)(u,"controlconfigurationid")})`;(0,_e.ensureSuccess)(await e.delete(c),e.apiUrl(c))}}ie.setColumnVisualization=i9;async function o9(e,t,r){if(r.length===0)return;if(IS(r,"createColumns"),!e.supportsAtomicBatch)throw new ge.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,HG.postChangeSet)(e,r.map(i=>{var o;return{method:"POST",path:n,body:rg(i,(o=i.languageCode)!==null&&o!==void 0?o:Jn.DEFAULT_LCID)}}),`${r.length} column(s) on '${t}'`)}ie.createColumns=o9;async function a9(e,t,r){var n,i,o,a;let s=(n=r.languageCode)!==null&&n!==void 0?n:Jn.DEFAULT_LCID,l=tg(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:et(r.displayName,s),RequiredLevel:Jl((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,_e.ensureSuccess)(await e.post("/CreateCustomerRelationships",d),e.apiUrl("/CreateCustomerRelationships")),{logicalName:r.schemaName.toLowerCase(),metadataId:""}}ie.createCustomerColumn=a9;async function s9(e,t,r){var n,i,o,a,s;let l=(n=r.languageCode)!==null&&n!==void 0?n:Jn.DEFAULT_LCID,u={EntityLogicalName:t,AttributeLogicalName:"statuscode",Label:et(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,_e.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=s9;async function l9(e,t){var r,n,i,o,a;let s=(r=t.languageCode)!==null&&r!==void 0?r:Jn.DEFAULT_LCID,l,u;if(t.type==="OneToMany"){if(!t.referencedEntity||!t.referencingEntity)throw new ge.InvalidArgumentError("OneToMany relationship requires referencedEntity and referencingEntity");let f=(n=t.lookupSchemaName)!==null&&n!==void 0?n:`${tg(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:Jl((i=t.lookupRequired)!==null&&i!==void 0?i:"None"),DisplayName:et((o=t.lookupDisplayName)!==null&&o!==void 0?o:t.referencedEntity,s)}}}else{if(!t.entity1||!t.entity2)throw new ge.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,_e.ensureSuccess)(await e.post(c,l),e.apiUrl(c));return{schemaName:t.schemaName,metadataId:Yl(d),lookupLogicalName:u}}ie.createRelationship=l9;async function u9(e,t){let r=`/EntityDefinitions(LogicalName='${(0,te.odataPathLiteral)(t)}')`;(0,_e.ensureSuccess)(await e.delete(r),e.apiUrl(r))}ie.deleteTable=u9;async function kS(e,t,r,n){var i,o;let a=(i=n.languageCode)!==null&&i!==void 0?i:Jn.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,_e.ensureSuccess)(await e.get(l),e.apiUrl(l)).body,d=KG[(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 ge.InvalidArgumentError(`cannot update column '${r}' on '${t}' (${g})`)}let f=(0,te.normalizeGuid)(c.MetadataId,"MetadataId"),m=`${s}(${f})/${d}`,p=(0,_e.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=et(n.displayName,a)),n.description!==void 0&&(p.Description=et(n.description,a)),n.required!==void 0&&(p.RequiredLevel=Jl(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 ge.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 ge.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),TS(p,n);let h=`${s}(${f})`;(0,_e.ensureSuccess)(await e.put(h,p,{headers:{"MSCRM.MergeLabels":"true"}}),e.apiUrl(h))}ie.updateColumn=kS;async function c9(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,_e.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||n===void 0?void 0:n.MetadataId;if(!s)throw new ge.InvalidArgumentError(`column '${r}' not found on '${t}'`);let l=`${i}(${(0,te.normalizeGuid)(s,"MetadataId")})`;(0,_e.ensureSuccess)(await e.delete(l),e.apiUrl(l))}ie.deleteColumn=c9;async function d9(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,_e.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 ge.InvalidArgumentError(`relationship '${t}' not found`);let l=`/RelationshipDefinitions(${(0,te.normalizeGuid)(s,"MetadataId")})`;(0,_e.ensureSuccess)(await e.delete(l),e.apiUrl(l))}ie.deleteRelationship=d9;async function SS(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,_e.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 f9(e,t){var r;let n=t.name.toLowerCase(),i=await SS(e,n);if(i)return{name:n,metadataId:i};let o=(r=t.languageCode)!==null&&r!==void 0?r:Jn.DEFAULT_LCID,a={"@odata.type":"Microsoft.Dynamics.CRM.OptionSetMetadata",Name:n,DisplayName:et(t.displayName,o),IsGlobal:!0,OptionSetType:"Picklist",Options:t.options.map(l=>({Value:l.value,Label:et(l.label,o)}))};t.description&&(a.Description=et(t.description,o));let s="/GlobalOptionSetDefinitions";try{let l=(0,_e.ensureSuccess)(await e.post(s,a),e.apiUrl(s));return{name:n,metadataId:Yl(l)}}catch(l){let u;try{u=await SS(e,n)}catch{u=void 0}if(u)return{name:n,metadataId:u};throw l}}ie.createGlobalOptionSet=f9;async function p9(e,t){let r=`/GlobalOptionSetDefinitions(Name='${(0,te.odataPathLiteral)(t.toLowerCase())}')`;(0,_e.ensureSuccess)(await e.delete(r),e.apiUrl(r))}ie.deleteGlobalOptionSet=p9;async function m9(e,t,r){var n;let i=(n=r.languageCode)!==null&&n!==void 0?n:Jn.DEFAULT_LCID,o={"@odata.type":"Microsoft.Dynamics.CRM.EntityKeyMetadata",SchemaName:r.schemaName,DisplayName:et(r.displayName,i),KeyAttributes:r.keyAttributes},a=`/EntityDefinitions(LogicalName='${(0,te.odataPathLiteral)(t)}')/Keys`,s=(0,_e.ensureSuccess)(await e.post(a,o),e.apiUrl(a));return{logicalName:r.schemaName.toLowerCase(),metadataId:Yl(s)}}ie.createAlternateKey=m9;async function h9(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,_e.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||n===void 0?void 0:n.MetadataId;if(!s)throw new ge.InvalidArgumentError(`alternate key '${r}' not found on '${t}'`);let l=`${i}(${(0,te.normalizeGuid)(s,"MetadataId")})`;(0,_e.ensureSuccess)(await e.delete(l),e.apiUrl(l))}ie.deleteAlternateKey=h9;async function g9(e,t,r){var n;let i=(n=r.languageCode)!==null&&n!==void 0?n:Jn.DEFAULT_LCID,o=`/EntityDefinitions(LogicalName='${(0,te.odataPathLiteral)(t)}')`,s=(0,_e.ensureSuccess)(await e.get(o),e.apiUrl(o)).body,l=s.MetadataId;if(!l)throw new ge.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=et(r.displayName,i)),r.pluralName!==void 0&&(s.DisplayCollectionName=et(r.pluralName,i)),r.description!==void 0&&(s.Description=et(r.description,i)),r.auditEnabled!==void 0&&ES(s,"IsAuditEnabled",r.auditEnabled),r.duplicateDetectionEnabled!==void 0&&ES(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,_e.ensureSuccess)(await e.put(c,s,{headers:{"MSCRM.MergeLabels":"true"}}),e.apiUrl(c))}ie.updateTable=g9});var so=v(Nr=>{"use strict";Object.defineProperty(Nr,"__esModule",{value:!0});Nr.rebuildRaw=Nr.assembleChildren=Nr.spliceChildren=Nr.mergeAttrs=Nr.rawFromNode=Nr.emptyBag=void 0;var ao=Q(),LS=1e6,wd=512;function y9(){return{a:[],c:[]}}Nr.emptyBag=y9;function $S(e,t=0){if(t>wd)throw new ao.InvalidArgumentError(`Artifact node tree exceeds the maximum depth of ${wd}`);return{n:e.getNodeName(),a:e.getAllProperties().map(r=>[r.key,r.value]),c:e.getAllChildren().map(r=>$S(r,t+1))}}Nr.rawFromNode=$S;function b9(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}Nr.mergeAttrs=b9;function vd(e,t){let r=new Set;for(let s of e){let l=s.i;if(!Number.isInteger(l)||l<0||l>LS)throw new ao.InvalidArgumentError(`Bag child index must be an integer in [0, ${LS}] (got ${String(l)})`);if(r.has(l))throw new ao.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}Nr.spliceChildren=vd;function v9(e,t){if(e.w){let r={n:e.w.n,a:e.w.a.map(n=>[n[0],n[1]]),c:vd(e.w.c,t)};return vd(e.c,[r])}return vd(e.c,t)}Nr.assembleChildren=v9;function xS(e,t,r,n=0){if(n>wd)throw new ao.InvalidArgumentError(`Artifact node tree exceeds the maximum depth of ${wd}`);w9(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,xS(o,t,i,n+1));return i}Nr.rebuildRaw=xS;function w9(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new ao.InvalidArgumentError(`Malformed hybrid node at depth ${t}: expected a JSON object`);let r=e;if(typeof r.n!="string")throw new ao.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 ao.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 ao.InvalidArgumentError(`Malformed hybrid node '${r.n}': each attribute must be a [string, string] pair`)}});var lo=v(Cd=>{"use strict";Object.defineProperty(Cd,"__esModule",{value:!0});Cd.installDomShim=void 0;var FS=ns(),MS=!1,C9={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 E9(){if(MS)return;let e=globalThis;typeof e.DOMParser>"u"&&(e.DOMParser=FS.DOMParser),typeof e.XMLSerializer>"u"&&(e.XMLSerializer=FS.XMLSerializer),typeof e.Node>"u"&&(e.Node=C9),MS=!0}Cd.installDomShim=E9});var uo=v(tt=>{"use strict";Object.defineProperty(tt,"__esModule",{value:!0});tt.projectElementBag=tt.serializeNode=tt.domEngine=tt.nodeLikeFromDom=tt.parseXmlRoot=tt.EMPTY_FORM_SENTINEL=tt.TEXT_SENTINEL=void 0;var A9=so(),us=Q(),S9=lo();tt.TEXT_SENTINEL="#text";tt.EMPTY_FORM_SENTINEL="#empty";var Ad=new WeakSet;function N9(e,t){(0,S9.installDomShim)();let r=e&&e.trim()!==""?e:t,n=new DOMParser().parseFromString(r,"text/xml"),i=n.documentElement;if(!i)throw new us.InvalidArgumentError("XML source has no root element (empty or malformed input)");return _9(r),D9(n),O9(i),P9(i),L9(i,r),i}tt.parseXmlRoot=N9;function _9(e){let t=e.search(/\S/);if(t!==-1&&e[t]!=="<")throw BS(3)}var T9=["http://www.mozilla.org/newlayout/xml/parsererror.xml","http://www.w3.org/1999/xhtml"];function D9(e){var t;for(let r of T9){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 us.InvalidArgumentError(`XML source is not well-formed (${i||"the XML parser reported an error"}), so it cannot be round-tripped`)}}}var I9=new Set([1,3]);function O9(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(!I9.has(o.nodeType))throw new us.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 P9(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 BS(a.nodeType)}}function BS(e){return new us.InvalidArgumentError(`Unsupported document-level XML node (type ${e}: declaration / comment / processing-instruction outside the root element) cannot be round-tripped`)}function R9(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 k9(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 qS(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 L9(e,t){let r=R9(t),n=k9(e),i=Math.min(r.length,n.length);for(let o=0;o<i;o+=1){if(r[o])continue;let a=n[o];qS(a)||Ad.add(a)}}function ng(e){let t=e.nodeType===3;return{getNodeName:()=>t?tt.TEXT_SENTINEL:e.tagName,getAllProperties:()=>{var r;if(t)return[{key:tt.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 Ad.has(e)&&!qS(e)&&i.push({key:tt.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(ng(o))}return r}}}tt.nodeLikeFromDom=ng;function $9(e){return{make:t=>t===tt.TEXT_SENTINEL?e.createTextNode(""):e.createElement(t),setProp:(t,r,n)=>{t.nodeType===3?t.nodeValue=n:r===tt.EMPTY_FORM_SENTINEL?Ad.add(t):t.setAttribute(r,n)},addChild:(t,r)=>{t.appendChild(r)}}}tt.domEngine=$9;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 Ed(r);if(r>=55296&&r<=56319){let n=e.charCodeAt(t+1);if(!(n>=56320&&n<=57343))throw Ed(r);t+=1;continue}if(r>=56320&&r<=57343)throw Ed(r)}}function Ed(e){let t=e.toString(16).toUpperCase().padStart(4,"0");return new us.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 x9(e){return VS(e),String(e).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/\r/g,"
").replace(/\n/g,"
").replace(/\t/g,"	")}function F9(e){return VS(e),String(e).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}function M9(e){return GS(e,0)}tt.serializeNode=M9;var US=512;function GS(e,t){var r;if(t>US)throw new us.InvalidArgumentError(`XML nesting exceeds the maximum supported depth of ${US}`);if(e.nodeType===3)return F9((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+'="'+x9(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 Ad.has(n)?i+"></"+n.tagName+">":i+" />";i+=">";for(let l of a)i+=GS(l,t+1);return i+"</"+n.tagName+">"}function U9(e){let t=ng(e);return{a:t.getAllProperties().map(r=>[r.key,r.value]),c:t.getAllChildren().map((r,n)=>({i:n,node:(0,A9.rawFromNode)(r)}))}}tt.projectElementBag=U9});var rn=v(Jt=>{"use strict";Object.defineProperty(Jt,"__esModule",{value:!0});Jt.rejectUnknownKeys=Jt.childObjects=Jt.optionalGuidId=Jt.optionalEnum=Jt.eachObject=Jt.issue=Jt.isJsonObject=void 0;function WS(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}Jt.isJsonObject=WS;function cs(e,t,r,n){return n?{pointer:e,rule:t,message:r,fatal:n}:{pointer:e,rule:t,message:r}}Jt.issue=cs;function zS(e,t,r,n){if(!Array.isArray(e))return[];let i=[];return e.forEach((o,a)=>{WS(o)?i.push({node:o,index:a}):n.push(cs(`${t}/${a}`,`${r}-must-be-object`,`a ${r} must be a JSON object, got ${o===null?"null":typeof o}`))}),i}Jt.eachObject=zS;function B9(e,t,r,n,i,o){let a=e[t];a!==void 0&&(typeof a!="string"||!r.includes(a))&&o.push(cs(`${n}/${t}`,i,`${t} must be one of ${r.map(s=>`'${s}'`).join(", ")}, got ${JSON.stringify(a)}`))}Jt.optionalEnum=B9;var q9=/^(?:\{[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 V9(e,t,r,n,i){let o=e[t];typeof o=="string"&&o!==""&&!q9.test(o)&&i.push(cs(`${r}/${t}`,n,`${t} must be a GUID or empty, got '${o}'`))}Jt.optionalGuidId=V9;function G9(e,t,r,n,i){let o=e[t],a=`${r}/${t}`;return o===void 0?[]:Array.isArray(o)?zS(o,a,n,i):(i.push(cs(a,`${n}-list-must-be-array`,`${t} must be an array when present, got ${typeof o}`)),[])}Jt.childObjects=G9;function W9(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(cs(`${r}/${l}`,`${n}-unknown-key`,`'${l}' is not a ${n} property, and would be SILENTLY DROPPED at serialization.${d}`))}}Jt.rejectUnknownKeys=W9});var Dd=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 z9=ns(),j9=Ma(),ig=pt(),nn=rn();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 H9=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function _r(e){if(typeof e!="string")return"";let t=e.trim().toLowerCase();return t.startsWith("{")&&t.endsWith("}")&&(t=t.slice(1,-1)),H9.test(t)?t:""}B.normGuid=_r;function co(e,t){let r=Se(e?.a).find(n=>Array.isArray(n)&&n[0]===t);return r?r[1]:void 0}B.rawAttr=co;function Xl(e){return Se(e?.c).filter(t=>typeof t?.n=="string"&&t.n.startsWith("<")).map(t=>t.n.slice(1)).join("")}B.rawText=Xl;function Se(e){return Array.isArray(e)?e:[]}function cg(e,t){let r=Se(e?.a).find(n=>Array.isArray(n)&&n[0]===t);return r?r[1]:void 0}function KS(e){return typeof e=="string"?e.trim().replace(/^\{|\}$/g,"").toUpperCase():""}function JS(e){return Sn(e).map(t=>t.cell)}B.typedCells=JS;function Sn(e){let t=[];return Se(e?.tabs).forEach((r,n)=>{Se(Re(r)?r.columns:void 0).forEach((i,o)=>{Se(Re(i)?i.sections:void 0).forEach((a,s)=>{Se(Re(a)?a.rows:void 0).forEach((l,u)=>{Se(Re(l)?l.cells:void 0).forEach((c,d)=>{Re(c)&&t.push({cell:c,pointer:`/tabs/${n}/columns/${o}/sections/${s}/rows/${u}/cells/${d}`})})})})})}),t}B.typedCellSites=Sn;function Oi(e){return Re(e)?_r(cg(e.bag,"uniqueid")):""}B.controlUniqueId=Oi;function K9(e){let t=new Set;for(let{cell:r}of Sn(e)){let n=Zo(r.control)?Oi(r.control):"";n&&t.add(n)}return t}function J9(e){let t=new Map;for(let{cell:r}of Sn(e)){let n=Re(r.control)?Oi(r.control):"";n&&!t.has(n)&&t.set(n,r.control)}return t}function Y9(e){return e!==void 0&&e.genPage===void 0&&(pg(e)!==B.CUSTOM_CONTROL_CLASS_ID||!Td(e))}function og(e,t){if(Re(e)){t(e);for(let r of Se(e.c))og(r,t)}}function Qo(e,t){var r;if(Re(e)){for(let n of Se(e.c))og(n?.node,t);for(let n of Se((r=e.w)===null||r===void 0?void 0:r.c))og(n?.node,t)}}function Nd(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(_r(co(i,"uniqueid")))};return Qo(e?.bag,n),Se(e?.tabs).forEach(i=>{Re(i)&&(Qo(i.bag,n),Se(i.columns).forEach(o=>{Re(o)&&(Qo(o.bag,n),Se(o.sections).forEach(a=>{Re(a)&&(Qo(a.bag,n),Se(a.rows).forEach(s=>{Re(s)&&(Qo(s.bag,n),Se(s.cells).forEach(l=>{Re(l)&&(Qo(l.bag,n),Re(l.control)&&(r(Oi(l.control)),Qo(l.control.bag,n)))}))}))}))}))}),t}B.controlUniqueIds=Nd;function ds(e){return Se(e?.c).find(t=>{var r;return((r=t?.node)===null||r===void 0?void 0:r.n)==="controlDescriptions"})}B.descriptionsRegion=ds;function Xo(e,t){var r;let n=_r(t);if(n)return Se((r=ds(e))===null||r===void 0?void 0:r.node.c).find(i=>i?.n==="controlDescription"&&_r(co(i,"forControl"))===n)}B.descriptionFor=Xo;function Zl(e){return Se(e.c).filter(YS)}B.pageEntries=Zl;function YS(e){return e?.n==="customControl"&&co(e,"name")===B.GENPAGE_CONTROL_NAME}function ag(e,t){let r=Se(e.c).find(n=>n?.n==="parameters");return Se(r?.c).find(n=>n?.n===t)}B.entryParameter=ag;function sg(e){return co(e,"static")==="true"}B.isStaticParameter=sg;function eu(e){let t=Zl(e);if(t.length===0)return{kind:"none"};let r,n;for(let i=0;i<t.length;i+=1){let o=ag(t[i],"RefId");if(!o||!sg(o))return{kind:"unsupported"};let a=_r(Xl(o));if(!a)return{kind:"unsupported"};let s=ag(t[i],"PageInput");if(s&&!sg(s))return{kind:"unsupported"};let l=s?Xl(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=eu;function Re(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function dg(e){if(e===void 0)return;let t;try{t=JSON.parse(e)}catch{return}return Re(t)&&Re(t.data)?t.data:void 0}B.inputDataFrom=dg;function fg(e){var t;return(t=e.formType)!==null&&t!==void 0?t:"Main"}B.effectiveFormType=fg;function pg(e){return KS(e.classId!==void 0?e.classId:cg(e.bag,"classid"))}B.effectiveClassId=pg;function Td(e){return!e.fieldName}B.isUnbound=Td;function mg(e,t){if(fg(e)!=="Main"||!Td(t)||pg(t)!==B.CUSTOM_CONTROL_CLASS_ID)return!1;let r=Oi(t),n=r?Xo(e.bag,r):void 0;return n!==void 0&&eu(n).kind==="projectable"}B.isRecognizedEmbed=mg;function Q9(e){for(let t of JS(e)){let r=t.control;if(!r||!mg(e,r))continue;let n=eu(Xo(e.bag,Oi(r)));if(n.kind!=="projectable")continue;let i=dg(n.pageInputRaw);r.genPage=i===void 0?{pageId:n.pageId}:{pageId:n.pageId,inputData:i}}}B.projectGenPageEmbeds=Q9;var X9=new Set(["pageId","inputData"]);function Ql(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 Z9(e){var t;let r=[],n=c=>d=>r.push(`${c}: ${d}`),i=new z9.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=_r(s[c].getAttribute("uniqueid"));d&&a.add(d)}let l=Ql(o).find(c=>c.nodeName==="controlDescriptions"),u=new Map;for(let c of l?Ql(l):[]){let d=_r(c.getAttribute("forControl"));if(!(c.nodeName!=="controlDescription"||!d||!a.has(d)))for(let f of Ql(c)){if(f.nodeName!=="customControl"||f.getAttribute("name")!==B.GENPAGE_CONTROL_NAME)continue;let m=Ql(f).find(g=>g.nodeName==="parameters"),p=m?Ql(m).find(g=>g.nodeName==="RefId"):void 0,h=p&&p.getAttribute("static")==="true"?_r(p.textContent):"";h&&u.set(`${d}|${h}`,[d,h])}}return[...u.values()]}B.activeEmbedBindings=Z9;function Sd(e){return{n:`<${e}`,a:[],c:[]}}function lg(e,t){return{n:e,a:[["type","SingleLine.Text"],["static","true"]],c:[Sd(t)]}}function ug(e,t){let r={};if(t!==void 0)try{let n=JSON.parse(t);Re(n)&&(r=n)}catch{}return JSON.stringify({...r,data:e})}function eW(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:[lg("RefId",t),...r===void 0?[]:[lg("PageInput",ug(r))]]}]}))}}function _d(e,t){if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((r,n)=>_d(r,t[n]));if(Re(e)&&Re(t)){let r=Object.keys(e);return r.length===Object.keys(t).length&&r.every(n=>n in t&&_d(e[n],t[n]))}return e===t}function tW(e,t,r){let n=Se(e.c).find(u=>u?.n==="parameters");if(!n||!Array.isArray(n.c))return;let i=n.c.find(u=>u?.n==="RefId");i&&_r(Xl(i))!==t&&(i.c=[Sd(t)]);let o=n.c.findIndex(u=>u?.n==="PageInput"),a=o>=0?n.c[o]:void 0,s=a?Xl(a):void 0;if(_d(dg(s),r))return;if(r!==void 0){a?a.c=[Sd(ug(r,s))]:n.c.push(lg("PageInput",ug(r)));return}let l=JSON.parse(s);delete l.data,Object.keys(l).length===0?n.c.splice(o,1):a.c=[Sd(JSON.stringify(l))]}function hg(e){let t=Se(e?.c),r=t.reduce((n,i)=>i.i>n?i.i:n,-1);return Math.max(r,t.length)+1}B.embedAppendIndex=hg;function rW(e,t){var r;let n=e.bag,i=ds(n);if(i&&t){let o=Nd(t),a=Nd(e),s=K9(t),l=J9(e),u=Se(i.node.c),c=[];for(let d of u){let f=d?.n==="controlDescription"&&Zl(d).length>0?_r(co(d,"forControl")):"";if(!f||!o.has(f))c.push(d);else if(a.has(f))if(s.has(f)&&Y9(l.get(f))&&_d(d,Xo(t.bag,f))){let m=Se(d.c).filter(p=>!YS(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 Sn(e)){let a=o.control;if(!Zo(a)||!Re(a.genPage))continue;let s=_r(a.genPage.pageId),l=a.genPage.inputData,u=Oi(a);if(!u){if(tu(a)!==void 0)continue;u=gg(a)}let c=Xo(n,u);if(c){for(let m of Zl(c))tW(m,s,l);continue}i||(i={i:hg(n),node:{n:"controlDescriptions",a:[],c:[]}},n.c.push(i));let d=((r=cg(a.bag,"uniqueid"))!==null&&r!==void 0?r:"").trim(),f=d.startsWith("{")?d:`{${u}}`;i.node.c.push(eW(f,s,l))}}B.reconcileEmbedDescriptions=rW;function nW(e,t){let r=ds(e.bag),n=t!==void 0&&(r===void 0||JSON.stringify(r.node)!==JSON.stringify(t)),i=Sn(e).some(({cell:a})=>Zo(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=ds(o.bag);s?s.node=a:(o.bag=Re(o.bag)?o.bag:{a:[],c:[]},o.bag.c=Se(o.bag.c),o.bag.c.push({i:hg(e.bag),node:a}))}for(let{cell:a}of Sn(o))Zo(a.control)&&(QS(a.control),XS(a));return o}B.commitEmbedState=nW;function iW(e){if(Sn(e).some(({cell:r})=>Zo(r.control)))return!0;let t=ds(e.bag);return Se(t?.node.c).some(r=>r?.n==="controlDescription"&&Zl(r).length>0)}B.mayCommitEmbedState=iW;function QS(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=QS;function XS(e){e.rowspan===void 0&&(e.rowspan=B.GENPAGE_EMBED_ROWSPAN)}B.applyEmbedCellDefaults=XS;function Zo(e){return Re(e)&&e.genPage!==void 0}B.hasGenPage=Zo;function jS(e){return Zo(e.control)&&(!e.control.id||!e.id||tu(e.control)===void 0)}function tu(e){let t=Se(Re(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=tu;function oW(e){if(!Sn(e).some(({cell:r})=>jS(r)))return e;let t=JSON.parse(JSON.stringify(e));for(let{cell:r}of Sn(t)){if(!jS(r))continue;let n=r.control;n.id||(n.id=(0,ig.newId)()),r.id||(r.id=(0,ig.newId)()),tu(n)===void 0&&gg(n)}return t}B.mintEmbedIdentity=oW;function gg(e){let t=(0,ig.newId)(),r=`{${t}}`;if(!Re(e.bag))return e.bag={a:[["uniqueid",r]],c:[]},t;let n=Se(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=Se(e.bag.c),t}B.setUniqueId=gg;function HS(e){return e===null?"null":Array.isArray(e)?"an array":typeof e}function aW(e){let t=Se(e.c).filter(r=>r?.n==="customControl").map(r=>{var n,i;return(i=(n=co(r,"name"))!==null&&n!==void 0?n:co(r,"id"))!==null&&i!==void 0?i:"unnamed"});return[...new Set(t)].join(", ")||"no custom control"}function sW(e){let t=[],r;for(let{cell:n,pointer:i}of Sn(e)){let o=n.control;if(!Re(o))continue;let a=`${i}/control`;if(o.genPage===void 0){lW(e,o,a,t);continue}r=r??Nd(e),uW(e,o,a,r,t)}return t}B.genPageEmbedIssues=sW;function lW(e,t,r,n){if(!mg(e,t))return;let i=eu(Xo(e.bag,Oi(t)));n.push((0,nn.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 uW(e,t,r,n,i){var o;let a=`${r}/genPage`,s=t.genPage;if(!Re(s))i.push((0,nn.issue)(a,"genpage-embed-shape",`genPage must be an object { pageId, inputData? }, got ${HS(s)}.`+(s===null?" To remove an embed, remove the cell (or set the cell's control to null).":"")));else{(typeof s.pageId!="string"||!_r(s.pageId))&&i.push((0,nn.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&&!Re(s.inputData)&&i.push((0,nn.issue)(`${a}/inputData`,"genpage-embed-shape",`genPage.inputData must be a JSON object \u2014 the page reads it as pageInput.data \u2014 got ${HS(s.inputData)}`));for(let m of Object.keys(s))X9.has(m)||i.push((0,nn.issue)(j9.JsonPointer.append(a,m),"genpage-embed-unknown-key",`'${m}' is not a genPage property (pageId, inputData), and would be SILENTLY DROPPED at serialization.`))}Td(t)||i.push((0,nn.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&&KS(t.classId)!==B.CUSTOM_CONTROL_CLASS_ID&&i.push((0,nn.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=fg(e);l!=="Main"&&i.push((0,nn.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=tu(t);u!==void 0&&!_r(u)&&i.push((0,nn.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=Oi(t);if(!c)return;let d=Xo(e.bag,c),f=d?eu(d):void 0;d&&f?.kind==="none"?i.push((0,nn.issue)(a,"genpage-embed-other-control",`this control is already bound to another custom control (${aW(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,nn.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,nn.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 bg=v(fo=>{"use strict";Object.defineProperty(fo,"__esModule",{value:!0});fo.findMissingGenPages=fo.GENPAGE_LOOKUP_CHUNK=void 0;var cW=Lt(),yg=le();fo.GENPAGE_LOOKUP_CHUNK=50;async function dW(e,t,r){let n=[...new Set(t.map(o=>(0,yg.normalizeGuid)(o,"uxagentprojectid")))],i=new Set;for(let o=0;o<n.length;o+=fo.GENPAGE_LOOKUP_CHUNK){let a=n.slice(o,o+fo.GENPAGE_LOOKUP_CHUNK),s="/uxagentprojects/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,yg.odataQuery)([["$select","uxagentprojectid"],["$filter",a.map(u=>`uxagentprojectid eq ${u}`).join(" or ")]]),l=await(0,cW.collectPages)(e,s,r);for(let u of l){let c=u.uxagentprojectid;typeof c=="string"&&c.trim()!==""&&i.add((0,yg.normalizeGuid)(c,"uxagentprojectid"))}}return n.filter(o=>!i.has(o))}fo.findMissingGenPages=dW});var ru=v(_t=>{"use strict";Object.defineProperty(_t,"__esModule",{value:!0});_t.assertSystemFormKind=_t.readSystemFormType=_t.decodeCode=_t.assertSystemFormRecordKind=_t.describeSystemFormType=_t.systemFormKindOf=_t.SYSTEMFORM_KIND_MISMATCH_CODE=void 0;var eN=Q(),fW=ye(),ZS=le();_t.SYSTEMFORM_KIND_MISMATCH_CODE="SYSTEMFORM_KIND_MISMATCH";var pW={0:"dashboard",10:"dashboard",2:"form",6:"form",7:"form",11:"form"},mW={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 Id(e){return Number.isInteger(e)?pW[e]:void 0}_t.systemFormKindOf=Id;function tN(e){var t;return Number.isFinite(e)?`a ${(t=mW[e])!==null&&t!==void 0?t:"systemform"} (type ${e})`:"a systemform whose type could not be read"}_t.describeSystemFormType=tN;function rN(e,t,r,n){let i=tN(r),o=Id(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 hW(e,t,r,n){let i=vg(e?.type);if(Id(i)!==r)throw new eN.SdkError(_t.SYSTEMFORM_KIND_MISMATCH_CODE,rN(t,r,i,n));return i}_t.assertSystemFormRecordKind=hW;function vg(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}_t.decodeCode=vg;async function gW(e,t){return await nN(e,t,!1)}_t.readSystemFormType=gW;async function yW(e,t){return nN(e,t,!0)}async function nN(e,t,r){var n;let o=`/systemforms(${(0,ZS.normalizeGuid)(t,"formId")})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,ZS.odataQuery)([["$select","type"]]),a=await e.get(o);if(!(r&&a.status===404))return(0,fW.ensureSuccess)(a,e.apiUrl(o)),vg((n=a.body)===null||n===void 0?void 0:n.type)}async function bW(e,t,r){let n=await yW(e,t);if(!(n===void 0||Id(n)===r))throw new eN.SdkError(_t.SYSTEMFORM_KIND_MISMATCH_CODE,rN(t,r,n,"delete"))}_t.assertSystemFormKind=bW});var Cg=v(Wr=>{"use strict";Object.defineProperty(Wr,"__esModule",{value:!0});Wr.patchSystemForm=Wr.assertSystemFormContentUnchanged=Wr.readSystemFormRowEtag=Wr.unpublishedSystemFormPath=Wr.FORM_TYPE_IMMUTABLE_CODE=void 0;var on=ye(),vW=le(),Od=Q(),po=ru();Wr.FORM_TYPE_IMMUTABLE_CODE="FORM_TYPE_IMMUTABLE";function wg(e,t="formid"){return`/systemforms(${e})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,vW.odataQuery)([["$select",t]])}Wr.unpublishedSystemFormPath=wg;function iN(e,t){return(0,on.readRowEtag)(e,"systemforms","formid",t)}Wr.readSystemFormRowEtag=iN;async function oN(e,t,r,n,i){(0,on.requireEtag)(i,r,t);let o=(0,on.ensureSuccess)(await e.get(n),e.apiUrl(n)),a=(0,po.assertSystemFormRecordKind)(o.body,t,r,"write"),s=(0,on.readEtag)(o);if(s===null)throw new Od.SdkError(on.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 Od.SdkError(on.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}Wr.assertSystemFormContentUnchanged=oN;async function wW(e,t,r,n,i,o){(0,on.requireEtag)(i,r,t);let a=await iN(e,t);if(a===null)throw new Od.SdkError(on.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 oN(e,t,r,wg(t,"formid,type"),i);if(n.type!==void 0&&(0,po.decodeCode)(n.type)!==s)throw new Od.SdkError(Wr.FORM_TYPE_IMMUTABLE_CODE,`Refusing to push ${r} '${t}': it would change it from ${(0,po.describeSystemFormType)(s)} to ${(0,po.describeSystemFormType)((0,po.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,on.echoWrite)("formid",{"If-Match":a}),u=`/systemforms(${t})${l.query}`;return(0,on.ensureSuccess)(await e.patch(u,n,l.options),e.apiUrl(u)),CW(e,t,r,o)}Wr.patchSystemForm=wW;async function CW(e,t,r,n){let i;try{let o=wg(t,n.select),a=(0,on.ensureSuccess)(await e.get(o),e.apiUrl(o)),s=a.body,l=(0,on.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,po.decodeCode)(s?.type),m=(0,po.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,po.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 _g=v($t=>{"use strict";Object.defineProperty($t,"__esModule",{value:!0});$t.getFormSecurityRoles=$t.setFormSecurityRoles=$t.formApi=$t.readPrimaryCreateRefusal=$t.FORM_GENPAGE_TARGET_UNVERIFIABLE=$t.FORM_GENPAGE_TARGET_NOT_FOUND=void 0;var EW=Lt(),Tt=ye(),an=le(),ea=Q(),Eg=uo(),sN=Dd(),AW=bg(),Ag=Cg(),nu=ru();$t.FORM_GENPAGE_TARGET_NOT_FOUND="FORM_GENPAGE_TARGET_NOT_FOUND";$t.FORM_GENPAGE_TARGET_UNVERIFIABLE="FORM_GENPAGE_TARGET_UNVERIFIABLE";var lN="formid,formxml,name,type,objecttypecode,formpresentation,formactivationstate,uniquename,description,versionnumber",SW={select:lN,required:["name","type","objecttypecode"]},NW="formid,name,type,objecttypecode",_W=2,TW={Main:_W,QuickView:6,QuickCreate:7,Card:11},uN=new WeakMap;function DW(e){return typeof e=="object"&&e!==null?uN.get(e):void 0}$t.readPrimaryCreateRefusal=DW;$t.formApi={async get(e,t){let r=(0,an.normalizeGuid)(t,"id"),n=`/systemforms(${r})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,an.odataQuery)([["$select",lN]]),i=(0,Tt.ensureSuccess)(await e.get(n),e.apiUrl(n));return(0,nu.assertSystemFormRecordKind)(i.body,r,"form","fetch"),{raw:i.body,etag:(0,Tt.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=>TW[u]))],a=[i.length===1?`type eq ${i[0]}`:`(${i.map(u=>`type eq ${u}`).join(" or ")})`];t?.entityLogicalName&&a.push(`objecttypecode eq '${(0,an.odataLiteral)(t.entityLogicalName)}'`);let s=`/systemforms${(0,an.odataQuery)([["$select",NW],["$filter",a.join(" and ")]])}`;return(await(0,EW.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=aN(t);n!==void 0&&await cN(e,Ng(n,"payload"),[]);let i=(0,Tt.echoWrite)("formid"),o=`/systemforms${i.query}`,a=(0,Tt.withClientMintedId)(t,"formid",r),s=Object.freeze({...a}),l=await(0,Tt.resendDeadlockVictim)(()=>e.post(o,{...s},i.options));try{(0,Tt.ensureSuccess)(l,e.apiUrl(o))}catch(u){throw typeof u=="object"&&u!==null&&uN.set(u,{status:l.status,sent:s,desiredId:r}),u}return{id:(0,Tt.resolveCreatedId)(l,"formid","form",r),etag:(0,Tt.readEtag)(l)}},async update(e,t,r,n){let i=(0,an.normalizeGuid)(t,"id"),o=aN(r);return o!==void 0&&await OW(e,i,o,n),(0,Ag.patchSystemForm)(e,i,"form",r,n,SW)},readContentThenToken(e,t){return $t.formApi.get(e,t)},async delete(e,t){let r=(0,an.normalizeGuid)(t,"id");return await(0,nu.assertSystemFormKind)(e,r,"form"),(0,Tt.deleteRecord)(e,"systemforms",r)}};var Sg="DisplayConditions";async function IW(e,t,r){var n,i,o,a;if(r.everyone&&r.roleIds&&r.roleIds.length>0)throw new ea.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,an.normalizeGuid)(t,"formId"),l=`/systemforms(${s})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,an.odataQuery)([["$select","formid,formxml,type"]]),u=(0,Tt.ensureSuccess)(await e.get(l),e.apiUrl(l));(0,nu.assertSystemFormRecordKind)(u.body,s,"form","set the security roles of");let c=(0,Tt.readEtag)(u),d=u.body,f=d?.formxml;if(!f)throw new ea.InvalidArgumentError(`form '${s}' returned no formxml, so its roles cannot be set`);let m=(0,Eg.parseXmlRoot)(f,"<form/>"),p=m.ownerDocument;if(!p)throw new ea.InvalidArgumentError(`form '${s}' produced no owner document`);let h=dN(m,Sg),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 ea.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(Sg),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,an.normalizeGuid)(x,"roleId")}}`),I.appendChild(K)}m.appendChild(I)}let S=(0,Eg.serializeNode)(m);await(0,Ag.assertSystemFormContentUnchanged)(e,s,"form",l,c);let O=await(0,Ag.readSystemFormRowEtag)(e,s),k=`/systemforms(${s})`;(0,Tt.ensureSuccess)(await e.patch(k,{formxml:S},{headers:{"Content-Type":"application/json","If-Match":(0,Tt.requireEtag)(O,"form",s)}}),e.apiUrl(k))}$t.setFormSecurityRoles=IW;function aN(e){let t=e?.formxml;return typeof t=="string"&&t.includes(sN.GENPAGE_CONTROL_NAME)?t:void 0}function Ng(e,t){try{return(0,sN.activeEmbedBindings)(e)}catch(r){throw new ea.SdkError($t.FORM_GENPAGE_TARGET_UNVERIFIABLE,`Refusing to push the form: the ${t} formxml could not be parsed, so the generative pages it embeds cannot be verified (${r instanceof Error?r.message:String(r)}).`)}}async function cN(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,AW.findMissingGenPages)(e,i,"form generative-page preflight");if(o.length>0)throw new ea.SdkError($t.FORM_GENPAGE_TARGET_NOT_FOUND,`Refusing to push the form: it embeds generative page(s) ${o.map(a=>`'${a}'`).join(", ")} that do not exist in this environment. Push the page before the form that embeds it.`)}async function OW(e,t,r,n){var i;(0,Tt.requireEtag)(n,"form",t);let o=`/systemforms(${t})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,an.odataQuery)([["$select","formid,formxml,type"]]),a=(0,Tt.ensureSuccess)(await e.get(o),e.apiUrl(o));(0,nu.assertSystemFormRecordKind)(a.body,t,"form","write");let s=(0,Tt.readEtag)(a);if(s===null||s!==n)throw new ea.SdkError(Tt.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!==""?Ng(l,"server"):[];await cN(e,Ng(r,"payload"),u)}function dN(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 PW(e,t){var r,n;let i=(0,an.normalizeGuid)(t,"formId"),o=`/systemforms(${i})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,an.odataQuery)([["$select","formid,formxml,type"]]),a=(0,Tt.ensureSuccess)(await e.get(o),e.apiUrl(o));(0,nu.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,Eg.parseXmlRoot)(s,"<form/>"),u=dN(l,Sg);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)}:{}}}$t.getFormSecurityRoles=PW});var Tg=v(be=>{"use strict";Object.defineProperty(be,"__esModule",{value:!0});be.deleteSolution=be.getDeploymentSettingsTemplate=be.importSolution=be.exportSolution=be.removeSolutionComponent=be.addSolutionComponent=be.setSolutionVersion=be.createSolution=be.createPublisher=be.getSolution=be.fetchSolutionComponents=be.resolveGenPageComponentType=be.SolutionComponentType=void 0;var RW=Lt(),Ft=ye(),ur=le(),kW=pt(),Yt=Q();be.SolutionComponentType={SavedQuery:26,Workflow:29,SavedQueryVisualization:59,SystemForm:60,AppModule:80};var LW=[be.SolutionComponentType.SavedQuery,be.SolutionComponentType.Workflow,be.SolutionComponentType.SavedQueryVisualization,be.SolutionComponentType.SystemForm,be.SolutionComponentType.AppModule],fN="uxagentproject",pN=new WeakMap;async function vN(e){var t;let r=pN.get(e);if(r!==void 0)return r;let n=`/EntityDefinitions(LogicalName='${fN}')${(0,ur.odataQuery)([["$select","ObjectTypeCode"]])}`,i=await e.get(n);if(i.status===404)return;(0,Ft.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 Yt.SdkError("GENPAGE_COMPONENT_TYPE_UNRESOLVED",`A generative page's solution component type \u2014 the ObjectTypeCode of '${fN}' \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 pN.set(e,o),o}be.resolveGenPageComponentType=vN;var mN=1,hN=0;async function $W(e,t){let r=(0,ur.normalizeGuid)(t,"solutionId"),n=await vN(e),o=[mN,...LW,...n===void 0?[]:[n]].map(c=>`componenttype eq ${c}`).join(" or "),a=`/solutioncomponents${(0,ur.odataQuery)([["$select","objectid,componenttype,rootcomponentbehavior"],["$filter",`_solutionid_value eq ${r} and (${o})`]])}`,s=await(0,RW.collectPages)(e,a,"fetchSolutionComponents"),l=[];for(let c of s){if(typeof c.objectid!="string")continue;let d=Number(c.componenttype);if(d===mN){let f=c.rootcomponentbehavior;(f===hN||f===String(hN))&&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))}be.fetchSolutionComponents=$W;function xW(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 FW(e,t){var r,n,i,o,a,s,l,u,c,d;let f=String(t??"").trim();if(!f)throw new Yt.InvalidArgumentError("getSolution: a solution unique name or id is required.");let m=xW(f)?`solutionid eq ${(0,ur.normalizeGuid)(f,"solutionId")}`:`uniquename eq '${(0,ur.odataLiteral)(f)}'`,p=`/solutions${(0,ur.odataQuery)([["$select","solutionid,uniquename,friendlyname,version,ismanaged"],["$expand","publisherid($select=publisherid,uniquename,customizationprefix,customizationoptionvalueprefix)"],["$filter",m]])}`,b=((n=(r=(0,Ft.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 Yt.InvalidArgumentError(`No solution found for '${t}'.`);let w=b.publisherid;if(!w?.publisherid)throw new Yt.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 Yt.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,ur.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,ur.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}}be.getSolution=FW;async function MW(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,Ft.ensureSuccess)(await(0,Ft.resendDeadlockVictim)(()=>e.post("/publishers",{...n})),e.apiUrl("/publishers")),o=(0,Ft.readCreatedId)(i,"publisherid");if(!o)throw new Yt.InvalidArgumentError(`Dataverse did not return an id for publisher '${t.uniqueName}'`);return{id:o,uniqueName:t.uniqueName}}be.createPublisher=MW;async function UW(e,t){var r;let n=(0,ur.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,Ft.ensureSuccess)(await e.post("/solutions",i),e.apiUrl("/solutions")),a=(0,Ft.readCreatedId)(o,"solutionid");if(!a)throw new Yt.InvalidArgumentError(`Dataverse did not return an id for solution '${t.uniqueName}'`);return{id:a,uniqueName:t.uniqueName}}be.createSolution=UW;async function BW(e,t,r){let i=`/solutions(${(0,ur.normalizeGuid)(t,"solutionId")})`;(0,Ft.ensureSuccess)(await e.patch(i,{version:r}),e.apiUrl(i))}be.setSolutionVersion=BW;async function qW(e,t){var r;let i={ComponentId:(0,ur.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,Ft.ensureSuccess)(await e.post("/AddSolutionComponent",i),e.apiUrl("/AddSolutionComponent"))}be.addSolutionComponent=qW;async function VW(e,t,r,n){let o={SolutionComponent:{"@odata.type":"Microsoft.Dynamics.CRM.solutioncomponent",solutioncomponentid:(0,ur.normalizeGuid)(t,"componentId")},ComponentType:r,SolutionUniqueName:n};(0,Ft.ensureSuccess)(await e.post("/RemoveSolutionComponent",o),e.apiUrl("/RemoveSolutionComponent"))}be.removeSolutionComponent=VW;async function GW(e,t){var r,n;let i={SolutionName:t.solutionName,Managed:(r=t.managed)!==null&&r!==void 0?r:!1},a=(n=(0,Ft.ensureSuccess)(await e.post("/ExportSolution",i),e.apiUrl("/ExportSolution")).body)===null||n===void 0?void 0:n.ExportSolutionFile;if(!a)throw new Yt.InvalidArgumentError(`ExportSolution returned no file for '${t.solutionName}'`);return{base64:a}}be.exportSolution=GW;async function WW(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 Yt.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:t5(t.deploymentSettings),i={OverwriteUnmanagedCustomizations:t.overwriteUnmanagedCustomizations,PublishWorkflows:t.publishWorkflows,CustomizationFile:t.base64,ImportJobId:t.importJobId?(0,ur.normalizeGuid)(t.importJobId,"importJobId"):(0,kW.newId)()};if(!n)return(0,Ft.ensureSuccess)(await e.post("/ImportSolution",i),e.apiUrl("/ImportSolution")),{};if(n.variables.length===0&&n.references.length===0)return(0,Ft.ensureSuccess)(await e.post("/ImportSolution",i),e.apiUrl("/ImportSolution")),{appliedSettings:{environmentVariables:[],connectionReferences:[]}};let o=[];try{let a=await wN(e,t.base64,iu,o),{parameters:s,applied:l}=r5(a,n);return i.ComponentParameters=s,(0,Ft.ensureSuccess)(await e.post("/ImportSolution",i),e.apiUrl("/ImportSolution")),{appliedSettings:l,...o.length>0?{warnings:o}:{}}}catch(a){throw(0,Yt.withCleanupWarnings)(a,o)}}be.importSolution=WW;var iu="importSolution",gN="getDeploymentSettingsTemplate";async function zW(e,t){var r;let n=t?.base64;if(typeof n!="string"||n.length===0)throw new Yt.InvalidArgumentError(`${gN}: '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 wN(e,n,gN,i),a=Pd(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=Pd(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,Yt.withCleanupWarnings)(o,i)}}be.getDeploymentSettingsTemplate=zW;function Pd(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 ta(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function xt(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 wN(e,t,r,n){var i;let a=(i=(0,Ft.ensureSuccess)(await e.post("/StageSolution",{CustomizationFile:t}),e.apiUrl("/StageSolution")).body)===null||i===void 0?void 0:i.StageSolutionResults;try{return HW(a,r)}finally{await jW(e,ta(a)?a.StageSolutionUploadId:void 0,n)}}async function jW(e,t,r){let n;try{n=(0,ur.normalizeGuid)(t,"StageSolutionUploadId")}catch{r.push(`StageSolution's reply named no usable staging upload id (${xt(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,Ft.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 lr(e,t){return new Yt.SdkError("SOLUTION_STAGING_UNREADABLE",`${e}: StageSolution's reply could not be read \u2014 ${t}.${e===iu?" Nothing was imported.":""}`)}function yN(e){return!Array.isArray(e)||e.length===0?"none":`${e.slice(0,5).map(r=>ta(r)&&typeof r.Message=="string"?r.Message:xt(r,200)).join("; ")}${e.length>5?` (+${e.length-5} more)`:""}`}function HW(e,t){if(!ta(e))throw lr(t,`it holds no StageSolutionResults (${xt(e,60)})`);let r=e.StageSolutionStatus;if(r==="Failed"||r===0)throw new Yt.SdkError("SOLUTION_STAGING_FAILED",`${t}: the package did not pass StageSolution in this environment (status ${xt(r)}). Missing dependencies: ${yN(e.MissingDependencies)}. Validation: ${yN(e.SolutionValidationResults)}.${t===iu?" 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 lr(t,`StageSolutionStatus is ${xt(r)}, neither "Passed" nor "Failed"`);let n=e.SolutionComponentsDetails;if(!Array.isArray(n))throw lr(t,`SolutionComponentsDetails is not a list (${xt(n,60)})`);let i=[],o=[],a=new Set,s=new Set;return n.forEach((l,u)=>{let c=`SolutionComponentsDetails[${u}]`;if(!ta(l))throw lr(t,`${c} is not an object`);if(typeof l.ComponentTypeName!="string")throw lr(t,`${c}.ComponentTypeName is not a string`);let d=l.ComponentTypeName.toLowerCase();if(d!=="environmentvariabledefinition"&&d!=="connectionreference")return;let f=KW(l.Attributes,`${c}.Attributes`,t),m=(p,h)=>{let g=f.get(p);if(g==null){if(h)throw lr(t,`${c}.${p} is missing`);return}if(typeof g!="string"||h&&g.length===0)throw lr(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 lr(t,`${c}.schemaname '${p}' is listed twice`);a.add(p.toLowerCase());let h=m("defaultvalue",!1),g=JW(f.get("type"),`${c}.type`,t),b=YW(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 lr(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 KW(e,t,r){if(!ta(e)||!Array.isArray(e.Keys)||!Array.isArray(e.Values))throw lr(r,`${t} is not { Keys: [...], Values: [...] }`);let{Keys:n,Values:i}=e;if(n.length!==i.length)throw lr(r,`${t} has ${n.length} keys but ${i.length} values`);let o=new Map;return n.forEach((a,s)=>{if(typeof a!="string")throw lr(r,`${t}.Keys[${s}] is not a string`);if(o.has(a))throw lr(r,`${t}.Keys lists '${a}' twice`);o.set(a,i[s])}),o}function JW(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 lr(r,`${t} is not a whole number (${xt(e,40)})`)}}function YW(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 lr(r,`${t} is not true or false (${xt(e,40)})`)}}var QW=new Set(["EnvironmentVariables","ConnectionReferences","Workflows","CanvasApps","CopilotAgents","$schema"]),XW=["Workflows","CanvasApps","CopilotAgents"],ZW=new Set(["SchemaName","Value","DefaultValue","TypeId","IsRequired","Name"]),e5=new Set(["LogicalName","ConnectionId","ConnectorId"]);function sr(e,t){return new Yt.InvalidArgumentError(`${iu}: deploymentSettings is not a deployment-settings file this SDK applies \u2014 ${e} ${t}. Nothing was imported.`)}function t5(e){let t="deploymentSettings";if(!ta(e))throw sr(t,`must be an object \u2014 the settings file, parsed (it was ${xt(e,40)})`);for(let l of Object.keys(e))if(!QW.has(l))throw sr(`${t}.${l}`,"is not part of the format (EnvironmentVariables, ConnectionReferences; Workflows, CanvasApps and CopilotAgents only empty; $schema)");for(let l of XW){let u=e[l];if(u!==void 0&&!(Array.isArray(u)&&u.length===0))throw sr(`${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 sr(`${t}.$schema`,"must be a string");let r=l=>{let u=e[l];if(u===void 0)return[];if(!Array.isArray(u))throw sr(`${t}.${l}`,`must be a list (it was ${xt(u,40)})`);return u.map((c,d)=>{if(!ta(c))throw sr(`${t}.${l}[${d}]`,`must be an object (it was ${xt(c,40)})`);return c})},n=(l,u,c)=>{let d=l[u];if(typeof d!="string"||d.length===0)throw sr(c,`must be a non-empty string (it was ${xt(d,40)})`);if(d.trim()!==d)throw sr(c,`must not begin or end with whitespace (it was ${xt(d,60)})`);return d},i=(l,u,c)=>{if(l.has(u.toLowerCase()))throw sr(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(!ZW.has(f))throw sr(`${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 sr(`${c}.Value`,`must be a string \u2014 empty to override nothing (it was ${xt(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(!e5.has(m))throw sr(`${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 sr(`${c}.ConnectionId`,`must be a string \u2014 empty to bind nothing (it was ${xt(f,40)})`);if(f.trim()!==f)throw sr(`${c}.ConnectionId`,`must not begin or end with whitespace (it was ${xt(f,60)})`);if(l.ConnectorId!==void 0&&typeof l.ConnectorId!="string")throw sr(`${c}.ConnectorId`,`must be a string (it was ${xt(l.ConnectorId,40)})`);f.length>0&&o.references.push({name:d,connectionId:f,...l.ConnectorId?{connectorId:l.ConnectorId}:{}})}),o}function bN(e,t=20){return e.length===0?"none":`${e.slice(0,t).join(", ")}${e.length>t?` (+${e.length-t} more)`:""}`}function r5(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=bN(Pd(e.variables,d=>d.SchemaName).map(d=>d.SchemaName)),c=bN(Pd(e.references,d=>d.LogicalName).map(d=>d.LogicalName));throw new Yt.InvalidArgumentError(`${iu}: 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 n5(e,t){let n=`/solutions(${(0,ur.normalizeGuid)(t,"solutionId")})`;(0,Ft.ensureSuccess)(await e.delete(n),e.apiUrl(n))}be.deleteSolution=n5});var _N=v(mt=>{"use strict";Object.defineProperty(mt,"__esModule",{value:!0});mt.recoverFormCreate=mt.solutionMembershipProblem=mt.formWriteMismatches=mt.validateExistingForm=mt.formExistsAtId=mt.isFormRecordAt=mt.MAIN_FORM_TYPE=void 0;var fs=le(),CN=Lt(),EN=Tg();mt.MAIN_FORM_TYPE=2;function Rd(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function kd(e){return e instanceof Error?e.message:String(e)}function Dg(e,t){if(typeof e!="string"||typeof t!="string")return!1;try{return(0,fs.normalizeGuid)(e,"a GUID")===(0,fs.normalizeGuid)(t,"a GUID")}catch{return!1}}function Ig(e,t){return Rd(e)&&Dg(e.formid,t)}mt.isFormRecordAt=Ig;async function i5(e,t){try{return Ig((await e()).raw,t)}catch{return!1}}mt.formExistsAtId=i5;function AN(e,t){let r=e.raw;if(!Rd(r))return{problem:"it is not a record"};if(!Ig(r,t))return{problem:"its formid is not the id this create sent"};if(r.type!==mt.MAIN_FORM_TYPE)return{problem:`its type is not ${mt.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}}mt.validateExistingForm=AN;function SN(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}mt.formWriteMismatches=SN;async function NN(e,t){let r=e.solutionName;if(r)try{let n=await(0,CN.collectPages)(e,`/solutions${(0,fs.odataQuery)([["$select","solutionid,uniquename"],["$filter",`uniquename eq '${(0,fs.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 Rd(i)&&typeof i.uniquename=="string"&&typeof i.solutionid=="string"&&i.uniquename.toLowerCase()===r.toLowerCase()&&(o=(0,fs.normalizeGuid)(i.solutionid,"solutionid")),o===void 0?`the configured solution '${r}' did not resolve to a valid solution of that name`:(await(0,CN.collectPages)(e,`/solutioncomponents${(0,fs.odataQuery)([["$select","objectid,componenttype,_solutionid_value"],["$filter",`_solutionid_value eq ${o} and componenttype eq ${EN.SolutionComponentType.SystemForm} and objectid eq ${t}`]])}`,"createRecovery solution membership")).some(l=>Rd(l)&&l.componenttype===EN.SolutionComponentType.SystemForm&&Dg(l.objectid,t)&&Dg(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 (${kd(n)})`}}mt.solutionMembershipProblem=NN;async function o5(e){try{return await a5(e)}catch(t){return{refused:`the recovery could not be completed (${kd(t)})`}}}mt.recoverFormCreate=o5;async function a5(e){let{client:t,read:r,sent:n,authoredFormType:i,project:o}=e;if(i!=="Main"||n.type!==mt.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 (${kd(f)})`}}let l=AN(s,a);if("problem"in l)return{refused:`the existing row cannot be trusted: ${l.problem}`};let u=SN(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 (${kd(f)})`}}let d=await NN(t,a);return d!==void 0?{refused:d}:{adopted:{artifact:c,etag:l.etag}}}});var $d=v(Ke=>{"use strict";Object.defineProperty(Ke,"__esModule",{value:!0});Ke.disassociateRecords=Ke.associateRecords=Ke.createRecordsBulk=Ke.upsertRecord=Ke.queryAllRecords=Ke.queryRecords=Ke.getRecord=Ke.deleteRecord=Ke.updateRecord=Ke.createRecord=void 0;var Og=Lt(),Nn=ye(),Qt=le(),ps=Q(),Yn=bd();function Ld(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 s5(e,t,r){let i=`/${await(0,Yn.resolveEntitySetName)(e,t)}`,o=(0,Nn.ensureSuccess)(await e.post(i,Ld(r)),e.apiUrl(i)),a=(0,Nn.readCreatedId)(o,`${t}id`);if(!a)throw new ps.InvalidArgumentError(`Dataverse did not return an id for the created '${t}' row`);return{id:a,entityType:t}}Ke.createRecord=s5;async function l5(e,t,r,n){let i=(0,Qt.normalizeGuid)(r,"id"),a=`/${await(0,Yn.resolveEntitySetName)(e,t)}(${i})`;(0,Nn.ensureSuccess)(await e.patch(a,Ld(n)),e.apiUrl(a))}Ke.updateRecord=l5;async function u5(e,t,r){let n=(0,Qt.normalizeGuid)(r,"id"),o=`/${await(0,Yn.resolveEntitySetName)(e,t)}(${n})`;(0,Nn.ensureSuccess)(await e.delete(o),e.apiUrl(o))}Ke.deleteRecord=u5;async function c5(e,t,r,n){let i=(0,Qt.normalizeGuid)(r,"id"),o=await(0,Yn.resolveEntitySetName)(e,t),a=(0,Qt.odataQuery)([["$select",n&&n.length>0?n.join(","):void 0]]),s=`/${o}(${i})${a}`,l=(0,Nn.ensureSuccess)(await e.get(s),e.apiUrl(s)),u=l.body;if(u===null||typeof u!="object"||Array.isArray(u))throw new ps.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,Og.describeMalformedValue)(u)}; refusing to read it as a row.`);return u}Ke.getRecord=c5;function d5(e){return e?.fetchXml?(0,Qt.odataQuery)([["fetchXml",e.fetchXml]]):(0,Qt.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 TN(e,t,r){var n;if(r?.paginate){if(r.top!==void 0)throw new ps.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 ps.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,Yn.resolveEntitySetName)(e,t)}${d5(r)}`;if(r?.paginate)return(0,Og.collectPages)(e,o,"queryRecords");let a=(0,Nn.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 ps.ConnectionError(e.apiUrl(o),a.status,`queryRecords: read returned a malformed page \u2014 expected an OData 'value' array but got ${(0,Og.describeMalformedValue)(s)}; refusing to read it as rows.`);return s}Ke.queryRecords=TN;async function f5(e,t,r){return TN(e,t,{...r,paginate:!0})}Ke.queryAllRecords=f5;function p5(e){if("id"in e)return`(${(0,Qt.normalizeGuid)(e.id,"id")})`;let t=typeof e.value=="string"?`'${(0,Qt.odataPathLiteral)(e.value)}'`:e.value;return`(${(0,Qt.assertODataName)(e.key,"alternate key name")}=${t})`}async function m5(e,t,r,n){let i=p5(r),a=`/${await(0,Yn.resolveEntitySetName)(e,t)}${i}`,s=(0,Nn.ensureSuccess)(await e.patch(a,Ld(n)),e.apiUrl(a)),l=s.status===201,u=(0,Nn.readCreatedId)(s,`${t}id`);return{id:u??("id"in r?(0,Qt.normalizeGuid)(r.id,"id"):""),created:l}}Ke.upsertRecord=m5;async function h5(e,t,r){var n,i;if(r.length===0)return[];let o=await(0,Yn.resolveEntitySetName)(e,t),a=r.map(c=>({"@odata.type":`Microsoft.Dynamics.CRM.${t}`,...Ld(c)})),s=`/${o}/Microsoft.Dynamics.CRM.CreateMultiple`,u=(i=(n=(0,Nn.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 ps.InvalidArgumentError(`CreateMultiple on '${t}' returned ${u.length} id(s) for ${r.length} row(s)`);return u}Ke.createRecordsBulk=h5;async function g5(e,t,r,n){let i=(0,Qt.normalizeGuid)(r,"id"),o=(0,Qt.normalizeGuid)(n.targetId,"targetId"),a=await(0,Yn.resolveEntitySetName)(e,t),s=await(0,Yn.resolveEntitySetName)(e,n.targetEntity),l=(0,Qt.assertODataName)(n.relationshipName,"relationshipName"),u=`/${a}(${i})/${l}/$ref`,c={"@odata.id":e.apiUrl(`/${s}(${o})`)};(0,Nn.ensureSuccess)(await e.post(u,c),e.apiUrl(u))}Ke.associateRecords=g5;async function y5(e,t,r,n,i){let o=(0,Qt.normalizeGuid)(r,"id"),a=(0,Qt.normalizeGuid)(i,"targetId"),s=await(0,Yn.resolveEntitySetName)(e,t),l=(0,Qt.assertODataName)(n,"relationshipName"),u=`/${s}(${o})/${l}(${a})/$ref`;(0,Nn.ensureSuccess)(await e.delete(u),e.apiUrl(u))}Ke.disassociateRecords=y5});var xd=v(sn=>{"use strict";Object.defineProperty(sn,"__esModule",{value:!0});sn.base64ToUtf8=sn.base64ToBytes=sn.bytesToBase64=sn.utf8ToBase64=sn.utf8ToBytes=void 0;var Pg=32768,Tr="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";function ou(){return globalThis}function DN(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 b5(e){let t="";for(let r=0;r<e.length;r+=Pg)t+=String.fromCharCode(...e.subarray(r,r+Pg));return t}function v5(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+="/":Tr.indexOf(n)>=0&&(t+=n)}for(t.length%4===1&&(t=t.slice(0,-1));t.length%4!==0;)t+="=";return t}function w5(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+=Tr[i>>18&63]+Tr[i>>12&63]+Tr[i>>6&63]+Tr[i&63]}let n=e.length-r;if(n===1){let i=e[r]<<16;t+=`${Tr[i>>18&63]}${Tr[i>>12&63]}==`}else if(n===2){let i=e[r]<<16|e[r+1]<<8,o=Tr[i>>18&63],a=Tr[i>>12&63],s=Tr[i>>6&63];t+=`${o}${a}${s}=`}return t}function C5(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=Tr.indexOf(e[o])<<18|Tr.indexOf(e[o+1])<<12|(e[o+2]==="="?0:Tr.indexOf(e[o+2]))<<6|(e[o+3]==="="?0:Tr.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 E5(e){let t=ou();if(t.Buffer)return new Uint8Array(t.Buffer.from(e,"utf8"));let r=t.TextEncoder;return r?new r().encode(e):DN(e)}sn.utf8ToBytes=E5;function A5(e){let t=ou();if(t.Buffer)return t.Buffer.from(e,"utf8").toString("base64");let r=t.TextEncoder;return IN(r?new r().encode(e):DN(e))}sn.utf8ToBase64=A5;function IN(e){let t=ou();return t.Buffer?t.Buffer.from(e).toString("base64"):t.btoa?t.btoa(b5(e)):w5(e)}sn.bytesToBase64=IN;function ON(e){let t=ou();if(t.Buffer)return new Uint8Array(t.Buffer.from(e,"base64"));let r=v5(e);if(t.atob){let n=t.atob(r);return Uint8Array.from(n,i=>i.charCodeAt(0))}return C5(r)}sn.base64ToBytes=ON;function S5(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>=Pg&&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 N5(e){let t=ou();return t.Buffer?t.Buffer.from(e,"base64").toString("utf8"):S5(ON(e))}sn.base64ToUtf8=N5});var $N=v(Qn=>{"use strict";Object.defineProperty(Qn,"__esModule",{value:!0});Qn.deleteWebResource=Qn.getWebResource=Qn.updateWebResource=Qn.createWebResource=void 0;var _5=Qr(),ra=ye(),au=le(),Rg=xd(),ms=Q(),T5={html:1,css:2,js:3,xml:4,png:5,jpg:6,gif:7,xsl:9,ico:10,svg:11,resx:12};function PN(e){if(e.contentBase64!==void 0)return e.contentBase64;if(e.content!==void 0)return(0,Rg.utf8ToBase64)(e.content)}async function RN(e,t){return(0,_5.publishWebResourceById)(e,t)}async function kN(e,t,r){try{await RN(e,t)}catch(n){let i=r?`Web resource '${r.name}' (${t})`:`Web resource ${t}`,o=`write its content again with updateWebResource('${t}', \u2026), which publishes and verifies again`+(r?" \u2014 it exists, and a second create of this name is refused":""),a=(0,ra.isConcurrencyLockRefusalError)(n)?`Another customization operation holds the environment's lock, and content has been observed missing after a publish the lock refused, so publishing again alone may not recover it: once the lock frees, ${o}.`:`Resolve that failure first, then ${o}.`;throw(0,ms.attachCause)(new ms.WebResourceUnverifiedError(t,r?.name,`${i} was written, but publishing it failed, so whether its published content is what was sent is unconfirmed (${n instanceof Error?n.message:String(n)}). ${a}`),n)}}function D5(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(e[r]!==t[r])return!1;return!0}async function LN(e,t,r,n){var i;let o=n?`Web resource '${n.name}' (${t})`:`Web resource ${t}`,a=n?`It exists: write its content again with updateWebResource('${t}', \u2026), which publishes and verifies again \u2014 a second create of this name is refused.`:"Writing it again is safe.",s=c=>new ms.WebResourceUnverifiedError(t,n?.name,`${o} ${c} ${a}`),l=`/webresourceset(${t})${(0,au.odataQuery)([["$select","content"]])}`,u;try{u=(i=(0,ra.ensureSuccess)(await e.get(l),e.apiUrl(l)).body)===null||i===void 0?void 0:i.content}catch(c){throw(0,ms.attachCause)(s("was written and published, but reading its published content back failed, so whether the write applied is unknown."),c)}if(typeof u!="string")throw s("was written and published, but the read-back carried no content, so whether the write applied is unknown.");if(!D5((0,Rg.base64ToBytes)(u),(0,Rg.base64ToBytes)(r)))throw s("was written and published, but the published content is not what was sent, so the write did not apply.")}async function I5(e,t){var r;let n=PN(t);if(n===void 0)throw new ms.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:T5[t.type],content:n};t.description&&(i.description=t.description);let o=(0,ra.ensureSuccess)(await e.post("/webresourceset",i),e.apiUrl("/webresourceset")),a=(0,ra.readCreatedId)(o,"webresourceid");if(!a)throw new ms.InvalidArgumentError(`Dataverse did not return an id for web resource '${t.name}'`);return t.publish!==!1&&(await kN(e,a,{name:t.name}),await LN(e,a,n,{name:t.name})),{id:a,name:t.name}}Qn.createWebResource=I5;async function O5(e,t,r){let n=(0,au.normalizeGuid)(t,"id"),i={},o=PN(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,ra.ensureSuccess)(await e.patch(a,i),e.apiUrl(a)),r.publish!==!1&&(o!==void 0?(await kN(e,n,void 0),await LN(e,n,o,void 0)):await RN(e,n))}Qn.updateWebResource=O5;async function P5(e,t){var r;let i=`/webresourceset(${(0,au.normalizeGuid)(t,"id")})${(0,au.odataQuery)([["$select","name,displayname,webresourcetype,content,description"]])}`;return(r=(0,ra.ensureSuccess)(await e.get(i),e.apiUrl(i)).body)!==null&&r!==void 0?r:{}}Qn.getWebResource=P5;async function R5(e,t){let n=`/webresourceset(${(0,au.normalizeGuid)(t,"id")})`;(0,ra.ensureSuccess)(await e.delete(n),e.apiUrl(n))}Qn.deleteWebResource=R5});var Fd=v(Dt=>{"use strict";Object.defineProperty(Dt,"__esModule",{value:!0});Dt.applyAppSettings=Dt.setAppSetting=Dt.readAppSettings=Dt.resolveSettingDefinitions=Dt.APP_SETTING_UNSET=Dt.APP_SETTING_OFF=Dt.APP_SETTING_ON=Dt.HEADER_AND_NAVIGATION_REFRESH=void 0;var hs=ye(),Pi=le();Dt.HEADER_AND_NAVIGATION_REFRESH="HeaderAndNavigationRefresh";Dt.APP_SETTING_ON="2";Dt.APP_SETTING_OFF="1";Dt.APP_SETTING_UNSET="0";function MN(e,t){return"/appsettings/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,Pi.odataQuery)([["$select",e],["$filter",t]])}async function UN(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,Pi.odataLiteral)(c)}'`).join(" or "),s=`/settingdefinitions${(0,Pi.odataQuery)([["$select","settingdefinitionid,uniquename,displayname"],["$filter",a]])}`,u=((n=(r=(0,hs.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}Dt.resolveSettingDefinitions=UN;async function k5(e,t){var r,n,i,o;let a=(0,Pi.normalizeGuid)(t,"App id"),s=MN("appsettingid,value,_settingdefinitionid_value",`_parentappmoduleid_value eq ${a}`),u=((n=(r=(0,hs.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,Pi.normalizeGuid)(h,"Setting definition id")}`).join(" or "),m=`/settingdefinitions${(0,Pi.odataQuery)([["$select","settingdefinitionid,uniquename,displayname"],["$filter",f]])}`,p=(0,hs.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}:{}}})}Dt.readAppSettings=k5;async function xN(e,t,r){var n,i,o;let a=MN("appsettingid,value",`_parentappmoduleid_value eq ${t} and _settingdefinitionid_value eq ${r}`),l=((i=(n=(0,hs.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 BN(e,t,r,n){let i=(0,Pi.normalizeGuid)(t,"App id"),a=(await UN(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,Pi.normalizeGuid)(s,"Setting definition id"),u=await xN(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,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 xN(e,i,l)}catch{p=void 0}if(p)return FN(e,p,n);throw f&&(0,hs.ensureSuccess)(f,e.apiUrl(c)),m}Dt.setAppSetting=BN;async function FN(e,t,r){if(t.value===r)return"unchanged";let n=`/appsettings(${(0,Pi.normalizeGuid)(t.id,"App setting id")})`;return(0,hs.ensureSuccess)(await e.patch(n,{value:r}),e.apiUrl(n)),"updated"}async function L5(e,t,r){var n;let i=[];for(let[o,a]of Object.entries(r??{}))try{await BN(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}Dt.applyAppSettings=L5});var Ud=v(Md=>{"use strict";Object.defineProperty(Md,"__esModule",{value:!0});Md.HEADER_NAV_BOOLEAN_RULE=void 0;Md.HEADER_NAV_BOOLEAN_RULE="headerAndNavigationRefresh-must-be-boolean"});var $g=v(ke=>{"use strict";Object.defineProperty(ke,"__esModule",{value:!0});ke.compileGenPage=ke.legacyEnumsNeeded=ke.createGenPageTypeScriptLoader=ke.acceptGenPageTypeScript=ke.isLoadableGenPageOutput=ke.runtimeTypesImportSpans=ke.GENPAGE_RUNTIME_TYPES_END=ke.GENPAGE_RUNTIME_TYPES_BEGIN=ke.GENPAGE_TYPESCRIPT_VERSION=void 0;var gs=Q();ke.GENPAGE_TYPESCRIPT_VERSION="5.8.3";ke.GENPAGE_RUNTIME_TYPES_BEGIN="// --- BEGIN GENERATED RUNTIME TYPES ---";ke.GENPAGE_RUNTIME_TYPES_END="// --- END GENERATED RUNTIME TYPES ---";var _n="./RuntimeTypes",$5="'\"`",qN=/\s/;function x5(e){return e===10||e===13||e===8232||e===8233}function F5(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 zN(e){let t=[],r=_n.length;for(let l=e.indexOf(_n);l!==-1;l=e.indexOf(_n,l+1)){let u=l-1;u>=0&&$5.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&&qN.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&&qN.test(e[d]);)d+=1;n.push({start:l,end:d}),u=d}}l=e.indexOf("import",u)}return n}ke.runtimeTypesImportSpans=zN;var M5=/\b(?:import\s*['"]|export\s)/;function U5(e){let t=F5(/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&&!x5(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 B5(e){return e!==void 0&&e!==""&&(M5.test(e)||U5(e))}ke.isLoadableGenPageOutput=B5;var VN=["transpileModule","createSourceFile","createProgram","getParseTreeNode","flattenDiagnosticMessageText","forEachChild","getModifiers","canHaveModifiers","isImportDeclaration","isExportDeclaration","isExportAssignment","isStringLiteral"];function jN(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?VN.filter(s=>typeof n?.[s]!="function"):[...VN];if(!n||i.length>0)throw new gs.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@${ke.GENPAGE_TYPESCRIPT_VERSION}'s lib/typescript.js.`);let o=typeof n.version=="string"?n.version:"",a=ke.GENPAGE_TYPESCRIPT_VERSION.split(".").slice(0,2).join(".");if(o.split(".").slice(0,2).join(".")!==a)throw new gs.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 (${ke.GENPAGE_TYPESCRIPT_VERSION}). Another version can emit different JavaScript for the same page. Supply typescript@${ke.GENPAGE_TYPESCRIPT_VERSION}.`);return n}ke.acceptGenPageTypeScript=jN;function q5(e){let t;return()=>{if(!t){if(e===void 0)return Promise.reject(new gs.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@${ke.GENPAGE_TYPESCRIPT_VERSION}'s lib/typescript.js. Nothing was written.`));t=Promise.resolve().then(()=>typeof e=="function"?e():e).then(jN).catch(r=>{throw t=void 0,r instanceof gs.SdkError?r:new gs.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}}ke.createGenPageTypeScriptLoader=q5;var HN=e=>`${e.kind}:${e.pos}:${e.end}`;function V5(e,t){return()=>r=>{let n=i=>{let o=e.getParseTreeNode(i);o&&t.add(HN(o)),e.forEachChild(i,n)};return n(r),r}}function Lg(e){return{target:e.ScriptTarget.ES5,module:e.ModuleKind.ES2020,jsx:e.JsxEmit.React}}var G5=2301;function GN(e,t,r){var n;let i=e.transpileModule(t,{compilerOptions:Lg(e),reportDiagnostics:!0,...r?{transformers:{after:[V5(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 WN=e=>e.startsWith(".")||e.startsWith("/"),Bd={line:1,column:1};function kg(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):Bd},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 Bd}}}function W5(e,t,r,n){var i,o;let a=[],s=kg(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===_n?l(s.statement(C,"export"),d,"a page cannot re-export from './RuntimeTypes': that module does not exist at runtime"):C!==void 0&&WN(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!==_n){WN(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(Bd,"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 KN(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===G5&&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===_n},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 z5(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=KN(e,t,Lg(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(HN(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 j5(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===_n)}function JN(e,t){return t.statements.filter(r=>e.isImportDeclaration(r)&&e.isStringLiteral(r.moduleSpecifier)&&r.moduleSpecifier.text===_n).map(r=>r.getStart(t))}function H5(e,t){let r=e.createSourceFile("page.js",t,e.ScriptTarget.ES2020,!0,e.ScriptKind.JS),n=JN(e,r),i=new Set(n),o,a="",s=0;for(let l of zN(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 K5(e,t,r){let n=new Set(JN(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 Bd}function YN(e,t,r){if(!r||r.size===0)return[];let n=KN(e,t,{...Lg(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===_n&&((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))}ke.legacyEnumsNeeded=YN;function J5(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 Y5(e,t,r,n){var i;let o=new Set,a=GN(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=J5(r,n,YN(e,l,n)),c=[...W5(e,l,s,u),...z5(e,s,u,o)];if(!u?.text)return{code:a.code,diagnostics:c};let d=GN(e,u.text);if(d.diagnostics.length>0)throw new gs.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=H5(e,a.code),m=f.code;if(c.length===0&&(!((i=f.inexact)===null||i===void 0)&&i.swallows))c.push({...kg(e,s).statement(_n,"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({...K5(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&&j5(e,m)&&c.push({...kg(e,s).statement(_n,"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:[ke.GENPAGE_RUNTIME_TYPES_BEGIN,d.code,ke.GENPAGE_RUNTIME_TYPES_END,m].join(`+`}});var $k=C(wg=>{"use strict";Object.defineProperty(wg,"__esModule",{value:!0});wg.generateGenPageRuntimeTypes=void 0;var kk=yE(),Qu=Y(),Rk=new Set(["None","ColorsDefaultsConstraints","ColorsDefaultsConstraintsDescriptions"]),Xu="generateGenPageRuntimeTypes";async function eZ(e,t,n){let r=tZ(t),i=nZ(n),o=[];for(let a of r){let s=await e(a);if(s.columnDetailComplete!==!0)throw new Qu.SdkError("GENPAGE_DATA_SOURCE_INCOMPLETE",`${Xu}: 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,kk.renderGenPageAuthoringTypes)(o,i)}wg.generateGenPageRuntimeTypes=eZ;function tZ(e){if(!Array.isArray(e))throw new Qu.InvalidArgumentError(`${Xu}: dataSources must be an array of table logical names`);let t=new Set;for(let n of e){if(typeof n!="string"||!kk.TABLE_LOGICAL_NAME.test(n))throw new Qu.InvalidArgumentError(`${Xu}: a data source must be a table logical name (lowercase, e.g. 'account'), got '${String(n)}'`);if(t.has(n))throw new Qu.InvalidArgumentError(`${Xu}: data source '${n}' is listed twice; a page's dataSources hold each table once`);t.add(n)}return[...t]}function nZ(e){if(e===void 0)return"None";if(e===null||typeof e!="object"||Array.isArray(e))throw new Qu.InvalidArgumentError(`${Xu}: options must be an object`);let t=Object.keys(e).filter(r=>r!=="detail");if(t.length>0)throw new Qu.InvalidArgumentError(`${Xu}: unknown option '${t[0]}' (the only option is 'detail')`);let n=e.detail===void 0?"None":e.detail;if(typeof n!="string"||!Rk.has(n))throw new Qu.InvalidArgumentError(`${Xu}: detail must be one of ${[...Rk].map(r=>`'${r}'`).join(", ")}, got '${String(n)}'`);return n}});var vE=C(za=>{"use strict";Object.defineProperty(za,"__esModule",{value:!0});za.readProvisionedLanguages=za.getEnvironmentLanguages=za.ENVIRONMENT_LANGUAGES_UNREADABLE_CODE=void 0;var rZ=Y(),Mk=pe();za.ENVIRONMENT_LANGUAGES_UNREADABLE_CODE="ENVIRONMENT_LANGUAGES_UNREADABLE";var Lk="/organizations?$select=languagecode",xk="/RetrieveProvisionedLanguages()",iZ="/RetrieveAvailableLanguages()";function Fk(e,t){return new rZ.SdkError(za.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 Uk(e){return typeof e=="number"&&Number.isInteger(e)&&e>0}async function bE(e,t,n,r){let i=(0,Mk.ensureSuccess)(await e.get(t),e.apiUrl(t)).body,o=i?.[n];if(!Array.isArray(o)||o.length===0||!o.every(Uk))throw Fk(r,`answered no list of language codes in '${n}'`);return[...new Set(o)]}async function oZ(e){var t;let n=(0,Mk.ensureSuccess)(await e.get(Lk),e.apiUrl(Lk)).body,r=n?.value,i=Array.isArray(r)&&r.length===1?(t=r[0])===null||t===void 0?void 0:t.languagecode:void 0;if(!Uk(i))throw Fk("the organization read","did not answer one row with a language code");let o=await bE(e,xk,"RetrieveProvisionedLanguages","RetrieveProvisionedLanguages"),a=await bE(e,iZ,"LocaleIds","RetrieveAvailableLanguages");return{baseLanguage:i,available:a,provisioned:o}}za.getEnvironmentLanguages=oZ;function aZ(e){return bE(e,xk,"RetrieveProvisionedLanguages","RetrieveProvisionedLanguages")}za.readProvisionedLanguages=aZ});var Zf=C(gn=>{"use strict";Object.defineProperty(gn,"__esModule",{value:!0});gn.projectConnectorOperationSchema=gn.projectConnectorOperations=gn.validateConnectorSwagger=gn.CONNECTOR_SCHEMA_TOO_LARGE_CODE=gn.CONNECTOR_OPERATION_NOT_FOUND_CODE=gn.CONNECTOR_SWAGGER_UNSUPPORTED_CODE=gn.CONNECTIVITY_RESPONSE_UNREADABLE_CODE=void 0;var Xf=Y();gn.CONNECTIVITY_RESPONSE_UNREADABLE_CODE="CONNECTIVITY_RESPONSE_UNREADABLE";gn.CONNECTOR_SWAGGER_UNSUPPORTED_CODE="CONNECTOR_SWAGGER_UNSUPPORTED";gn.CONNECTOR_OPERATION_NOT_FOUND_CODE="CONNECTOR_OPERATION_NOT_FOUND";gn.CONNECTOR_SCHEMA_TOO_LARGE_CODE="CONNECTOR_SCHEMA_TOO_LARGE";var qk=64,Bk=128,Vk=2e5,Gk=4e6,sZ=new Set(["get","put","post","delete","patch","head","options"]),uZ=new Set(["query","header","path","formData","body"]);function Wi(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function yo(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Wn(e){return e===void 0?"absent":e===null?"null":Array.isArray(e)?"an array":`a ${typeof e}`}function an(e){return e.length>80?`'${e.slice(0,80)}\u2026'`:`'${e}'`}function Nt(e,t){return new Xf.SdkError(gn.CONNECTIVITY_RESPONSE_UNREADABLE_CODE,`The connector's swagger could not be read: ${e} ${t}. Nothing was skipped or assumed in its place.`)}function js(e,t){return new Xf.SdkError(gn.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 lZ(e,t){let n=e;for(let r of t.slice(2).split("/")){let i=r.replace(/~1/g,"/").replace(/~0/g,"~");if(typeof n!="object"||n===null||!yo(n,i))return{found:!1};n=n[i]}return{found:!0,value:n}}function AE(e,t,n){if(!t.startsWith("#/"))throw js(n,`has a $ref that is not a local '#/\u2026' pointer (${an(t)})`);if(t.includes("%"))throw js(n,`has a $ref with a percent-encoded character (${an(t)}), which is not decoded`);if(/~(?![01])/.test(t))throw Nt(n,`has a $ref with a malformed escape (${an(t)}): a '~' not followed by 0 or 1`);let r=lZ(e,t);if(!r.found)throw Nt(n,`has a $ref that does not resolve (${an(t)})`);return r.value}function Eg(e,t){if(yo(e,"$ref")){if(typeof e.$ref!="string")throw Nt(t,`has a $ref that is ${Wn(e.$ref)}, not a string`);return e.$ref}}function cZ(e,t,n){if(!Wi(t))throw Nt(n,`is ${Wn(t)}, not a parameter object`);let r=t,i=Eg(t,n);if(i!==void 0){let s=AE(e,i,n);if(!Wi(s))throw Nt(n,`has a $ref (${an(i)}) that resolves to ${Wn(s)}, not a parameter object`);if(Eg(s,`${n} \u2192 ${an(i)}`)!==void 0)throw js(n,`has a $ref (${an(i)}) to a parameter that is itself a $ref`);r=s}if(typeof r.name!="string")throw Nt(n,"has no string name");let o=r.in;if(typeof o!="string"||!uZ.has(o))throw Nt(n,`has an in that is ${typeof o=="string"?an(o):Wn(o)}, not one of query, header, path, formData or body`);if(yo(r,"required")&&typeof r.required!="boolean")throw Nt(n,`has a required that is ${Wn(r.required)}, not a boolean`);let a=r["x-ms-visibility"];if(yo(r,"x-ms-visibility")&&typeof a!="string")throw Nt(n,`has an x-ms-visibility that is ${Wn(a)}, not a string`);return{name:r.name,in:o,required:r.required===!0,internal:a==="internal"}}function wE(e){return`${e.in}:${e.name}`}function Wk(e,t,n){if(!yo(t,"parameters"))return[];let r=t.parameters;if(!Array.isArray(r))throw Nt(n,`has parameters that are ${Wn(r)}, not an array`);let i=new Set;return r.map((o,a)=>{let s=`${n} parameters[${a}]`,u=cZ(e,o,s),l=wE(u);if(i.has(l))throw Nt(s,`repeats the parameter ${an(u.name)} in ${an(u.in)}, which must be unique in its list`);return i.add(l),u})}function zk(e,t,n){let r=t.responses;if(!yo(r,"200"))return;let i=`${n} response 200`,o=r[200];if(!Wi(o))throw Nt(i,`is ${Wn(o)}, not a response object`);let a=o,s=Eg(o,i);if(s!==void 0){if(s.startsWith("#/")&&!/^#\/responses\/[^/]+$/.test(s))throw Nt(i,`has a $ref (${an(s)}) that does not name a response ('#/responses/<name>')`);let u=AE(e,s,i);if(!Wi(u))throw Nt(i,`has a $ref (${an(s)}) that resolves to ${Wn(u)}, not a response object`);if(Eg(u,`${i} \u2192 ${an(s)}`)!==void 0)throw js(i,`has a $ref (${an(s)}) to a response that is itself a $ref`);a=u}if(yo(a,"content"))throw js(i,"is an OpenAPI 3 response (it has content), not a Swagger 2.0 one");if(yo(a,"schema")){if(!Wi(a.schema))throw Nt(i,`has a schema that is ${Wn(a.schema)}, not an object`);return a.schema}}function jk(e,t,n){if(!yo(e,t))return;let r=e[t];if(typeof r!="string")throw Nt(n,`has a ${t} that is ${Wn(r)}, not a string`);return r}function dZ(e,t,n,r,i){if(!Wi(t))throw Nt(n,`is ${Wn(t)}, not an operation object`);let o=t.operationId;if(typeof o!="string")throw Nt(n,`has no string operationId (${Wn(o)})`);if(r.has(o))throw Nt(n,`repeats the operationId ${an(o)}, which must be unique in the document`);r.add(o);let a=jk(t,"summary",n),s=jk(t,"description",n),u=Wk(e,t,n);if(!Wi(t.responses))throw Nt(n,`has no responses object (${Wn(t.responses)})`);return zk(e,t,n),{id:o,summary:a,description:s,node:t,where:n,parameters:u,pathParameters:i}}function CE(e){if(!Wi(e))throw Nt("the document",`is ${Wn(e)}, not an object`);if(yo(e,"openapi"))throw js("the document","is OpenAPI 3 (it has an openapi member), not Swagger 2.0");if(!yo(e,"swagger"))throw Nt("the document","names no Swagger version");if(e.swagger!=="2.0")throw js("the document",`declares swagger ${an(String(e.swagger))}, not 2.0`);let t=e.paths;if(!Wi(t))throw Nt("the document",`has paths that are ${Wn(t)}, not an object`);let n=[],r=new Set;for(let i of Object.keys(t)){let o=t[i],a=`paths[${an(i)}]`;if(!Wi(o))throw Nt(a,`is ${Wn(o)}, not a path item object`);let s=[];for(let u of Object.keys(o))if(sZ.has(u.toLowerCase()))n.push(dZ(e,o[u],`${a}.${u}`,r,s));else if(u==="parameters")for(let l of Wk(e,o,a))s.push(l);else if(!u.startsWith("x-"))throw js(a,`has a ${an(u)} member; a path item may hold only HTTP methods, parameters and x- extensions`)}return{document:e,operations:n}}function fZ(e){CE(e)}gn.validateConnectorSwagger=fZ;var EE=class{constructor(t,n){this.root=t,this.where=n,this.nodes=0,this.characters=0,this.path=[]}run(t){return this.visit(t,0)}tooLarge(t){return new Xf.SdkError(gn.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>Vk)throw this.tooLarge(`more than ${Vk} nodes`)}text(t){if(this.characters+=t,this.characters>Gk)throw this.tooLarge(`more than ${Gk} characters of strings and keys`)}checkDepth(t){if(t>Bk)throw this.tooLarge(`nesting deeper than ${Bk} levels`)}visit(t,n){if(this.checkDepth(n),Array.isArray(t)){this.node();let r=[];for(let i of t)r.push(this.visit(i,n+1));return r}if(Wi(t)){if(typeof t.$ref=="string")return this.reference(t.$ref,n);this.node();let r={};for(let i of Object.keys(t))this.text(i.length),Object.defineProperty(r,i,{value:this.visit(t[i],n+1),enumerable:!0,writable:!0,configurable:!0});return r}return this.node(),typeof t=="string"&&this.text(t.length),t}reference(t,n){if(this.path.includes(t)){this.checkDepth(n+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>=qk)throw this.tooLarge(`a $ref chain of more than ${qk} references`);let r=AE(this.root,t,this.where);if(!Wi(r))throw Nt(this.where,`has a schema $ref (${an(t)}) that resolves to ${Wn(r)}, not a schema object`);this.path.push(t);let i=this.visit(r,n);return this.path.pop(),i}};function pZ(e){let{operations:t}=CE(e);return{operations:t.map(n=>{var r,i;return{name:n.id,summary:(i=(r=n.summary)!==null&&r!==void 0?r:n.description)!==null&&i!==void 0?i:null}})}}gn.projectConnectorOperations=pZ;function mZ(e,t){if(typeof t!="string"||t==="")throw new Xf.InvalidArgumentError("operationId must be a non-empty string.");let{document:n,operations:r}=CE(e),i=r.find(l=>l.id===t);if(!i)throw new Xf.SdkError(gn.CONNECTOR_OPERATION_NOT_FOUND_CODE,`The connector has no operation with the id ${an(t)} (ids are matched exactly, case included). List the connector\u2019s operations to see its ids.`);let o=new Set(i.parameters.map(wE)),a=[...i.parameters,...i.pathParameters.filter(l=>!o.has(wE(l)))].filter(l=>!l.internal).map(({name:l,required:c})=>({name:l,required:c})),s=zk(n,i.node,i.where),u=s===void 0?{}:new EE(n,`${i.where} (${an(i.id)})`).run(s);return{operation:i.id,parameters:a,response:u}}gn.projectConnectorOperationSchema=mZ});var Zu=C(se=>{"use strict";Object.defineProperty(se,"__esModule",{value:!0});se.readEnvironmentName=se.readConnection=se.connectorShortName=se.CONNECTOR_PREFIX=se.connectivityUnauthorized=se.errorCodeOf=se.messageOf=se.environmentFilter=se.unreadable=se.connectivityCloudOf=se.sameOrigin=se.parseUrl=se.bounded=se.kindOf=se.isObject=se.CONNECTOR_RUNTIME_UNSUPPORTED_CODE=se.CONNECTOR_NOT_TABULAR_CODE=se.CONNECTIVITY_ROUTE_DECOMMISSIONED_CODE=se.CONNECTIVITY_UNAUTHORIZED_CODE=se.CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE=se.CONNECTIVITY_CLOUD_UNSUPPORTED_CODE=se.CONNECTIVITY_NOT_CONFIGURED_CODE=void 0;var ep=Y(),hZ=pe(),gZ=Zf();se.CONNECTIVITY_NOT_CONFIGURED_CODE="CONNECTIVITY_NOT_CONFIGURED";se.CONNECTIVITY_CLOUD_UNSUPPORTED_CODE="CONNECTIVITY_CLOUD_UNSUPPORTED";se.CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE="CONNECTIVITY_ENVIRONMENT_UNVERIFIED";se.CONNECTIVITY_UNAUTHORIZED_CODE="CONNECTIVITY_UNAUTHORIZED";se.CONNECTIVITY_ROUTE_DECOMMISSIONED_CODE="CONNECTIVITY_ROUTE_DECOMMISSIONED";se.CONNECTOR_NOT_TABULAR_CODE="CONNECTOR_NOT_TABULAR";se.CONNECTOR_RUNTIME_UNSUPPORTED_CODE="CONNECTOR_RUNTIME_UNSUPPORTED";function si(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}se.isObject=si;function Nc(e){return e===void 0?"absent":e===null?"null":Array.isArray(e)?"an array":`a ${typeof e}`}se.kindOf=Nc;function _c(e,t=200){return e.length>t?`${e.slice(0,t)}\u2026`:e}se.bounded=_c;function Kk(e){try{let t=new URL(e);return{protocol:t.protocol,host:t.host,origin:t.origin}}catch{return}}se.parseUrl=Kk;function yZ(e,t){return e.protocol===t.protocol&&e.host.toLowerCase()===t.host.toLowerCase()}se.sameOrigin=yZ;var bZ=/^[a-z0-9-]+\.crm(\d*)\.dynamics\.com$/,vZ=/^[a-z0-9-]+\.crmtest\.dynamics\.com$/;function wZ(e){let t=Kk(e),n=t?t.host.toLowerCase():"";if(vZ.test(n))return"Test";let r=bZ.exec(n);return r&&r[1]!=="9"?"Public":"Unsupported"}se.connectivityCloudOf=wZ;function na(e,t){return new ep.SdkError(gZ.CONNECTIVITY_RESPONSE_UNREADABLE_CODE,`${e} could not be read: ${t}. Nothing was skipped or assumed in its place.`)}se.unreadable=na;function EZ(e){return encodeURIComponent(`environment eq '${e.replace(/'/g,"''")}'`)}se.environmentFilter=EZ;function AZ(e){if(typeof e=="string"&&e.length>0)return _c(e,500);if(si(e)){let t=si(e.error)?e.error.message:void 0;for(let n of[t,e.Message,e.message])if(typeof n=="string")return _c(n,500)}return"request failed"}se.messageOf=AZ;function Jk(e){return si(e)&&si(e.error)?e.error.code:void 0}se.errorCodeOf=Jk;function CZ(e){if(si(e)&&si(e.error)&&si(e.error.innererror))return e.error.innererror.code}function SZ(e,t,n){let r=[],i=Jk(t);typeof i=="string"&&i.length>0&&r.push(_c(i,80));let o=CZ(t);typeof o=="string"&&o.length>0&&r.push(_c(o,80));let a=r.length>0?` (${r.join("; ")})`:"";return(0,ep.attachCause)(new ep.SdkError(se.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.`),n)}se.connectivityUnauthorized=SZ;se.CONNECTOR_PREFIX="/providers/Microsoft.PowerApps/apis/";var NZ=/^[A-Za-z0-9_.-]{1,128}$/,_Z=new Set(["shared_logicflows","shared_powerflows","shared_pqogenericconnector"]);function IZ(e){if(typeof e=="string"){let n=e.slice(0,se.CONNECTOR_PREFIX.length).toLowerCase()===se.CONNECTOR_PREFIX.toLowerCase()?e.slice(se.CONNECTOR_PREFIX.length):e;if(NZ.test(n)&&!/^\.{1,2}$/.test(n))return n}throw new ep.InvalidArgumentError(`connector must be a connector's short name ('shared_office365users') or its full API id ('${se.CONNECTOR_PREFIX}shared_office365users'); got ${typeof e=="string"?`'${_c(e,80)}'`:Nc(e)}.`)}se.connectorShortName=IZ;function TZ(e,t,n){let r=`Connection row ${t}`;if(!si(e))throw na(r,`it is ${Nc(e)}, not an object`);let i=e.properties;if(!si(i))throw na(r,`its properties are ${Nc(i)}, not an object`);let o=i.apiId;if(typeof o!="string"||o.slice(0,se.CONNECTOR_PREFIX.length).toLowerCase()!==se.CONNECTOR_PREFIX.toLowerCase())throw na(r,`its apiId is not '${se.CONNECTOR_PREFIX}<connector>'`);let a=o.slice(se.CONNECTOR_PREFIX.length);if(a===""||a.includes("/"))throw na(r,"its apiId names no single connector");if(_Z.has(a.toLowerCase()))return;let s=e.name;if(typeof s!="string"||s==="")throw na(r,"it has no name");let u=i.environment,l=si(u)?u.name:void 0;if(typeof l!="string"||l.toLowerCase()!==n.toLowerCase())throw na(r,"it is not a connection of this environment (properties.environment.name)");let c=i.displayName;if(typeof c!="string")throw na(r,`its displayName is ${Nc(c)}, not a string`);let d=i.statuses;if(!Array.isArray(d))throw na(r,`its statuses are ${Nc(d)}, not an array`);return{connectionId:s,displayName:c,connectorId:o,connectorName:a,statuses:d.map(f=>{let p=si(f)?f.status:void 0;if(typeof p!="string")throw na(r,"one of its statuses has no string status");return p})}}se.readConnection=TZ;var Hk="/RetrieveCurrentOrganization(AccessType=@p1)?@p1=Microsoft.Dynamics.CRM.EndpointAccessType'Default'";async function OZ(e){let t=(0,hZ.ensureSuccess)(await e.get(Hk),e.apiUrl(Hk)).body,n=si(t)?t.Detail:void 0,r=si(n)?n.EnvironmentId:void 0;if(typeof r!="string"||r==="")throw new ep.SdkError(se.CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE,"The environment of this org could not be verified: the org answered no environment id (RetrieveCurrentOrganization, Detail.EnvironmentId).");return r}se.readEnvironmentName=OZ});var n$=C(ui=>{"use strict";Object.defineProperty(ui,"__esModule",{value:!0});ui.ConnectivityApi=ui.CONNECTIVITY_UNAUTHORIZED_CODE=ui.CONNECTIVITY_ROUTE_DECOMMISSIONED_CODE=ui.CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE=ui.CONNECTIVITY_CLOUD_UNSUPPORTED_CODE=ui.CONNECTIVITY_NOT_CONFIGURED_CODE=void 0;var gr=Y(),DZ=pe(),Cg=Zf(),np=Zu(),rp=Zu();Object.defineProperty(ui,"CONNECTIVITY_NOT_CONFIGURED_CODE",{enumerable:!0,get:function(){return rp.CONNECTIVITY_NOT_CONFIGURED_CODE}});Object.defineProperty(ui,"CONNECTIVITY_CLOUD_UNSUPPORTED_CODE",{enumerable:!0,get:function(){return rp.CONNECTIVITY_CLOUD_UNSUPPORTED_CODE}});Object.defineProperty(ui,"CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE",{enumerable:!0,get:function(){return rp.CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE}});Object.defineProperty(ui,"CONNECTIVITY_ROUTE_DECOMMISSIONED_CODE",{enumerable:!0,get:function(){return rp.CONNECTIVITY_ROUTE_DECOMMISSIONED_CODE}});Object.defineProperty(ui,"CONNECTIVITY_UNAUTHORIZED_CODE",{enumerable:!0,get:function(){return rp.CONNECTIVITY_UNAUTHORIZED_CODE}});var Yk="2016-11-01",PZ="2021-04-01",RZ="https://api.bap.microsoft.com",kZ="https://test.api.bap.microsoft.com",$Z=/^[a-z0-9-]+\.crm(\d*)\.dynamics\.com$/,LZ=/^[a-z0-9-]+\.crmtest\.dynamics\.com$/,Qk="/RetrieveCurrentOrganization(AccessType=@p1)?@p1=Microsoft.Dynamics.CRM.EndpointAccessType'Default'",Ha="/providers/Microsoft.PowerApps/apis/",MZ=/^[A-Za-z0-9_.-]{1,128}$/,xZ=new Set(["shared_logicflows","shared_powerflows","shared_pqogenericconnector"]),FZ="ServiceDecommissioned";function _n(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ws(e){return e===void 0?"absent":e===null?"null":Array.isArray(e)?"an array":`a ${typeof e}`}function ra(e,t=200){return e.length>t?`${e.slice(0,t)}\u2026`:e}function tp(e){try{let t=new URL(e);return{protocol:t.protocol,host:t.host,origin:t.origin}}catch{return}}function Xk(e,t){return e.protocol===t.protocol&&e.host.toLowerCase()===t.host.toLowerCase()}function UZ(e){return/^[a-z0-9][a-z0-9.-]*$/.test(e)&&(e==="api.powerapps.com"||e.endsWith(".api.powerapps.com"))}function zi(e,t){return new gr.SdkError(Cg.CONNECTIVITY_RESPONSE_UNREADABLE_CODE,`${e} could not be read: ${t}. Nothing was skipped or assumed in its place.`)}function Ag(e){return new gr.SdkError(np.CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE,`The environment of this org could not be verified: ${e}. The Power Apps service was not asked about it.`)}function Zk(e){return encodeURIComponent(`environment eq '${e.replace(/'/g,"''")}'`)}function e$(e){if(typeof e=="string"&&e.length>0)return ra(e,500);if(_n(e)){let t=_n(e.error)?e.error.message:void 0;for(let n of[t,e.Message,e.message])if(typeof n=="string")return ra(n,500)}return"request failed"}function qZ(e){return _n(e)&&_n(e.error)?e.error.code:void 0}function t$(e){if(typeof e=="string"){let n=e.slice(0,Ha.length).toLowerCase()===Ha.toLowerCase()?e.slice(Ha.length):e;if(MZ.test(n)&&!/^\.{1,2}$/.test(n))return n}throw new gr.InvalidArgumentError(`connector must be a connector's short name ('shared_office365users') or its full API id ('${Ha}shared_office365users'); got ${typeof e=="string"?`'${ra(e,80)}'`:Ws(e)}.`)}function BZ(e,t,n){let r=`Connection row ${t}`;if(!_n(e))throw zi(r,`it is ${Ws(e)}, not an object`);let i=e.properties;if(!_n(i))throw zi(r,`its properties are ${Ws(i)}, not an object`);let o=i.apiId;if(typeof o!="string"||o.slice(0,Ha.length).toLowerCase()!==Ha.toLowerCase())throw zi(r,`its apiId is not '${Ha}<connector>'`);let a=o.slice(Ha.length);if(a===""||a.includes("/"))throw zi(r,"its apiId names no single connector");if(xZ.has(a.toLowerCase()))return;let s=e.name;if(typeof s!="string"||s==="")throw zi(r,"it has no name");let u=i.environment,l=_n(u)?u.name:void 0;if(typeof l!="string"||l.toLowerCase()!==n.toLowerCase())throw zi(r,"it is not a connection of this environment (properties.environment.name)");let c=i.displayName;if(typeof c!="string")throw zi(r,`its displayName is ${Ws(c)}, not a string`);let d=i.statuses;if(!Array.isArray(d))throw zi(r,`its statuses are ${Ws(d)}, not an array`);return{connectionId:s,displayName:c,connectorId:o,connectorName:a,statuses:d.map(f=>{let p=_n(f)?f.status:void 0;if(typeof p!="string")throw zi(r,"one of its statuses has no string status");return p})}}var SE=class{constructor(t,n,r){this.org=t,this.instanceUrl=n,this.service=r,this.swaggers=new Map}async listConnections(){let t=this.requireService(),n=await this.resolveEnvironment(t),r=[],i=new Set,o=`${n.origin}/providers/Microsoft.PowerApps/connections?api-version=${Yk}&$filter=${Zk(n.id)}`,a=await this.send(t,o,!0),s=1,u=0;for(;;){let l=`Page ${s} of the connections`,c=a.body,d=c?.value;if(!Array.isArray(d))throw zi(l,`its value is ${Ws(d)}, not an array`);for(let p of d){let m=BZ(p,u,n.id);u+=1,m&&r.push(m)}let f=c?.nextLink;if(f==null)return r;if(typeof f!="string"||f.length===0)throw zi(l,`its nextLink is ${f===""?"an empty string":Ws(f)}, not a non-empty string`);if(i.has(f))throw new gr.InvalidArgumentError(`listConnections: aborting pagination \u2014 the server returned a repeated nextLink ('${ra(f)}'), which would loop indefinitely.`);i.add(f),this.assertSameOrigin(f,n.parsed),a=await this.send(t,f,!0),s+=1}}async listConnectorOperations(t){let n=this.requireService(),r=t$(t);return(0,Cg.projectConnectorOperations)(await this.swagger(n,r))}async getConnectorOperationSchema(t,n){let r=this.requireService(),i=t$(t);if(typeof n!="string"||n==="")throw new gr.InvalidArgumentError("operationId must be a non-empty string.");return(0,Cg.projectConnectorOperationSchema)(await this.swagger(r,i),n)}requireService(){if(!this.service)throw new gr.SdkError(np.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 n=this.verifyEnvironment(t);this.environment=n,n.catch(()=>{this.environment===n&&(this.environment=void 0)})}return this.environment}async verifyEnvironment(t){let n=this.candidateBapOrigin(),r=await this.readEnvironmentId(),i=`${n}/providers/Microsoft.BusinessAppPlatform/environments/${encodeURIComponent(r)}?api-version=${PZ}`,o=(await this.send(t,i,!1)).body,a=_n(o)?o.properties:void 0,s=_n(o)?o.name:void 0;if(typeof s!="string"||s.toLowerCase()!==r.toLowerCase())throw Ag(`BAP's environment row is not the one named '${ra(r,80)}' (its name)`);let u=_n(a)&&_n(a.linkedEnvironmentMetadata)?a.linkedEnvironmentMetadata.instanceUrl:void 0,l=typeof u=="string"?tp(u):void 0,c=tp(this.instanceUrl);if(!l||!c||!Xk(l,c))throw Ag("BAP's row is not linked to this org (its linkedEnvironmentMetadata.instanceUrl is another origin)");let d=_n(a)?a.runtimeEndpoints:void 0,f=_n(d)?d["microsoft.PowerApps"]:void 0,p=typeof f=="string"?tp(f):void 0;if(!p||p.protocol!=="https:"||!UZ(p.host.toLowerCase()))throw Ag("BAP's Power Apps runtime endpoint is not an https host of api.powerapps.com (runtimeEndpoints['microsoft.PowerApps'])");return{id:r,origin:p.origin.toLowerCase(),parsed:p}}candidateBapOrigin(){let t=tp(this.instanceUrl),n=t?t.host.toLowerCase():"",r=$Z.exec(n);if(r&&r[1]!=="9")return RZ;if(LZ.test(n))return kZ;throw new gr.SdkError(np.CONNECTIVITY_CLOUD_UNSUPPORTED_CODE,`The org's host is not one of the clouds this reads in (${t?`'${ra(t.host,80)}'`:`'${ra(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,DZ.ensureSuccess)(await this.org.get(Qk),this.org.apiUrl(Qk)).body,n=_n(t)?t.Detail:void 0,r=_n(n)?n.EnvironmentId:void 0;if(typeof r!="string"||r==="")throw Ag("the org answered no environment id (RetrieveCurrentOrganization, Detail.EnvironmentId)");return r}swagger(t,n){let r=n.toLowerCase(),i=this.swaggers.get(r);if(!i){let o=this.readSwagger(t,n);i=o,this.swaggers.set(r,o),o.catch(()=>{this.swaggers.get(r)===o&&this.swaggers.delete(r)})}return i}async readSwagger(t,n){let r=await this.resolveEnvironment(t),i=encodeURIComponent(n),o=`${r.origin}${Ha}${i}?api-version=${Yk}&$filter=${Zk(r.id)}`,a=(await this.send(t,o,!0)).body,s=_n(a)?a.properties:void 0,u=_n(s)?s.swagger:void 0;if(!_n(u))throw zi(`The connector '${ra(n,80)}'`,`its properties.swagger is ${Ws(u)}, not an object`);return(0,Cg.validateConnectorSwagger)(u),u}assertSameOrigin(t,n){let r=tp(t);if(!r)throw new gr.InvalidArgumentError(`Refusing to follow a malformed absolute URL: '${ra(t)}'`);if(!Xk(r,n))throw new gr.InvalidArgumentError(`Refusing to follow a cross-origin link ('${ra(r.origin,120)}' is not the environment's Power Apps endpoint '${n.origin}'); server-driven pagination must stay on that origin.`)}async send(t,n,r){let i;try{i=await t.get(n)}catch(o){throw o instanceof gr.ConnectionError&&typeof o.statusCode=="number"&&o.statusCode>0?this.mapNon2xx(n,o.statusCode,void 0,r,o):o instanceof gr.SdkError?o:new gr.ConnectionError(n,0,o instanceof Error?o.message:String(o),o)}if(!i||typeof i.status!="number")throw new gr.ConnectionError(n,0,"the transport returned no HTTP response");if(i.status>=200&&i.status<300)return i;throw this.mapNon2xx(n,i.status,i.body,r)}mapNon2xx(t,n,r,i,o){let a=o??new gr.ConnectionError(t,n,e$(r),r);return i&&n===410&&qZ(r)===FZ?(0,gr.attachCause)(new gr.SdkError(np.CONNECTIVITY_ROUTE_DECOMMISSIONED_CODE,`The Power Apps API this reads through is decommissioned for this environment: ${e$(r)} 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):n===401||n===403?(0,np.connectivityUnauthorized)(n,r,a):a}};ui.ConnectivityApi=SE});var OE=C(Pt=>{"use strict";Object.defineProperty(Pt,"__esModule",{value:!0});Pt.projectConnectorTableSchema=Pt.projectConnectorTables=Pt.tableSchemaSuffix=Pt.tablesSuffix=Pt.encodeTable=Pt.encodeDataset=Pt.checkTabularConnection=Pt.runtimeAuthority=Pt.tabularRevision=Pt.checkTableSchemaArguments=Pt.checkListTablesArguments=void 0;var el=Y(),z=Zu(),VZ=/^[A-Za-z0-9_.-]{1,128}$/,tl=/^\.{1,2}$/,GZ="shared_sharepointonline",jZ=/^[0-9]{1,9}$/,WZ=/^[A-Za-z0-9._~-]+$/,zZ=/^\/apim\/([A-Za-z0-9._-]+)\/?$/,HZ=/^\/connectors\/runtime\/invoke\/scalegroups\/([A-Za-z0-9._-]+)\/(scaleunits|shards)\/([A-Za-z0-9._-]+)\/apis\/([A-Za-z0-9._-]+)\/connections\/?$/,KZ=/^[A-Za-z0-9._~!'()*-]$/,JZ=/^[0-9A-Fa-f]{2}$/;function Ka(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function ip(e){return typeof e=="string"?`'${(0,z.bounded)(e,80)}'`:(0,z.kindOf)(e)}function NE(e,t){return new el.SdkError(z.CONNECTOR_NOT_TABULAR_CODE,`The connector '${(0,z.bounded)(e,80)}' has no tables: ${t}.`)}function Sg(e,t){return new el.SdkError(z.CONNECTOR_RUNTIME_UNSUPPORTED_CODE,`The connector '${(0,z.bounded)(e,80)}' runs where this SDK does not send a token: ${t}. Nothing was sent to it.`)}function YZ(e){if(typeof e=="string"&&VZ.test(e)&&!tl.test(e))return e;throw new el.InvalidArgumentError(`connectionId must be a connection's name (letters, digits, '_', '.', '-'; at most 128; not '.' or '..'); got ${ip(e)}.`)}function QZ(e){if(e!=null){if(typeof e=="string"&&e!==""&&e.split(",").find(n=>n===""||tl.test(n))===void 0)return e;throw new el.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 ${ip(e)}.`)}}function XZ(e){if(typeof e=="string"&&e!==""&&!tl.test(e))return e;throw new el.InvalidArgumentError(`table must be a non-empty string other than '.' and '..'; got ${ip(e)}.`)}function i$(e,t,n){return{short:(0,z.connectorShortName)(e),connectionId:YZ(t),dataset:QZ(n)}}Pt.checkListTablesArguments=i$;function ZZ(e,t,n,r){return{...i$(e,t,n),table:XZ(r)}}Pt.checkTableSchemaArguments=ZZ;function eee(e,t){let n=`The connector '${(0,z.bounded)(t,80)}'`,r=e.properties;if(!(0,z.isObject)(r))throw(0,z.unreadable)(n,`its properties are ${(0,z.kindOf)(r)}, not an object`);if(!Ka(r,"interfaces"))throw NE(t,"it declares no interfaces");let i=r.interfaces;if(!(0,z.isObject)(i))throw(0,z.unreadable)(n,`its properties.interfaces are ${(0,z.kindOf)(i)}, not an object`);if(!Ka(i,"CDPTabular1"))throw NE(t,"it declares no CDPTabular1 interface");let o=i.CDPTabular1;if(!(0,z.isObject)(o))throw(0,z.unreadable)(n,`its CDPTabular1 interface is ${(0,z.kindOf)(o)}, not an object`);let a=o.revisions;if(!(0,z.isObject)(a))throw(0,z.unreadable)(n,`its CDPTabular1 revisions are ${(0,z.kindOf)(a)}, not an object`);let s,u=new Map;for(let l of Object.keys(a)){let c=a[l],d=`its CDPTabular1 revision '${(0,z.bounded)(l,40)}'`;if(!(0,z.isObject)(c)||typeof c.status!="string")throw(0,z.unreadable)(n,`${d} is not an object with a string status`);if(c.status!=="Production")continue;if(!jZ.test(l))throw(0,z.unreadable)(n,`${d} is a Production revision whose key is not a decimal integer of 1\u20139 digits`);let f=tee(c.baseUrl);if(f===void 0)throw(0,z.unreadable)(n,`${d} has a baseUrl that is not '/' or '/'-separated [A-Za-z0-9._~-] segments`);let p=Number(l),m=u.get(p);if(m!==void 0)throw(0,z.unreadable)(n,`its Production revisions '${m}' and '${(0,z.bounded)(l,40)}' have the same number`);u.set(p,l),(!s||p>s.revisionNumber)&&(s={revisionNumber:p,revision:f})}if(!s)throw NE(t,"its CDPTabular1 interface has no Production revision");return s.revision}Pt.tabularRevision=eee;function tee(e){if(typeof e!="string")return;let t=e.replace(/^\/+/,"").replace(/\/+$/,"");return t===""?"":t.split("/").every(i=>WZ.test(i)&&!tl.test(i))?t:void 0}function nee(e,t,n){let r=(0,z.isObject)(e.properties)?e.properties:void 0,i=r?r.primaryRuntimeUrl:void 0;if(typeof i!="string")throw Sg(n,`its primaryRuntimeUrl is ${(0,z.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,z.parseUrl)(i);if(!s||s.protocol!=="https:"||s.origin.toLowerCase()!==a)throw Sg(n,`its runtime ('${(0,z.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 u=i.slice(0,a.length).toLowerCase()===a?i.slice(a.length):void 0;if(o){let c=u===void 0?null:zZ.exec(u);if(!c||tl.test(c[1]))throw Sg(n,`its runtime ('${(0,z.bounded)(i,120)}') is not <host>/apim/<connector>`);return{transport:"invoke",origin:a,path:`/apim/${c[1]}`}}let l=u===void 0?null:HZ.exec(u);if(!l||[l[1],l[3],l[4]].some(c=>tl.test(c)))throw Sg(n,`its runtime ('${(0,z.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/${l[1]}/${l[2]}/${l[3]}/apis/${l[4]}/connections`}}Pt.runtimeAuthority=nee;function ree(e,t,n,r){let i=`The connection '${(0,z.bounded)(t,128)}'`;if(!(0,z.isObject)(e))throw(0,z.unreadable)(i,`it is ${(0,z.kindOf)(e)}, not an object`);if(e.name!==t)throw(0,z.unreadable)(i,`its name is ${ip(e.name)}, not the requested connection`);let o=e.properties;if(!(0,z.isObject)(o))throw(0,z.unreadable)(i,`its properties are ${(0,z.kindOf)(o)}, not an object`);let a=o.apiId;if(typeof a!="string"||a.toLowerCase()!==`${z.CONNECTOR_PREFIX}${n}`.toLowerCase())throw(0,z.unreadable)(i,`its apiId is ${ip(a)}, not the connector '${(0,z.bounded)(n,80)}'`);let s=o.environment,u=(0,z.isObject)(s)?s.name:void 0;if(typeof u!="string"||u.toLowerCase()!==r.toLowerCase())throw(0,z.unreadable)(i,"it is not a connection of this environment (properties.environment.name)");return t}Pt.checkTabularConnection=ree;function r$(e){return encodeURIComponent(e).replace(/[!'()*]/g,t=>`%${t.charCodeAt(0).toString(16).toUpperCase()}`)}function iee(e){if(e==="")return!1;for(let t=0;t<e.length;t+=1)if(e[t]==="%"){if(!JZ.test(e.slice(t+1,t+3)))return!1;t+=2}else if(!KZ.test(e[t]))return!1;return!0}function o$(e,t){let n,r,i;try{n=r$(e),r=r$(n),i=decodeURIComponent(r)}catch{throw new el.InvalidArgumentError(`${t} is not well-formed Unicode (it has a lone surrogate), so it cannot be sent.`)}if(!iee(r)||tl.test(r)||i!==n)throw new el.InvalidArgumentError(`${t} cannot be sent as one path segment.`);return r}function TE(e){return e.split(",").map((t,n)=>o$(t,`dataset part ${n}`)).join(",")}Pt.encodeDataset=TE;function a$(e){return o$(e,"table")}Pt.encodeTable=a$;function oee(e,t){if(t===void 0)return"/tables";let n=e.toLowerCase()===GZ?"allTables":"tables";return`/datasets/${TE(t)}/${n}`}Pt.tablesSuffix=oee;function aee(e,t){return`/$metadata.json${e===void 0?"":`/datasets/${TE(e)}`}/tables/${a$(t)}`}Pt.tableSchemaSuffix=aee;function Ic(e,t){let n=t.toLowerCase();for(let r of Object.keys(e))if(r.toLowerCase()===n)return{found:!0,value:e[r]};return{found:!1}}function see(e){let t="The table list",n;if(Array.isArray(e))n=e;else if((0,z.isObject)(e)){for(let o of["nextLink","@odata.nextLink"])if(Ic(e,o).found)throw(0,z.unreadable)(t,`it carries a ${o} \u2014 a paged answer is refused, never read as a partial list`);let r=Ic(e,"value"),i=r.found?r:Ic(e,"tables");if(!i.found)throw(0,z.unreadable)(t,"it is an object with neither a value nor a tables member");if(!Array.isArray(i.value))throw(0,z.unreadable)(t,`its ${r.found?"value":"tables"} is ${(0,z.kindOf)(i.value)}, not an array`);n=i.value}else throw(0,z.unreadable)(t,`it is ${(0,z.kindOf)(e)}, not an array or an object`);return{tables:n.map((r,i)=>uee(r,i))}}Pt.projectConnectorTables=see;function uee(e,t){let n=`Table row ${t}`;if(!(0,z.isObject)(e))throw(0,z.unreadable)(n,`it is ${(0,z.kindOf)(e)}, not an object`);let r=Ic(e,"name");if(!r.found||typeof r.value!="string"||r.value==="")throw(0,z.unreadable)(n,"it has no non-empty string name");let i=Ic(e,"displayName");if(i.found&&typeof i.value!="string")throw(0,z.unreadable)(n,`its displayName is ${(0,z.kindOf)(i.value)}, not a string`);let o=Ic(e,"id");if(o.found&&(typeof o.value!="string"||o.value===""))throw(0,z.unreadable)(n,`its id is ${o.value===""?"an empty string":(0,z.kindOf)(o.value)}, not a non-empty string`);return{name:r.value,displayName:i.found?i.value:null,id:o.found?o.value:r.value}}function _E(e,t,n){if(!Ka(e,t))return;let r=e[t];if(!(0,z.isObject)(r))throw(0,z.unreadable)("The table schema",`its ${n} is ${(0,z.kindOf)(r)}, not an object`);return r}function IE(e,t,n){if(!Ka(e,t))return;let r=e[t];if(typeof r!="string")throw(0,z.unreadable)(n,`its ${t} is ${(0,z.kindOf)(r)}, not a string`);return r}function lee(e,t){var n,r;if(Ka(e,"$ref"))throw(0,z.unreadable)(t,"it is a $ref, whose type is not guessed");let i=IE(e,"type",t),o=IE(e,"format",t),a=(n=i??o)!==null&&n!==void 0?n:"object";if(!Ka(e,"items"))return a;let s=e.items;if(!(0,z.isObject)(s))throw(0,z.unreadable)(t,`its items are ${(0,z.kindOf)(s)}, not an object`);if(Ka(s,"$ref"))throw(0,z.unreadable)(t,"its items are a $ref, whose type is not guessed");return`${a}<${(r=IE(s,"type",`${t} items`))!==null&&r!==void 0?r:"object"}>`}function cee(e,t){let n="The table schema";if(!(0,z.isObject)(e))throw(0,z.unreadable)(n,`it is ${(0,z.kindOf)(e)}, not an object`);let r=_E(e,"items","items"),i=_E(e,"schema","schema"),o=i?_E(i,"items","schema.items"):void 0,a=[[e,"the answer"],[r,"items"],[i,"schema"],[o,"schema.items"]],s=new Set;for(let[c,d]of a)if(c&&Ka(c,"required")){let f=c.required;if(!Array.isArray(f))throw(0,z.unreadable)(n,`the required of ${d} is ${(0,z.kindOf)(f)}, not an array`);f.forEach(p=>{if(typeof p!="string")throw(0,z.unreadable)(n,`the required of ${d} has an entry that is ${(0,z.kindOf)(p)}, not a string`);s.add(p.toLowerCase())})}let u;for(let[c,d]of a)if(c&&Ka(c,"properties")){if(!(0,z.isObject)(c.properties))throw(0,z.unreadable)(n,`the properties of ${d} are ${(0,z.kindOf)(c.properties)}, not an object`);u=c.properties;break}if(!u)throw(0,z.unreadable)(n,"it has no properties, items.properties, schema.properties or schema.items.properties");let l=Object.keys(u).map(c=>{let d=`Column '${(0,z.bounded)(c,80)}'`,f=u[c];if(!(0,z.isObject)(f))throw(0,z.unreadable)(d,`it is ${(0,z.kindOf)(f)}, not an object`);return{name:c,type:lee(f,d),required:s.has(c.toLowerCase())}});return{table:t,columns:l}}Pt.projectConnectorTableSchema=cee});var s$=C(Ng=>{"use strict";Object.defineProperty(Ng,"__esModule",{value:!0});Ng.PowerPlatformApiDiscovery=void 0;var DE=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,n,r=""){if(!/^[a-zA-Z0-9\-]+$/g.test(t))throw new Error(`Cannot generate Power Platform API endpoint because the ${n} 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 ${n} 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),u=this._getEnvironmentApiHostNameSuffix();return`${r}${s}.${a}.${n}.${u}`}_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}`)}}};Ng.PowerPlatformApiDiscovery=DE});var u$=C(_g=>{"use strict";Object.defineProperty(_g,"__esModule",{value:!0});_g.PowerPlatformApiDiscovery=void 0;var dee=s$();Object.defineProperty(_g,"PowerPlatformApiDiscovery",{enumerable:!0,get:function(){return dee.PowerPlatformApiDiscovery}})});var f$=C(zs=>{"use strict";Object.defineProperty(zs,"__esModule",{value:!0});zs.platformTokenAudience=zs.platformEnvironment=zs.platformClusterOf=void 0;var l$=u$(),c$=Y(),d$=Zu(),fee=/^[a-z0-9-]+\.crm(\d*)\.dynamics\.com$/,pee=/^[a-z0-9-]+\.crmtest\.dynamics\.com$/,mee=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,hee=/^default-/i;function PE(e,t=80){return e.length>t?`${e.slice(0,t)}\u2026`:e}function gee(e){try{return new URL(e).host.toLowerCase()}catch{return}}function yee(e){let t=gee(e);if(t){if(pee.test(t))return{cloud:"Test",category:"test"};let n=fee.exec(t);if(n&&n[1]!=="9")return{cloud:"Public",category:"prod"}}throw new c$.SdkError(d$.CONNECTIVITY_CLOUD_UNSUPPORTED_CODE,`The Power Platform API route is built for the Test and Public clouds; this org (${t?`'${PE(t)}'`:`'${PE(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.`)}zs.platformClusterOf=yee;function bee(e,t){let n=hee.test(e)?e.slice(8):e;if(!mee.test(n))throw new c$.SdkError(d$.CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE,`The environment of this org could not be verified: its name ('${PE(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 l$.PowerPlatformApiDiscovery(t).getEnvironmentEndpoint(e)}`,guid:n.toLowerCase()}}zs.platformEnvironment=bee;function vee(e){return new l$.PowerPlatformApiDiscovery(e).getTokenAudience()}zs.platformTokenAudience=vee});var m$=C(Tc=>{"use strict";Object.defineProperty(Tc,"__esModule",{value:!0});Tc.PlatformConnectivityApi=Tc.assertTabularCloud=void 0;var bo=Y(),RE=Zf(),je=Zu(),p$=f$(),Ja=OE(),kE="1";function $E(e){let t=(0,je.connectivityCloudOf)(e);if(t!=="Test"&&t!=="Public")throw new bo.SdkError(je.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.")}Tc.assertTabularCloud=$E;var LE=class{constructor(t,n,r,i){this.org=t,this.instanceUrl=n,this.client=r,this.runtime=i,this.records=new Map,this.swaggers=new Map}async listConnections(){let t=await this.resolveEnvironment(),n=[],r=new Set,i=await this.send(this.client,"GET",`${t.origin}/connectivity/connections?api-version=${kE}`,[401,403]),o=1,a=0;for(;;){let s=`Page ${o} of the connections`,u=i.body,l=u?.value;if(!Array.isArray(l))throw(0,je.unreadable)(s,`its value is ${(0,je.kindOf)(l)}, not an array`);for(let d of l){let f=(0,je.readConnection)(d,a,t.name);a+=1,f&&n.push(f)}let c=u?.nextLink;if(c==null)return n;if(typeof c!="string"||c.length===0)throw(0,je.unreadable)(s,`its nextLink is ${c===""?"an empty string":(0,je.kindOf)(c)}, not a non-empty string`);if(r.has(c))throw new bo.InvalidArgumentError(`listConnections: aborting pagination \u2014 the server returned a repeated nextLink ('${(0,je.bounded)(c)}'), which would loop indefinitely.`);r.add(c),this.assertSameOrigin(c,t.parsed),i=await this.send(this.client,"GET",c,[401,403]),o+=1}}async listConnectorOperations(t){let n=(0,je.connectorShortName)(t);return(0,RE.projectConnectorOperations)(await this.swagger(n))}async getConnectorOperationSchema(t,n){let r=(0,je.connectorShortName)(t);if(typeof n!="string"||n==="")throw new bo.InvalidArgumentError("operationId must be a non-empty string.");return(0,RE.projectConnectorOperationSchema)(await this.swagger(r),n)}async listConnectorTables(t,n,r){$E(this.instanceUrl);let i=(0,Ja.checkListTablesArguments)(t,n,r),o=(0,Ja.tablesSuffix)(i.short,i.dataset);return(0,Ja.projectConnectorTables)(await this.invokeTabular(i,o))}async getConnectorTableSchema(t,n,r,i){$E(this.instanceUrl);let o=(0,Ja.checkTableSchemaArguments)(t,n,r,i),a=(0,Ja.tableSchemaSuffix)(o.dataset,o.table);return(0,Ja.projectConnectorTableSchema)(await this.invokeTabular(o,a),o.table)}async invokeTabular(t,n){let r=this.requireRuntime(),i=await this.resolveEnvironment(),o=await this.record(t.short),a=(0,Ja.tabularRevision)(o,t.short),s=(0,Ja.runtimeAuthority)(o,{cloud:i.cloud,name:i.name,origin:i.origin},t.short),u=`${i.origin}/connectivity/connectors/${encodeURIComponent(t.short)}/connections/${encodeURIComponent(t.connectionId)}?$filter=${(0,je.environmentFilter)(i.name)}&api-version=${kE}`,l=(await this.send(this.client,"GET",u,[401,403])).body,c=(0,Ja.checkTabularConnection)(l,t.connectionId,t.short,i.name),d=`${s.path}/${c}${a===""?"":`/${a}`}${n}`;return(s.transport==="invoke"?await this.send(r,"POST",`${s.origin}/invoke`,[401],{"X-Ms-Request-Url":d,"X-Ms-Request-Method":"GET"}):await this.send(r,"GET",`${s.origin}${d}`,[401])).body}requireRuntime(){if(!this.runtime)throw new bo.SdkError(je.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:n}=(0,p$.platformClusterOf)(this.instanceUrl),r=await(0,je.readEnvironmentName)(this.org),{origin:i,guid:o}=(0,p$.platformEnvironment)(r,n),a=(0,je.parseUrl)(i);if(!a)throw(0,je.unreadable)("The Power Platform API origin",`'${(0,je.bounded)(i)}' is not a URL`);return{cloud:t,origin:i,parsed:a,name:r,guid:o}}cached(t,n,r){let i=t.get(n);if(!i){let o=r();i=o,t.set(n,o),o.catch(()=>{t.get(n)===o&&t.delete(n)})}return i}record(t){return this.cached(this.records,t.toLowerCase(),()=>this.readRecord(t))}async readRecord(t){let n=await this.resolveEnvironment(),r=`${n.origin}/connectivity/connectors/${encodeURIComponent(t)}?$filter=${(0,je.environmentFilter)(n.name)}&api-version=${kE}`,i=(await this.send(this.client,"GET",r,[401,403])).body,o=(0,je.isObject)(i)?i.name:void 0;if(!(0,je.isObject)(i)||typeof o!="string"||o.toLowerCase()!==t.toLowerCase())throw(0,je.unreadable)(`The connector '${(0,je.bounded)(t,80)}'`,`the record's name is ${typeof o=="string"?`'${(0,je.bounded)(o,80)}'`:(0,je.kindOf)(o)}, not the requested connector`);return i}swagger(t){return this.cached(this.swaggers,t.toLowerCase(),async()=>{let r=(await this.record(t)).properties,i=(0,je.isObject)(r)?r.swagger:void 0;if(!(0,je.isObject)(i))throw(0,je.unreadable)(`The connector '${(0,je.bounded)(t,80)}'`,`its properties.swagger is ${(0,je.kindOf)(i)}, not an object`);return(0,RE.validateConnectorSwagger)(i),i})}assertSameOrigin(t,n){let r=(0,je.parseUrl)(t);if(!r)throw new bo.InvalidArgumentError(`Refusing to follow a malformed absolute URL: '${(0,je.bounded)(t)}'`);if(!(0,je.sameOrigin)(r,n))throw new bo.InvalidArgumentError(`Refusing to follow a cross-origin link ('${(0,je.bounded)(r.origin,120)}' is not the environment's Power Platform API origin '${n.origin}'); server-driven pagination must stay on that origin.`)}async send(t,n,r,i,o){let a;try{a=n==="GET"?await t.get(r):await t.post(r,void 0,{headers:o})}catch(s){throw s instanceof bo.ConnectionError&&typeof s.statusCode=="number"&&s.statusCode>0?this.non2xx(r,s.statusCode,void 0,i,s):s instanceof bo.SdkError?s:new bo.ConnectionError(r,0,s instanceof Error?s.message:String(s),s)}if(!a||typeof a.status!="number")throw new bo.ConnectionError(r,0,"the transport returned no HTTP response");if(a.status>=200&&a.status<300)return a;throw this.non2xx(r,a.status,a.body,i)}non2xx(t,n,r,i,o){let a=o??new bo.ConnectionError(t,n,(0,je.messageOf)(r),r);return i.includes(n)?(0,je.connectivityUnauthorized)(n,r,a):a}};Tc.PlatformConnectivityApi=LE});var g$=C(Tg=>{"use strict";Object.defineProperty(Tg,"__esModule",{value:!0});Tg.ConnectivityRouter=void 0;var ME=Y(),wee=n$(),Ig=Zu(),h$=OE(),xE=m$(),FE=class{constructor(t,n,r){this.org=t,this.instanceUrl=n,this.clients=r}async listConnections(){return this.route().listConnections()}async listConnectorOperations(t){return this.route().listConnectorOperations(t)}async getConnectorOperationSchema(t,n){return this.route().getConnectorOperationSchema(t,n)}async listConnectorTables(t,n,r){return(0,xE.assertTabularCloud)(this.instanceUrl),(0,h$.checkListTablesArguments)(t,n,r),this.tabularRoute().listConnectorTables(t,n,r)}async getConnectorTableSchema(t,n,r,i){return(0,xE.assertTabularCloud)(this.instanceUrl),(0,h$.checkTableSchemaArguments)(t,n,r,i),this.tabularRoute().getConnectorTableSchema(t,n,r,i)}route(){return this.delegate||(this.delegate=this.select()),this.delegate}platformRoute(t){return this.platform||(this.platform=new xE.PlatformConnectivityApi(this.org,this.instanceUrl,t,this.clients.connectorRuntimeClient)),this.platform}tabularRoute(){let{powerPlatformApiClient:t,connectorRuntimeClient:n}=this.clients,r=[t?void 0:"powerPlatformApiClient (the Power Platform API)",n?void 0:"connectorRuntimeClient (API Hub, https://apihub.azure.com)"].filter(i=>i!==void 0);if(r.length>0||!t)throw new ME.SdkError(Ig.CONNECTIVITY_NOT_CONFIGURED_CODE,`Connector tables are read through the Power Platform API and the connector runtime: this SDK was created without MakerSdkOptions.${r.join(" or MakerSdkOptions.")}, an HttpClient that does not follow redirects. Nothing was requested.`);return this.platformRoute(t)}select(){let t=(0,Ig.connectivityCloudOf)(this.instanceUrl),{powerAppsServiceClient:n,powerPlatformApiClient:r}=this.clients;if(t==="Unsupported")throw new ME.SdkError(Ig.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(r)return this.platformRoute(r);if(t==="Public"&&n)return new wee.ConnectivityApi(this.org,this.instanceUrl,n);throw new ME.SdkError(Ig.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.")}};Tg.ConnectivityRouter=FE});var ia=C(ci=>{"use strict";Object.defineProperty(ci,"__esModule",{value:!0});ci.bytesToUtf8=ci.base64ToUtf8=ci.base64ToBytes=ci.bytesToBase64=ci.utf8ToBase64=ci.utf8ToBytes=void 0;var UE=32768,li="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";function Oc(){return globalThis}function y$(e){let t=[];for(let n=0;n<e.length;n+=1){let r=e.charCodeAt(n);if(r>=55296&&r<=56319){let i=n+1<e.length?e.charCodeAt(n+1):0;i>=56320&&i<=57343?(r=(r-55296<<10)+(i-56320)+65536,n+=1):r=65533}else r>=56320&&r<=57343&&(r=65533);r<128?t.push(r):r<2048?t.push(192|r>>6,128|r&63):r<65536?t.push(224|r>>12,128|r>>6&63,128|r&63):t.push(240|r>>18,128|r>>12&63,128|r>>6&63,128|r&63)}return Uint8Array.from(t)}function Eee(e){let t="";for(let n=0;n<e.length;n+=UE)t+=String.fromCharCode(...e.subarray(n,n+UE));return t}function Aee(e){let t="";for(let n=0;n<e.length;n+=1){let r=String.fromCharCode(e.charCodeAt(n)&255);if(r==="=")break;r==="-"?t+="+":r==="_"?t+="/":li.indexOf(r)>=0&&(t+=r)}for(t.length%4===1&&(t=t.slice(0,-1));t.length%4!==0;)t+="=";return t}function Cee(e){let t="",n=0;for(;n+2<e.length;n+=3){let i=e[n]<<16|e[n+1]<<8|e[n+2];t+=li[i>>18&63]+li[i>>12&63]+li[i>>6&63]+li[i&63]}let r=e.length-n;if(r===1){let i=e[n]<<16;t+=`${li[i>>18&63]}${li[i>>12&63]}==`}else if(r===2){let i=e[n]<<16|e[n+1]<<8,o=li[i>>18&63],a=li[i>>12&63],s=li[i>>6&63];t+=`${o}${a}${s}=`}return t}function See(e){let t=e.endsWith("==")?2:e.endsWith("=")?1:0,n=e.length/4*3-t,r=new Uint8Array(n>0?n:0),i=0;for(let o=0;o<e.length;o+=4){let a=li.indexOf(e[o])<<18|li.indexOf(e[o+1])<<12|(e[o+2]==="="?0:li.indexOf(e[o+2]))<<6|(e[o+3]==="="?0:li.indexOf(e[o+3]));i<n&&(r[i++]=a>>16&255),i<n&&(r[i++]=a>>8&255),i<n&&(r[i++]=a&255)}return r}function Nee(e){let t=Oc();if(t.Buffer)return new Uint8Array(t.Buffer.from(e,"utf8"));let n=t.TextEncoder;return n?new n().encode(e):y$(e)}ci.utf8ToBytes=Nee;function _ee(e){let t=Oc();if(t.Buffer)return t.Buffer.from(e,"utf8").toString("base64");let n=t.TextEncoder;return b$(n?new n().encode(e):y$(e))}ci.utf8ToBase64=_ee;function b$(e){let t=Oc();return t.Buffer?t.Buffer.from(e).toString("base64"):t.btoa?t.btoa(Eee(e)):Cee(e)}ci.bytesToBase64=b$;function v$(e){let t=Oc();if(t.Buffer)return new Uint8Array(t.Buffer.from(e,"base64"));let n=Aee(e);if(t.atob){let r=t.atob(n);return Uint8Array.from(r,i=>i.charCodeAt(0))}return See(n)}ci.base64ToBytes=v$;function w$(e){let t=[],n="",r=()=>{n+=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>=UE&&r()},o=0;for(;o<e.length;){let a=e[o],s=0,u=0,l=128,c=191;if(a<128){i(a),o+=1;continue}else if(a>=194&&a<=223)s=1,u=a&31;else if(a>=224&&a<=239)s=2,u=a&15,l=a===224?160:128,c=a===237?159:191;else if(a>=240&&a<=244)s=3,u=a&7,l=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<l||m>c){f=!1;break}l=128,c=191,u=u<<6|m&63}f?(i(u),o=d):(i(65533),o=d)}return r(),n}function Iee(e){let t=Oc();return t.Buffer?t.Buffer.from(e,"base64").toString("utf8"):w$(v$(e))}ci.base64ToUtf8=Iee;function Tee(e){let t=Oc();return t.Buffer?t.Buffer.from(e).toString("utf8"):w$(e)}ci.bytesToUtf8=Tee});var Ya=C(Le=>{"use strict";Object.defineProperty(Le,"__esModule",{value:!0});Le.originOf=Le.readEnvironment=Le.ReadBudget=Le.DEFAULT_LIMITS=Le.compareVersions=Le.parseVersion=Le.canonicalGuid=Le.ZERO_GUID=Le.byCodeUnit=Le.identityKey=Le.digestOf=Le.sha256Of=Le.canonicalJson=Le.safeDiagnostics=Le.promotionError=Le.promotionProblem=Le.PROMOTION_ERROR_CODES=void 0;var E$=Y(),Oee=ia(),qE={INVALID_ARGUMENT:"The promotion input is invalid",PROMOTION_CODEC_REQUIRED:"A host codec with callable inflateRaw and sha256 is required",PROMOTION_JOURNAL_REQUIRED:"A trusted atomic journal (begin, read, replace, release) is required to apply a plan",PROMOTION_JOURNAL_FAILED:"The attempt journal could not record this step; no further application write was sent and the reservation is kept",PROMOTION_PACKAGE_UNREADABLE:"The package is not a solution package this SDK reads safely",PROMOTION_PACKAGE_MODE_MISMATCH:"The selected import mode differs from the package's managed bit",PROMOTION_TARGET_MODE_MISMATCH:"The target's solution has the other managed bit; conversion is not an update",PROMOTION_ENVIRONMENT_MISMATCH:"The receiving environment is not the one the plan or receipt is bound to",PROMOTION_TENANT_MISMATCH:"The source and target environments are in different tenants",PROMOTION_SAME_ENVIRONMENT:"The source and target are the same organization",PROMOTION_SOURCE_PACKAGE_MISMATCH:"The package does not correspond to the named source solution as it is now",PROMOTION_APP_NOT_IN_PACKAGE:"The named app is not in the package",PROMOTION_COVERAGE_GAP:"A required component, file or field cannot be carried, matched or completely interpreted",PROMOTION_DEPENDENCY_MISSING:"A required component is neither in the package nor in the target",PROMOTION_DEPENDENCY_IDENTITY_UNRESOLVED:"A required component has no unambiguous supported identity",PROMOTION_COMPONENT_COLLISION:"An existing target component belongs to another owner, layer or identity",PROMOTION_DESTRUCTIVE_SCHEMA_CHANGE:"The import would change existing schema destructively",PROMOTION_VALUE_REQUIRED:"A required variable, or one with a packaged current value, needs a non-empty target value",PROMOTION_SECRET_VALUE:"Secret content would be uploaded, or a Secret input is not a reference",PROMOTION_CONNECTION_UNMAPPED:"A packaged connection reference has no target connection",PROMOTION_CONNECTION_NOT_IN_TARGET:"The mapped connection does not exist in the target",PROMOTION_CONNECTION_CONNECTOR_MISMATCH:"The mapped connection's connector differs from the reference's",PROMOTION_SETTING_UNAVAILABLE:"A required setting definition is neither incoming nor available in the target",PROMOTION_PUBLISH_REQUIRED:"A necessary additional app publication has not been authorized",PROMOTION_PUBLICATION_SCOPE_UNKNOWN:"The complete approved publication footprint cannot be established",PROMOTION_NON_ATOMIC_IMPORT_NOT_ACKNOWLEDGED:"acknowledgeNonAtomicImport must be exactly true",PROMOTION_READ_BUDGET_EXCEEDED:"A configured read budget was exhausted; the plan is incomplete",PROMOTION_VERIFICATION_UNAVAILABLE:"A required reader, condition or certified protocol is unavailable",PROMOTION_VERSION_REFUSED:"A fresh import of the same or an older version, or an unsupported version, is refused",PROMOTION_PUBLISHER_MISMATCH:"The target solution's publisher differs from the package's",PROMOTION_HOLDING_PRESENT:"A holding solution or patch on the target requires external reconciliation",PROMOTION_UPGRADE_NOT_SUPPORTED:"Upgrade, holding import and solution deletion are not supported",PROMOTION_PLAN_INVALID:"The plan is not a valid, unaltered plan for these package bytes",PROMOTION_PLAN_STALE:"A planned precondition changed on the target",PROMOTION_ATTEMPT_IN_PROGRESS:"Another promotion attempt holds this target",PROMOTION_RECEIPT_UNVERIFIED:"The attempt to resume cannot be authenticated against the journal",PROMOTION_STAGE_FAILED:"The package did not pass staging on the target; nothing was imported",PROMOTION_STAGE_UNKNOWN:"The staging outcome or its upload id could not be read; nothing was imported",PROMOTION_IMPORT_FAILED:"The import failed or was canceled",PROMOTION_IMPORT_UNKNOWN:"Whether the import was submitted or completed cannot be settled; it is never resent",PROMOTION_STEP_FAILED:"A planned step was refused or failed",PROMOTION_VERIFICATION_FAILED:"A required postcondition does not match, or could not be verified, after the import",PROMOTION_CLEANUP_FAILED:"The staged upload was not deleted; it remains in the target"};Le.PROMOTION_ERROR_CODES=Object.keys(qE);function A$(e,t,n={}){var r;return{code:e,phase:t,blocking:(r=n.blocking)!==null&&r!==void 0?r:!0,message:n.reason?`${qE[e]} (${n.reason}).`:`${qE[e]}.`,...n.subject?{subject:n.subject}:{},...n.stepId?{stepId:n.stepId}:{},...n.httpStatus!==void 0?{httpStatus:n.httpStatus}:{},...n.platformCode?{platformCode:n.platformCode}:{}}}Le.promotionProblem=A$;function ap(e,t,n={}){return new E$.PromotionError(A$(e,t,n))}Le.promotionError=ap;function C$(e){var t;let n={},r=e;r&&typeof r.statusCode=="number"&&r.statusCode>0&&(n.httpStatus=r.statusCode);let i=r?.cause,o=(t=i?.error)===null||t===void 0?void 0:t.code;return typeof o=="string"&&/^0x[0-9a-fA-F]{8}$/.test(o)&&(n.platformCode=o.toLowerCase()),n}Le.safeDiagnostics=C$;function sp(e){if(e===null)return"null";switch(typeof e){case"string":case"boolean":return JSON.stringify(e);case"number":if(!Number.isFinite(e))throw new TypeError("canonicalJson: a non-finite number");return JSON.stringify(e);case"object":{if(Array.isArray(e))return`[${e.map(r=>sp(r===void 0?null:r)).join(",")}]`;let t=e;return`{${Object.keys(t).filter(r=>t[r]!==void 0).sort((r,i)=>r<i?-1:r>i?1:0).map(r=>`${JSON.stringify(r)}:${sp(t[r])}`).join(",")}}`}default:throw new TypeError(`canonicalJson: a ${typeof e} is not JSON`)}}Le.canonicalJson=sp;async function S$(e,t){let n;try{n=await e.sha256(t)}catch{throw ap("PROMOTION_CODEC_REQUIRED","preflight",{reason:"sha256 failed"})}if(typeof n!="string"||!/^[0-9a-f]{64}$/.test(n))throw ap("PROMOTION_CODEC_REQUIRED","preflight",{reason:"sha256 did not return 64 lowercase hexadecimal characters"});return n}Le.sha256Of=S$;function Dee(e,t){return S$(e,(0,Oee.utf8ToBytes)(sp(t)))}Le.digestOf=Dee;function Pee(e){return sp(e)}Le.identityKey=Pee;function Ree(e,t){return e<t?-1:e>t?1:0}Le.byCodeUnit=Ree;var kee=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;Le.ZERO_GUID="00000000-0000-0000-0000-000000000000";function op(e){if(typeof e!="string")return;let t=e.trim().replace(/^\{([^}]*)\}$/,"$1").toLowerCase();return kee.test(t)?t:void 0}Le.canonicalGuid=op;function $ee(e){if(typeof e!="string")return;let t=e.split(".");if(t.length<2||t.length>4||t.some(r=>!/^\d{1,10}$/.test(r)))return;let n=t.map(Number);if(!n.some(r=>r>2147483647)){for(;n.length<4;)n.push(0);return n}}Le.parseVersion=$ee;function Lee(e,t){for(let n=0;n<4;n+=1)if(e[n]!==t[n])return e[n]<t[n]?-1:1;return 0}Le.compareVersions=Lee;Le.DEFAULT_LIMITS={maxCompressedBytes:50*1024*1024,maxExpandedBytes:256*1024*1024,maxEntries:1e4,maxComponents:1e3,maxGetAttempts:5e3,maxLayerPagesPerComponent:10,maxPlanMs:3e5};var BE=class{constructor(t,n,r){this.limits=t,this.now=n,this.timed=r,this.getAttempts=0,this.layerLookups=0,this.layerPages=0,this.components=0,this.exhausted=!1,this.started=n()}get elapsedMs(){return Math.max(0,this.now()-this.started)}exceeded(t){return this.exhausted=!0,ap("PROMOTION_READ_BUDGET_EXCEEDED","preflight",{reason:t})}checkTime(){if(this.timed&&this.elapsedMs>this.limits.maxPlanMs)throw this.exceeded("maxPlanMs")}spendGet(){if(this.checkTime(),this.getAttempts>=this.limits.maxGetAttempts)throw this.exceeded("maxGetAttempts");this.getAttempts+=1}spendLayerPage(t){if(t>=this.limits.maxLayerPagesPerComponent)throw this.exceeded("maxLayerPagesPerComponent");this.layerPages+=1}countComponents(t){if(this.components=t,t>this.limits.maxComponents)throw this.exceeded("maxComponents")}wrap(t){return{get:(r,i)=>(this.spendGet(),t.get(r,i)),post:(r,i,o)=>t.post(r,i,o),patch:(r,i,o)=>t.patch(r,i,o),delete:(r,i)=>t.delete(r,i)}}};Le.ReadBudget=BE;var Mee="/RetrieveCurrentOrganization(AccessType=@p1)?@p1=Microsoft.Dynamics.CRM.EndpointAccessType'Default'";async function xee(e){var t,n;let r=(l,c)=>c instanceof E$.PromotionError?c:ap("PROMOTION_VERIFICATION_UNAVAILABLE","preflight",{reason:l,...C$(c)}),i,o;try{let l=await e.get("/WhoAmI"),c=await e.get(Mee);if(l.status!==200||c.status!==200)throw r("the environment identity could not be read");i=l.body,o=(n=(t=c.body)===null||t===void 0?void 0:t.Detail)!==null&&n!==void 0?n:null}catch(l){throw r("the environment identity could not be read",l)}let a=op(i?.UserId),s=op(o?.OrganizationId),u=op(o?.TenantId);if(!a||!s||!u||op(i?.OrganizationId)!==s)throw r("the environment identity answers are incomplete or disagree");return{organizationId:s,tenantId:u,actorId:a,instanceUrl:N$(e)}}Le.readEnvironment=xee;function N$(e){let t=e.apiUrl("/"),n=/^([a-z][a-z0-9+.-]*:\/\/[^/?#]+)/i.exec(t);return(n?n[1]:t).toLowerCase()}Le.originOf=N$});var T$=C(Dc=>{"use strict";Object.defineProperty(Dc,"__esModule",{value:!0});Dc.readZip=Dc.crc32=void 0;var Fee=Y(),Uee=Ya(),qee=67324752,Bee=33639248,Vee=101010256,Gee=117853008,jee=134695760,Wee=1,_$=8,zee=64,Hee=2048;function We(e){return new Fee.PromotionError((0,Uee.promotionProblem)("PROMOTION_PACKAGE_UNREADABLE","preflight",{reason:e}))}var Og;function I$(e){if(!Og){Og=new Uint32Array(256);for(let n=0;n<256;n+=1){let r=n;for(let i=0;i<8;i+=1)r=r&1?3988292384^r>>>1:r>>>1;Og[n]=r>>>0}}let t=4294967295;for(let n=0;n<e.length;n+=1)t=Og[(t^e[n])&255]^t>>>8;return(t^4294967295)>>>0}Dc.crc32=I$;var Lr=(e,t)=>{if(t+2>e.length)throw We("a header runs past the end of the archive");return e[t]|e[t+1]<<8},tr=(e,t)=>{if(t+4>e.length)throw We("a header runs past the end of the archive");return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0};function Kee(e,t){let n=!0;for(let r of e)r>=128&&(n=!1);if(n)return String.fromCharCode(...Array.from(e));if(!t)throw We("an entry name is neither ASCII nor flagged UTF-8");try{return decodeURIComponent(Array.from(e,r=>`%${r.toString(16).padStart(2,"0")}`).join(""))}catch{throw We("an entry name is not valid UTF-8")}}function Jee(e){if(e.length===0||e.startsWith("/")||e.includes("\\")||/^[A-Za-z]:/.test(e)||/[\u0000-\u001f\u007f]/.test(e))throw We("an entry path is absolute, uses a backslash or drive, or carries a control character");if(e.replace(/\/$/,"").split("/").some(n=>n===""||n==="."||n===".."))throw We('an entry path has an empty, "." or ".." segment')}function Yee(e){let t=Math.max(0,e.length-22-65535);for(let n=e.length-22;n>=t;n-=1)if(tr(e,n)===Vee&&n+22+Lr(e,n+20)===e.length)return n;throw We("no end-of-central-directory record")}async function Qee(e,t,n){if(e.length>n.maxCompressedBytes)throw We("the package is larger than maxCompressedBytes");let r=Yee(e),i=Lr(e,r+4),o=Lr(e,r+6),a=Lr(e,r+8),s=Lr(e,r+10),u=tr(e,r+12),l=tr(e,r+16);if(i!==0||o!==0||a!==s)throw We("a multi-disk archive");if(s===65535||u===4294967295||l===4294967295||r>=20&&tr(e,r-20)===Gee)throw We("a ZIP64 archive");if(s>n.maxEntries)throw We("more entries than maxEntries");if(l+u!==r)throw We("the central directory does not end where the end record begins");let c=new Set,d=[],f=[],p=0,m=l;for(let h=0;h<s;h+=1){if(tr(e,m)!==Bee)throw We("a central directory header is missing");let g=Lr(e,m+8),y=Lr(e,m+10),b=tr(e,m+16),E=tr(e,m+20),w=tr(e,m+24),_=Lr(e,m+28),I=Lr(e,m+30),T=Lr(e,m+32),O=Lr(e,m+34),v=tr(e,m+42);if(m+46+_>r)throw We("a central directory header runs past the directory");let N=e.subarray(m+46,m+46+_);if(m+=46+_+I+T,m>r)throw We("a central directory header runs past the directory");if(g&(Wee|zee))throw We("an encrypted entry");if(O!==0)throw We("a multi-disk archive");if(E===4294967295||w===4294967295||v===4294967295)throw We("a ZIP64 entry");if(y!==0&&y!==8)throw We("an entry compressed by a method other than stored or deflate");if(y===0&&E!==w)throw We("a stored entry whose sizes differ");let S=Kee(N,(g&Hee)!==0);Jee(S);let R=S.toLowerCase();if(c.has(R))throw We("two entries share one path (case-insensitively)");if(c.add(R),tr(e,v)!==qee)throw We("a local header is missing");let x=Lr(e,v+6),G=Lr(e,v+8),U=Lr(e,v+26),M=Lr(e,v+28),q=e.subarray(v+30,v+30+U);if(x!==g||G!==y||U!==_||q.some((wt,Fn)=>wt!==N[Fn])||!(g&_$)&&(tr(e,v+14)!==b||tr(e,v+18)!==E||tr(e,v+22)!==w))throw We("a local header disagrees with its central directory header");let X=v+30+U+M,ye=X+E;if(g&_$){let wt=tr(e,ye)===jee,Fn=ye+(wt?4:0);if(tr(e,Fn)!==b||tr(e,Fn+4)!==E||tr(e,Fn+8)!==w)throw We("a data descriptor disagrees with its central directory header");ye=Fn+12}if(ye>l)throw We("an entry overlaps the central directory");if(d.push([v,ye]),S.endsWith("/")){if(w!==0)throw We("a directory entry carries data");continue}if(p+=w,p>n.maxExpandedBytes)throw We("the package expands past maxExpandedBytes");let Ve=e.subarray(X,X+E),_e;if(y===0)_e=Ve.slice();else{try{_e=await t.inflateRaw(Ve.slice(),w)}catch{throw We("an entry could not be inflated within its declared size")}if(!(_e instanceof Uint8Array))throw We("the codec did not return bytes")}if(_e.length!==w)throw We("an entry inflated to a size other than declared");if(I$(_e)!==b)throw We("an entry does not match its CRC");f.push({name:S,bytes:_e})}d.sort((h,g)=>h[0]-g[0]);for(let h=1;h<d.length;h+=1)if(d[h][0]<d[h-1][1])throw We("two entries overlap");return f}Dc.readZip=Qee});var Pg=C(it=>{"use strict";Object.defineProperty(it,"__esModule",{value:!0});it.pickFields=it.projectRow=it.columnsOf=it.SEARCH_FIELDS=it.SOLUTION_FIELDS=it.ADDRESS_FIELDS=it.PUBLISHER_FIELDS=it.REFERENCE_FIELDS=it.VARIABLE_FIELDS=it.APP_SETTING_FIELDS=it.APP_FIELDS=it.SITEMAP_FIELDS=it.ROLE_FIELDS=it.WEB_RESOURCE_FIELDS=void 0;var di=(e,t)=>({element:e,column:t,kind:"text"}),zn=(e,t)=>({element:e,column:t,kind:"int"}),O$=(e,t)=>({element:e,column:t,kind:"flag"}),Dg=(e,t)=>({element:e,column:t,kind:"word"}),Hs=(e,t)=>({element:e,column:t,kind:"managed"}),Qa=(e,t,n)=>({element:e,column:n,kind:"label",item:t});it.WEB_RESOURCE_FIELDS={displayName:di("DisplayName","displayname"),description:di("Description","description"),languageCode:zn("LanguageCode","languagecode"),introducedVersion:di("IntroducedVersion","introducedversion"),enabledForMobileClient:O$("IsEnabledForMobileClient","isenabledformobileclient"),availableForMobileOffline:O$("IsAvailableForMobileOffline","isavailableformobileoffline"),customizable:Hs("IsCustomizable","iscustomizable"),canBeDeleted:Hs("CanBeDeleted","canbedeleted"),hidden:Hs("IsHidden","ishidden")};it.ROLE_FIELDS={customizable:Hs("IsCustomizable","iscustomizable"),autoAssigned:zn("IsAutoAssigned","isautoassigned"),inherited:zn("IsInherited","isinherited"),description:di("Description","description")};it.SITEMAP_FIELDS={collapsibleGroups:Dg("EnableCollapsibleGroups","enablecollapsiblegroups"),showHome:Dg("ShowHome","showhome"),showPinned:Dg("ShowPinned","showpinned"),showRecents:Dg("ShowRecents","showrecents"),name:Qa("LocalizedNames","LocalizedName","sitemapname")};it.APP_FIELDS={name:Qa("LocalizedNames","LocalizedName","name"),description:Qa("Descriptions","Description","description"),introducedVersion:di("IntroducedVersion","introducedversion"),optimizedFor:di("OptimizedFor","optimizedfor"),stateCode:zn("statecode","statecode"),statusCode:zn("statuscode","statuscode"),formFactor:zn("FormFactor","formfactor"),clientType:zn("ClientType","clienttype"),navigationType:zn("NavigationType","navigationtype")};it.APP_SETTING_FIELDS={customizable:Hs("iscustomizable","iscustomizable")};it.VARIABLE_FIELDS={displayName:Qa("displayname","label","displayname"),description:Qa("description","label","description"),introducedVersion:di("introducedversion","introducedversion"),customizable:Hs("iscustomizable","iscustomizable"),secretStore:zn("secretstore","secretstore"),valueSchema:di("valueschema","valueschema")};it.REFERENCE_FIELDS={displayName:di("connectionreferencedisplayname","connectionreferencedisplayname"),description:di("description","description"),customizable:Hs("iscustomizable","iscustomizable"),promptingBehavior:zn("promptingbehavior","promptingbehavior"),stateCode:zn("statecode","statecode"),statusCode:zn("statuscode","statuscode")};it.PUBLISHER_FIELDS={friendlyName:Qa("LocalizedNames","LocalizedName","friendlyname"),description:Qa("Descriptions","Description","description"),email:di("EMailAddress","emailaddress"),website:di("SupportingWebsiteUrl","supportingwebsiteurl"),optionValuePrefix:zn("CustomizationOptionValuePrefix","customizationoptionvalueprefix")};var Xee=e=>({[`address${e}TypeCode`]:zn("AddressTypeCode",`address${e}_addresstypecode`),[`address${e}ShippingMethodCode`]:zn("ShippingMethodCode",`address${e}_shippingmethodcode`)});it.ADDRESS_FIELDS=Xee;it.SOLUTION_FIELDS={friendlyName:Qa("LocalizedNames","LocalizedName","friendlyname"),description:Qa("Descriptions","Description","description")};it.SEARCH_FIELDS={name:di("name","name"),appModuleUniqueName:di("appmoduleuniquename","appmoduleuniquename"),customizable:Hs("iscustomizable","iscustomizable"),searchType:zn("searchtype","searchtype"),stateCode:zn("statecode","statecode"),statusCode:zn("statuscode","statuscode")};function Zee(...e){let t=new Set;for(let n of e)for(let r of Object.values(n))t.add(r.column);return[...t].sort()}it.columnsOf=Zee;function ete(e,t){if(e===null)return null;switch(t){case"text":case"label":return typeof e=="string"?e===""?null:e:void 0;case"int":return typeof e=="number"&&Number.isSafeInteger(e)?e:void 0;case"flag":case"word":return typeof e=="boolean"?e:void 0;case"managed":{let n=typeof e=="object"?e.Value:e;return typeof n=="boolean"?n:void 0}default:return}}function tte(e,...t){let n={};for(let r of t)for(let i of Object.keys(r).sort()){let o=r[i];if(!(o.column in e))return;let a=ete(e[o.column],o.kind);if(a===void 0)return;n[i]=a}return n}it.projectRow=tte;function nte(e,t){let n={};for(let r of[...t].sort())r in e&&(n[r]=e[r]);return n}it.pickFields=nte});var kg=C(Rt=>{"use strict";Object.defineProperty(Rt,"__esModule",{value:!0});Rt.readPackage=Rt.canonicalSitemapText=Rt.canonicalElement=Rt.SECRET_TYPE=Rt.VARIABLE_TYPES=Rt.COMPONENT=Rt.PACKAGE_PROJECTION_VERSION=void 0;var rte=Ms(),VE=ia(),Qt=Ya(),ite=T$(),sn=Pg();Rt.PACKAGE_PROJECTION_VERSION="promotion-package-v2";Rt.COMPONENT={role:20,webResource:61,sitemap:62,app:80,variable:380};Rt.VARIABLE_TYPES=new Set([1e8,100000001,100000002,100000003,100000004,100000005]);Rt.SECRET_TYPE=100000005;function Ee(e){return(0,Qt.promotionError)("PROMOTION_PACKAGE_UNREADABLE","preflight",{reason:e})}var nl=(e,t)=>({kind:"unsupportedComponent",componentType:e,packageId:t}),Ki="a field this version does not verify",yr="an attribute this version does not interpret",ote="a localized label in another language";function up(e,t){let n=(0,VE.bytesToUtf8)(e).replace(/^\uFEFF/,"");if(/<!DOCTYPE|<!ENTITY/i.test(n))throw Ee(`${t} declares a document type or entity`);let r=[],i=s=>r.push(s),o=new rte.DOMParser({errorHandler:{warning:i,error:i,fatalError:i}}).parseFromString(n,"text/xml"),a=o?.documentElement;if(!a||r.length>0)throw Ee(`${t} is not well-formed XML`);return a}function qt(e){let t=[];for(let n=0;n<e.childNodes.length;n+=1){let r=e.childNodes[n];r.nodeType===1&&t.push(r)}return t}function $$(e){var t;return qt(e).length>0||e.attributes.length>0?!1:((t=e.textContent)!==null&&t!==void 0?t:"").trim()===""}function Mr(e,t){let n=qt(e).filter(r=>r.nodeName===t);if(n.length>1)throw Ee(`an element holds <${t}> twice`);return n[0]}function Ks(e,t){var n;let r=Mr(e,t);if(!r)return null;if(qt(r).length>0)throw Ee(`<${t}> is not a text element`);return(n=r.textContent)!==null&&n!==void 0?n:""}function Hi(e,t){let n=Ks(e,t);if(n===null||n.trim()==="")throw Ee(`a required <${t}> is missing or empty`);return n.trim()}function Js(e,t){if(e===null||e.trim()==="")return null;if(!/^-?\d{1,10}$/.test(e.trim()))throw Ee(`${t} is not a whole number`);return Number(e.trim())}function oa(e,t){return qt(e).some(n=>!t.has(n.nodeName))}function In(e,t){for(let n=0;n<e.attributes.length;n+=1)if(!t.includes(e.attributes[n].name))return!0;return!1}function D$(e,t){let n=e.trim().toLowerCase();if(n==="")return null;let[r,i]=t?["true","false"]:["1","0"];if(n===r)return!0;if(n===i)return!1;throw Ee(t?"a field is neither True nor False":"a field is neither 0 nor 1")}function vo(e,t,n,r){var i;let o={};for(let a of Object.keys(t).sort(Qt.byCodeUnit)){let s=t[a],u=Mr(e,s.element);if(!u)continue;if(s.kind==="label"){In(u,["default"])&&r(yr);let c=qt(u);if(c.some(p=>p.nodeName!==s.item))throw Ee("a localized label list holds another element");c.some(p=>In(p,["description","languagecode"]))&&r(yr),c.some(p=>p.getAttribute("languagecode")!==String(n))&&r(ote);let d=c.find(p=>p.getAttribute("languagecode")===String(n)),f=d?d.getAttribute("description"):u.getAttribute("default");o[a]=f===null||f===""?null:f;continue}if(In(u,["xsi:nil"])&&r(yr),qt(u).length>0)throw Ee("a field element is not a text element");let l=u.getAttribute("xsi:nil")==="true"?"":(i=u.textContent)!==null&&i!==void 0?i:"";switch(s.kind){case"text":o[a]=l===""?null:l;break;case"int":o[a]=Js(l,"a numeric field");break;case"word":o[a]=D$(l,!0);break;default:o[a]=D$(l,!1)}}return o}var aa=(e,...t)=>new Set([...e,...t.flatMap(n=>Object.values(n).map(r=>r.element))]);function Rg(e){var t,n;let r=[];for(let o=0;o<e.attributes.length;o+=1){let a=e.attributes[o];r.push(`${a.name}=${JSON.stringify(a.value)}`)}r.sort(Qt.byCodeUnit);let i=[];for(let o=0;o<e.childNodes.length;o+=1){let a=e.childNodes[o];a.nodeType===1?i.push(Rg(a)):(a.nodeType===3||a.nodeType===4)&&((t=a.nodeValue)!==null&&t!==void 0?t:"").trim()!==""&&i.push(JSON.stringify(((n=a.nodeValue)!==null&&n!==void 0?n:"").trim()))}return`<${e.nodeName}${r.length?` ${r.join(" ")}`:""}>${i.join("")}</${e.nodeName}>`}Rt.canonicalElement=Rg;function ate(e){try{return Rg(up((0,VE.utf8ToBytes)(e),"sitemap"))}catch{return}}Rt.canonicalSitemapText=ate;var ste=aa(["UniqueName","Version","Managed","Publisher","RootComponents","MissingDependencies"],sn.SOLUTION_FIELDS),ute=aa(["UniqueName","CustomizationPrefix","Addresses"],sn.PUBLISHER_FIELDS),P$="AddressNumber",R$={Entities:1,optionsets:9,EntityRelationships:10,Workflows:29,Templates:36,EntityMaps:46,FieldSecurityProfiles:70,OrganizationSettings:0,EntityDataProviders:0,CustomControls:66,SolutionPluginAssemblies:91,SdkMessageProcessingSteps:92},lte=new Set(["Assets","botcomponents","CanvasApps","connectionreferences","Controls","customapis","dvtablesearchs","environmentvariabledefinitions","Formulas","Other","PluginAssemblies","Reports","Templates","WebResources","Workflows"]),cte=aa(["RolePrivileges"],sn.ROLE_FIELDS),dte=aa(["WebResourceId","Name","WebResourceType","FileName"],sn.WEB_RESOURCE_FIELDS),fte=aa(["SiteMapUniqueName","SiteMap","Descriptions"],sn.SITEMAP_FIELDS),pte=aa(["UniqueName","WebResourceId","AppModuleComponents","AppModuleRoleMaps","appsettings"],sn.APP_FIELDS),mte=aa(["value"],sn.APP_SETTING_FIELDS),hte=aa(["connectorid"],sn.REFERENCE_FIELDS),gte=aa(["defaultvalue","isrequired","type"],sn.VARIABLE_FIELDS),yte=aa(["m365appmoduleid"],sn.SEARCH_FIELDS),bte=["GenPageId","Page","DefaultDashboard"],k$=/^\$webresource:/i;async function vte(e,t,n){var r,i,o,a,s,u;let l=await(0,Qt.sha256Of)(t,e),c=await(0,ite.readZip)(e,t,n),d=new Map(c.map(W=>[W.name,W])),f=new Set(["[Content_Types].xml"]),p=[],m=W=>{let Fe=d.get(W);if(!Fe)throw Ee("a file the package names is missing");return f.add(W),Fe.bytes},h=up(m("solution.xml"),"solution.xml");if(h.nodeName!=="ImportExportXml")throw Ee("solution.xml is not an ImportExportXml document");let g=Mr(h,"SolutionManifest");if(!g)throw Ee("solution.xml has no SolutionManifest");qt(g).forEach((W,Fe)=>{ste.has(W.nodeName)||p.push({subject:nl(0,`solution.xml#SolutionManifest/${Fe+1}`),reason:"an unrecognized manifest element"})});let y=(r=Js(h.getAttribute("languagecode"),"languagecode"))!==null&&r!==void 0?r:1033,b=Hi(g,"UniqueName"),E={kind:"solution",uniqueName:b},w=W=>Fe=>{p.some(Ie=>Ie.reason===Fe&&JSON.stringify(Ie.subject)===JSON.stringify(W))||p.push({subject:W,reason:Fe})},_=vo(g,sn.SOLUTION_FIELDS,y,w(E)),I=Hi(g,"Version");if(!(0,Qt.parseVersion)(I))throw Ee("the solution version is not a numeric version");let T=Hi(g,"Managed");if(T!=="0"&&T!=="1")throw Ee("the managed bit is neither 0 nor 1");let O=Mr(g,"Publisher");if(!O)throw Ee("the manifest has no Publisher");let v=Hi(O,"UniqueName"),N=Hi(O,"CustomizationPrefix"),S=w({kind:"publisher",uniqueName:v});(oa(O,ute)||In(O,[]))&&S(Ki);let R={...vo(O,sn.PUBLISHER_FIELDS,y,S),...wte(Mr(O,"Addresses"),S)},x=[],G=Mr(g,"RootComponents");for(let W of G?qt(G):[]){if(W.nodeName!=="RootComponent")throw Ee("RootComponents holds an element that is not a RootComponent");let Fe=Js(W.getAttribute("type"),"a root component type");if(Fe===null)throw Ee("a root component has no type");let Ie=W.getAttribute("id"),At=Ie&&(i=(0,Qt.canonicalGuid)(Ie))!==null&&i!==void 0?i:null;if(Ie&&!At)throw Ee("a root component id is not a GUID");let Ts=W.getAttribute("schemaName")||null;(In(W,["type","id","schemaName","behavior"])||((o=W.getAttribute("behavior"))!==null&&o!==void 0?o:"0")!=="0")&&p.push({subject:nl(Fe,At??Ts),reason:yr}),x.push({type:Fe,id:At,schemaName:Ts})}let U=[],M=Mr(g,"MissingDependencies");for(let W of M?qt(M):[]){let Fe=W.nodeName==="MissingDependency"?Mr(W,"Required"):void 0;if(!Fe)throw Ee("a MissingDependency has no Required");let Ie=Fe.getAttribute("id");U.push({type:(a=Fe.getAttribute("type"))!==null&&a!==void 0?a:"",schemaName:Fe.getAttribute("id.schemaname")||Fe.getAttribute("schemaName")||null,uniqueName:Fe.getAttribute("id.uniquename")||null,id:Ie&&(s=(0,Qt.canonicalGuid)(Ie))!==null&&s!==void 0?s:null})}let q=up(m("customizations.xml"),"customizations.xml");if(q.nodeName!=="ImportExportXml")throw Ee("customizations.xml is not an ImportExportXml document");let X=[],ye=[],Ve=[],_e=[],wt=[],Fn=new Set;qt(q).forEach((W,Fe)=>{let Ie=W.nodeName;if(Fn.has(Ie))throw Ee("customizations.xml holds one container twice");switch(Fn.add(Ie),Ie){case"Roles":for(let At of qt(W))wt.push(Ete(At,p,y));break;case"WebResources":for(let At of qt(W))Ve.push(Ate(At,p,m,y));break;case"AppModuleSiteMaps":for(let At of qt(W))ye.push(Nte(At,p,y));break;case"AppModules":for(let At of qt(W))X.push(_te(At,p,y));break;case"connectionreferences":for(let At of qt(W))_e.push(Ite(At,p,y));break;case"Languages":for(let At of qt(W))if(At.nodeName!=="Language"||Js(At.textContent,"a language")===null)throw Ee("Languages holds something other than a language code");break;default:if(!$$(W)){let At=Object.prototype.hasOwnProperty.call(R$,Ie),Ts=At?R$[Ie]:0;p.push({subject:nl(Ts,At?`customizations.xml#${Ie}`:`customizations.xml#${Fe+1}`),reason:Ts?"a component kind without a certified provider":"an unrecognized customizations element"})}}});let xe=[],Et=[];for(let W of c){let Fe=/^environmentvariabledefinitions\/([^/]+)\/environmentvariabledefinition\.xml$/.exec(W.name);Fe&&(f.add(W.name),xe.push(Tte(W.bytes,Fe[1],d,f,p,y)));let Ie=/^dvtablesearchs\/([^/]+)\/dvtablesearch\.xml$/.exec(W.name);Ie&&(f.add(W.name),Et.push(Ote(W.bytes,Ie[1],p,y)))}let zt=new Set;c.forEach((W,Fe)=>{if(!f.has(W.name)){let Ie=W.name.includes("/")?W.name.slice(0,W.name.indexOf("/")):"";zt.add(lte.has(Ie)?Ie:`entry#${Fe+1}`)}});for(let W of[...zt].sort(Qt.byCodeUnit))p.push({subject:nl(0,W),reason:"a package file no certified provider reads"});for(let W of Et)X.some(Fe=>Fe.uniqueName.toLowerCase()===W.appUniqueName.toLowerCase())||p.push({subject:{kind:"appSearch",packageId:W.id,appUniqueName:W.appUniqueName},reason:"a search row of an app outside the package"});for(let W of x)W.type===Rt.COMPONENT.role&&wt.some(Ie=>Ie.id===W.id)||W.type===Rt.COMPONENT.webResource&&Ve.some(Ie=>Ie.name===W.schemaName)||W.type===Rt.COMPONENT.sitemap&&ye.some(Ie=>Ie.uniqueName===W.schemaName)||W.type===Rt.COMPONENT.app&&X.some(Ie=>Ie.uniqueName===W.schemaName)||W.type===Rt.COMPONENT.variable&&xe.some(Ie=>Ie.schemaName===W.schemaName)||W.type>=1e4&&_e.some(Ie=>Ie.logicalName===W.schemaName)||p.push({subject:nl(W.type,(u=W.id)!==null&&u!==void 0?u:W.schemaName),reason:"a root component this version does not project, or one the package does not define"});let Ht=(W,Fe)=>W.sort((Ie,At)=>(0,Qt.byCodeUnit)(Fe(Ie),Fe(At)));return{sha256:l,solutionUniqueName:b,version:I,managed:T==="1",publisherUniqueName:v,publisherPrefix:N,languageCode:y,solutionFields:_,publisherFields:R,apps:Ht(X,W=>W.uniqueName),sitemaps:Ht(ye,W=>W.uniqueName),webResources:Ht(Ve,W=>W.name),variables:Ht(xe,W=>W.schemaName),references:Ht(_e,W=>W.logicalName),roles:Ht(wt,W=>W.id),searches:Ht(Et,W=>W.id),dependencies:U,gaps:p,componentCount:X.length+ye.length+Ve.length+xe.length+_e.length+wt.length+Et.length+p.length}}Rt.readPackage=vte;function wte(e,t){var n;if(!e)return{};In(e,[])&&t(yr);let r={};for(let i of qt(e)){let o=Js(Ks(i,P$),"an address number");if(i.nodeName!=="Address"||o!==1&&o!==2||In(i,[])){t(Ki);continue}let a=(0,sn.ADDRESS_FIELDS)(o),s=new Set([P$,...Object.values(a).map(u=>u.element)]);for(let u of qt(i)){let l=u.getAttribute("xsi:nil")==="true"&&((n=u.textContent)!==null&&n!==void 0?n:"")==="";!s.has(u.nodeName)&&!l&&t(Ki)}Object.assign(r,vo(i,a,0,t))}return r}function Ete(e,t,n){var r;if(e.nodeName!=="Role")throw Ee("Roles holds an element that is not a Role");let i=(0,Qt.canonicalGuid)(e.getAttribute("id"));if(!i)throw Ee("a Role has no GUID id");let o=u=>t.push({subject:nl(Rt.COMPONENT.role,i),reason:u});oa(e,cte)&&o(Ki),In(e,["id","name"])&&o(yr);let a=[],s=Mr(e,"RolePrivileges");for(let u of s?qt(s):[]){let l=u.getAttribute("name"),c=u.getAttribute("level");if(u.nodeName!=="RolePrivilege"||!l||!c)throw Ee("a RolePrivilege has no name or level");In(u,["name","level"])&&o(yr),a.push(`${l}:${c}`)}return{id:i,name:(r=e.getAttribute("name"))!==null&&r!==void 0?r:"",privileges:[...new Set(a)].sort(Qt.byCodeUnit),fields:vo(e,sn.ROLE_FIELDS,n,o)}}function Ate(e,t,n,r){if(e.nodeName!=="WebResource")throw Ee("WebResources holds an element that is not a WebResource");let i=(0,Qt.canonicalGuid)(Hi(e,"WebResourceId"));if(!i)throw Ee("a WebResourceId is not a GUID");let o=Hi(e,"Name"),a=Js(Hi(e,"WebResourceType"),"WebResourceType"),s=l=>t.push({subject:{kind:"webResource",name:o},reason:l});oa(e,dte)&&s(Ki),In(e,[])&&s(yr);let u=Hi(e,"FileName").replace(/^\//,"");return{id:i,name:o,type:a,fileName:u,bytes:n(u),fields:vo(e,sn.WEB_RESOURCE_FIELDS,r,s)}}function Cte(e){var t,n,r;let i=e.trim();if(k$.test(i)){let f=i.replace(k$,"").split("?")[0].trim();return f===""?{unsupported:!0}:{resource:f}}let o=i.indexOf("#"),a=o<0?i:i.slice(0,o),s=a.indexOf("?"),u=s<0?a:a.slice(0,s),l=s<0?"":a.slice(s+1),c=f=>{try{return decodeURIComponent(f)}catch{return}},d=u.toLowerCase();if(d.includes("webresources/")){let f=d.indexOf("/webresources/");if(f<0)return{unsupported:!0};let p=u.slice(0,f);if(p!==""&&!/^\/(\{[^/{}]*\}|%7b[^/]*%7d)$/i.test(p))return{unsupported:!0};let m=c(u.slice(f+14));return m===void 0||m.trim()===""?{unsupported:!0}:{resource:m}}if(/(^|\/)main\.aspx$/i.test(u)){let f=new Map;for(let h of l.split("&")){let g=h.indexOf("="),y=c(g<0?h:h.slice(0,g)),b=c(g<0?"":h.slice(g+1).replace(/\+/g," "));if(y===void 0||b===void 0)return{unsupported:!0};f.set(y.toLowerCase(),b)}let p=(t=f.get("pagetype"))===null||t===void 0?void 0:t.toLowerCase(),m=/^\/?main\.aspx$/i.test(u);if(p==="webresource"){let h=(n=f.get("webresourcename"))!==null&&n!==void 0?n:"";return h===""||!m?{unsupported:!0}:{resource:h}}if(p==="entitylist"||p==="entityrecord"||p===void 0&&f.has("etn")){let h=(r=f.get("etn"))!==null&&r!==void 0?r:"";return h===""||!m?{unsupported:!0}:{table:h.toLowerCase()}}return p===void 0?{}:{unsupported:!0}}return{}}function Ste(e){let t=new Set,n=new Set,r=!1,i=o=>{for(let a=0;a<o.attributes.length;a+=1){let{name:s,value:u}=o.attributes[a],l=Cte(u);l.resource!==void 0?t.add(l.resource):l.table!==void 0?n.add(l.table):l.unsupported?r=!0:s==="Entity"&&u.trim()!==""?n.add(u.trim().toLowerCase()):bte.includes(s)&&u.trim()!==""&&(r=!0)}qt(o).forEach(i)};return i(e),{webResources:[...t].sort(Qt.byCodeUnit),tables:[...n].sort(Qt.byCodeUnit),unsupported:r}}function Nte(e,t,n){if(e.nodeName!=="AppModuleSiteMap")throw Ee("AppModuleSiteMaps holds an element that is not an AppModuleSiteMap");let r=Hi(e,"SiteMapUniqueName"),i=u=>t.push({subject:{kind:"sitemap",uniqueName:r},reason:u});oa(e,fte)&&i(Ki),In(e,[])&&i(yr);let o=Mr(e,"Descriptions");o&&!$$(o)&&i(Ki);let a=Mr(e,"SiteMap");if(!a)throw Ee("an AppModuleSiteMap has no SiteMap");let s=Ste(a);return s.unsupported&&i("a sitemap link of a kind without a certified provider"),{uniqueName:r,canonicalXml:Rg(a),fields:vo(e,sn.SITEMAP_FIELDS,n,i),webResources:s.webResources,tables:s.tables}}function _te(e,t,n){var r,i,o;if(e.nodeName!=="AppModule")throw Ee("AppModules holds an element that is not an AppModule");let a=Hi(e,"UniqueName"),s={kind:"app",uniqueName:a},u=y=>t.push({subject:s,reason:y});oa(e,pte)&&u(Ki),In(e,[])&&u(yr);let l=Ks(e,"WebResourceId"),c=l&&l.trim()&&(r=(0,Qt.canonicalGuid)(l))!==null&&r!==void 0?r:null;if(l&&l.trim()&&!c)throw Ee("an app WebResourceId is not a GUID");let d=[],f=Mr(e,"AppModuleComponents");for(let y of f?qt(f):[]){let b=Js(y.getAttribute("type"),"an app component type"),E=y.getAttribute("schemaName");(y.nodeName!=="AppModuleComponent"||In(y,["type","schemaName","id"]))&&u(yr),b===Rt.COMPONENT.sitemap&&E?d.push(E):t.push({subject:nl(b??0,(o=(i=(0,Qt.canonicalGuid)(y.getAttribute("id")))!==null&&i!==void 0?i:E)!==null&&o!==void 0?o:null),reason:"an app component of a kind without a certified provider"})}let p=[],m=Mr(e,"AppModuleRoleMaps");for(let y of m?qt(m):[]){let b=(0,Qt.canonicalGuid)(y.getAttribute("id"));if(y.nodeName!=="Role"||!b)throw Ee("an AppModuleRoleMaps entry is not a Role with a GUID id");In(y,["id"])&&u(yr),p.push(b)}let h=[],g=Mr(e,"appsettings");for(let y of g?qt(g):[]){let b=y.getAttribute("settingdefinitionid.uniquename"),E=Ks(y,"value");if(y.nodeName!=="appsetting"||!b||E===null)throw Ee("an appsetting has no definition or value");let w=_=>t.push({subject:{kind:"appSetting",appUniqueName:a,settingUniqueName:b},reason:_});oa(y,mte)&&w(Ki),In(y,["settingdefinitionid.uniquename"])&&w(yr),h.push({definition:b,value:E,fields:vo(y,sn.APP_SETTING_FIELDS,n,w)})}if(new Set(h.map(y=>y.definition.toLowerCase())).size!==h.length)throw Ee("an app carries one setting definition twice");return{uniqueName:a,fields:vo(e,sn.APP_FIELDS,n,u),iconWebResourceId:c,sitemapNames:d.sort(Qt.byCodeUnit),roleIds:[...new Set(p)].sort(Qt.byCodeUnit),settings:h.sort((y,b)=>(0,Qt.byCodeUnit)(y.definition,b.definition))}}function Ite(e,t,n){let r=e.getAttribute("connectionreferencelogicalname");if(e.nodeName!=="connectionreference"||!r)throw Ee("a connectionreference has no logical name");let i=o=>t.push({subject:{kind:"connectionReference",logicalName:r},reason:o});return oa(e,hte)&&i(Ki),In(e,["connectionreferencelogicalname"])&&i(yr),{logicalName:r,connectorId:Hi(e,"connectorid"),fields:vo(e,sn.REFERENCE_FIELDS,n,i)}}function Tte(e,t,n,r,i,o){let a=up(e,"an environment variable definition"),s=a.getAttribute("schemaname");if(a.nodeName!=="environmentvariabledefinition"||!s)throw Ee("an environment variable definition has no schema name");if(s.toLowerCase()!==t.toLowerCase())throw Ee("an environment variable definition is filed under another name");let u=p=>i.push({subject:{kind:"environmentVariable",schemaName:s},reason:p});oa(a,gte)&&u(Ki),In(a,["schemaname"])&&u(yr);let l=Js(Ks(a,"type"),"a variable type");if(l===null||!Rt.VARIABLE_TYPES.has(l))throw Ee("a variable type is unknown, so its Secret classification is incomplete");let c=Ks(a,"isrequired"),d=`environmentvariabledefinitions/${t}/environmentvariablevalues.json`,f=n.get(d);if(f){r.add(d);let p;try{p=JSON.parse((0,VE.bytesToUtf8)(f.bytes).replace(/^\uFEFF/,""))}catch{throw Ee("a variable value file is not JSON")}if(typeof p!="object"||p===null||!("environmentvariablevalues"in p))throw Ee("a variable value file is not an environmentvariablevalues document")}return{schemaName:s,type:l,isRequired:c!==null&&c.trim()==="1",defaultValue:Ks(a,"defaultvalue"),hasCurrentValue:f!==void 0,fields:vo(a,sn.VARIABLE_FIELDS,o,u)}}function Ote(e,t,n,r){let i=up(e,"a search row"),o=(0,Qt.canonicalGuid)(i.getAttribute("dvtablesearchid"));if(i.nodeName!=="dvtablesearch"||!o)throw Ee("a search row has no GUID id");if((0,Qt.canonicalGuid)(t)!==o)throw Ee("a search row is filed under another id");let a=Mr(i,"m365appmoduleid"),s=a?Ks(a,"uniquename"):null;if(!a||!s||s.trim()==="")throw Ee("a search row names no app");let u={kind:"appSearch",packageId:o,appUniqueName:s},l=c=>n.push({subject:u,reason:c});return(oa(i,yte)||oa(a,new Set(["uniquename"])))&&l(Ki),(In(i,["dvtablesearchid"])||In(a,[]))&&l(yr),{id:o,appUniqueName:s,fields:vo(i,sn.SEARCH_FIELDS,r,l)}}});var il=C(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.resolveCustomApiComponentTypes=me.resolveAppPartComponentType=me.resolveConnectionReferenceComponentType=me.resolveGenPageComponentType=me.SolutionComponentType=void 0;var Dte=Ke(),rr=pe(),Ur=ae(),Pte=ft(),br=Y();me.SolutionComponentType={SavedQuery:26,Workflow:29,SavedQueryVisualization:59,SystemForm:60,AppModule:80,EnvironmentVariableDefinition:380,EnvironmentVariableValue:381,FieldSecurityProfile:70,DuplicateRule:4414,DuplicateRuleCondition:4416,DuplicateRuleClassic:44,DuplicateRuleConditionClassic:45};var Rte=[me.SolutionComponentType.SavedQuery,me.SolutionComponentType.Workflow,me.SolutionComponentType.SavedQueryVisualization,me.SolutionComponentType.SystemForm,me.SolutionComponentType.AppModule,me.SolutionComponentType.EnvironmentVariableDefinition,me.SolutionComponentType.EnvironmentVariableValue,me.SolutionComponentType.FieldSecurityProfile,me.SolutionComponentType.DuplicateRule,me.SolutionComponentType.DuplicateRuleCondition,me.SolutionComponentType.DuplicateRuleClassic,me.SolutionComponentType.DuplicateRuleConditionClassic],kte="uxagentproject",$te="connectionreference",GE=new WeakMap;async function Lg(e,t,n){var r,i;let o=(r=GE.get(e))===null||r===void 0?void 0:r.get(t);if(o!==void 0)return o;let a=`/EntityDefinitions(LogicalName='${t}')${(0,Ur.odataQuery)([["$select","ObjectTypeCode"]])}`,s=await e.get(a);if(s.status===404)return;(0,rr.ensureSuccess)(s,e.apiUrl(a));let u=(i=s.body)===null||i===void 0?void 0:i.ObjectTypeCode;if(typeof u!="number"||!Number.isInteger(u)||u<=0)throw new br.SdkError(n.errorCode,`${n.owner} solution component type \u2014 the ObjectTypeCode of '${t}' \u2014 could not be read: its metadata answered without a usable value (${JSON.stringify(u)}). Without it a solution's ${n.plural} cannot be told apart from other components. Retry.`);let l=GE.get(e);return l||(l=new Map,GE.set(e,l)),l.set(t,u),u}function q$(e){return Lg(e,kte,{errorCode:"GENPAGE_COMPONENT_TYPE_UNRESOLVED",owner:"A generative page's",plural:"generative pages"})}me.resolveGenPageComponentType=q$;function B$(e){return Lg(e,$te,{errorCode:"CONNECTION_REFERENCE_COMPONENT_TYPE_UNRESOLVED",owner:"A connection reference's",plural:"connection references"})}me.resolveConnectionReferenceComponentType=B$;function Lte(e,t){return Lg(e,t,{errorCode:"APP_PART_COMPONENT_TYPE_UNRESOLVED",owner:t==="appsetting"?"An app setting's":"An app search row's",plural:t==="appsetting"?"app settings":"app search rows"})}me.resolveAppPartComponentType=Lte;var Mte={api:"customapi",requestParameter:"customapirequestparameter",responseProperty:"customapiresponseproperty"};async function V$(e){let t={};for(let[n,r]of Object.entries(Mte)){let i=await Lg(e,r,{errorCode:"CUSTOM_API_COMPONENT_TYPE_UNRESOLVED",owner:"A custom API's",plural:"custom APIs"});i!==void 0&&(t[n]=i)}return t}me.resolveCustomApiComponentTypes=V$;var L$=1,M$=0;async function xte(e,t){let n=(0,Ur.normalizeGuid)(t,"solutionId"),r=await q$(e),i=await B$(e),o=await V$(e),a=new Map(Object.entries(o).map(([p,m])=>[m,p])),u=[L$,...Rte,...r===void 0?[]:[r],...i===void 0?[]:[i],...a.keys()].map(p=>`componenttype eq ${p}`).join(" or "),l=`/solutioncomponents${(0,Ur.odataQuery)([["$select","objectid,componenttype,rootcomponentbehavior"],["$filter",`_solutionid_value eq ${n} and (${u})`]])}`,c=await(0,Dte.collectPages)(e,l,"fetchSolutionComponents"),d=[];for(let p of c){if(typeof p.objectid!="string")continue;let m=Number(p.componenttype),h=m===me.SolutionComponentType.DuplicateRuleClassic?me.SolutionComponentType.DuplicateRule:m===me.SolutionComponentType.DuplicateRuleConditionClassic?me.SolutionComponentType.DuplicateRuleCondition:m;if(h===L$){let g=p.rootcomponentbehavior;(g===M$||g===String(M$))&&d.push({objectId:p.objectid,componentType:h,includesAllSubcomponents:!0});continue}d.push({objectId:p.objectid,componentType:h,...r!==void 0&&h===r?{genPage:!0}:{},...i!==void 0&&h===i?{connectionReference:!0}:{},...a.has(h)&&h!==r&&h!==i?{customApi:a.get(h)}:{}})}let f=p=>p.objectId.toLowerCase().replace(/^\{|\}$/g,"");return d.sort((p,m)=>p.componentType-m.componentType||(f(p)<f(m)?-1:f(p)>f(m)?1:0))}me.fetchSolutionComponents=xte;function Fte(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 Ute(e,t){var n,r,i,o,a,s,u,l,c,d;let f=String(t??"").trim();if(!f)throw new br.InvalidArgumentError("getSolution: a solution unique name or id is required.");let p=Fte(f)?`solutionid eq ${(0,Ur.normalizeGuid)(f,"solutionId")}`:`uniquename eq '${(0,Ur.odataLiteral)(f)}'`,m=`/solutions${(0,Ur.odataQuery)([["$select","solutionid,uniquename,friendlyname,version,ismanaged"],["$expand","publisherid($select=publisherid,uniquename,customizationprefix,customizationoptionvalueprefix)"],["$filter",p]])}`,y=((r=(n=(0,rr.ensureSuccess)(await e.get(m),e.apiUrl(m)).body)===null||n===void 0?void 0:n.value)!==null&&r!==void 0?r:[])[0];if(!y?.solutionid)throw new br.InvalidArgumentError(`No solution found for '${t}'.`);let b=y.publisherid;if(!b?.publisherid)throw new br.InvalidArgumentError(`Solution '${(i=y.uniquename)!==null&&i!==void 0?i:t}' returned no owning publisher, so its customization prefix cannot be determined; refusing to report an empty prefix that could be mistaken for "no prefix".`);if(!("customizationprefix"in b))throw new br.InvalidArgumentError(`Solution '${(o=y.uniquename)!==null&&o!==void 0?o:t}' returned a publisher without a customizationprefix property (partial expansion), so its prefix cannot be determined.`);return{solutionId:(0,Ur.normalizeGuid)(y.solutionid,"solutionId"),uniqueName:(a=y.uniquename)!==null&&a!==void 0?a:"",friendlyName:(s=y.friendlyname)!==null&&s!==void 0?s:"",version:(u=y.version)!==null&&u!==void 0?u:"",isManaged:!!y.ismanaged,publisherId:(0,Ur.normalizeGuid)(b.publisherid,"publisherId"),publisherUniqueName:(l=b.uniquename)!==null&&l!==void 0?l:"",publisherPrefix:(c=b.customizationprefix)!==null&&c!==void 0?c:"",publisherOptionValuePrefix:(d=b.customizationoptionvalueprefix)!==null&&d!==void 0?d:0}}me.getSolution=Ute;async function qte(e,t){var n;let r={uniquename:t.uniqueName,friendlyname:t.friendlyName,customizationprefix:t.prefix,customizationoptionvalueprefix:(n=t.optionValuePrefix)!==null&&n!==void 0?n:1e4};t.description&&(r.description=t.description);let i=(0,rr.ensureSuccess)(await(0,rr.resendDeadlockVictim)(()=>e.post("/publishers",{...r})),e.apiUrl("/publishers")),o=(0,rr.readCreatedId)(i,"publisherid");if(!o)throw new br.InvalidArgumentError(`Dataverse did not return an id for publisher '${t.uniqueName}'`);return{id:o,uniqueName:t.uniqueName}}me.createPublisher=qte;async function Bte(e,t){var n;let r=(0,Ur.normalizeGuid)(t.publisherId,"publisherId"),i={uniquename:t.uniqueName,friendlyname:t.friendlyName,version:(n=t.version)!==null&&n!==void 0?n:"1.0.0.0","[email protected]":`/publishers(${r})`};t.description&&(i.description=t.description);let o=(0,rr.ensureSuccess)(await e.post("/solutions",i),e.apiUrl("/solutions")),a=(0,rr.readCreatedId)(o,"solutionid");if(!a)throw new br.InvalidArgumentError(`Dataverse did not return an id for solution '${t.uniqueName}'`);return{id:a,uniqueName:t.uniqueName}}me.createSolution=Bte;async function Vte(e,t,n){let i=`/solutions(${(0,Ur.normalizeGuid)(t,"solutionId")})`;(0,rr.ensureSuccess)(await e.patch(i,{version:n}),e.apiUrl(i))}me.setSolutionVersion=Vte;async function Gte(e,t){var n;let i={ComponentId:(0,Ur.normalizeGuid)(t.componentId,"componentId"),ComponentType:t.componentType,SolutionUniqueName:t.solutionUniqueName,AddRequiredComponents:(n=t.addRequiredComponents)!==null&&n!==void 0?n:!1};t.doNotIncludeSubcomponents!==void 0&&(i.DoNotIncludeSubcomponents=t.doNotIncludeSubcomponents),(0,rr.ensureSuccess)(await e.post("/AddSolutionComponent",i),e.apiUrl("/AddSolutionComponent"))}me.addSolutionComponent=Gte;async function jte(e,t,n,r){let o={SolutionComponent:{"@odata.type":"Microsoft.Dynamics.CRM.solutioncomponent",solutioncomponentid:(0,Ur.normalizeGuid)(t,"componentId")},ComponentType:n,SolutionUniqueName:r};(0,rr.ensureSuccess)(await e.post("/RemoveSolutionComponent",o),e.apiUrl("/RemoveSolutionComponent"))}me.removeSolutionComponent=jte;async function Wte(e,t){var n,r;let i={SolutionName:t.solutionName,Managed:(n=t.managed)!==null&&n!==void 0?n:!1},a=(r=(0,rr.ensureSuccess)(await e.post("/ExportSolution",i),e.apiUrl("/ExportSolution")).body)===null||r===void 0?void 0:r.ExportSolutionFile;if(!a)throw new br.InvalidArgumentError(`ExportSolution returned no file for '${t.solutionName}'`);return{base64:a}}me.exportSolution=Wte;async function zte(e,t){let n=[["overwriteUnmanagedCustomizations","overwrote unmanaged customizations made over the solution's components"],["publishWorkflows","activated the solution's workflows"]];for(let[a,s]of n)if(typeof t?.[a]!="boolean")throw new br.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 r=t.deploymentSettings===void 0?void 0:rne(t.deploymentSettings),i={OverwriteUnmanagedCustomizations:t.overwriteUnmanagedCustomizations,PublishWorkflows:t.publishWorkflows,CustomizationFile:t.base64,ImportJobId:t.importJobId?(0,Ur.normalizeGuid)(t.importJobId,"importJobId"):(0,Pte.newId)()};if(!r)return(0,rr.ensureSuccess)(await e.post("/ImportSolution",i),e.apiUrl("/ImportSolution")),{};if(r.variables.length===0&&r.references.length===0)return(0,rr.ensureSuccess)(await e.post("/ImportSolution",i),e.apiUrl("/ImportSolution")),{appliedSettings:{environmentVariables:[],connectionReferences:[]}};let o=[];try{let a=await G$(e,t.base64,lp,o),{parameters:s,applied:u}=ine(a,r);return i.ComponentParameters=s,(0,rr.ensureSuccess)(await e.post("/ImportSolution",i),e.apiUrl("/ImportSolution")),{appliedSettings:u,...o.length>0?{warnings:o}:{}}}catch(a){throw(0,br.withCleanupWarnings)(a,o)}}me.importSolution=zte;var lp="importSolution",x$="getDeploymentSettingsTemplate";async function Hte(e,t){var n;let r=t?.base64;if(typeof r!="string"||r.length===0)throw new br.InvalidArgumentError(`${x$}: 'base64' must be the solution package \u2014 a non-empty base64 string, e.g. exportSolution's result (it was ${(n=JSON.stringify(r))!==null&&n!==void 0?n:String(r)})`);let i=[];try{let o=await G$(e,r,x$,i),a=$g(o.variables,u=>u.SchemaName).map(({SchemaName:u,DefaultValue:l,TypeId:c,IsRequired:d})=>({SchemaName:u,Value:"",...l!==void 0?{DefaultValue:l}:{},...c!==void 0?{TypeId:c}:{},...d!==void 0?{IsRequired:d}:{}})),s=$g(o.references,u=>u.LogicalName).map(({LogicalName:u,ConnectorId:l})=>({LogicalName:u,ConnectionId:"",...l!==void 0?{ConnectorId:l}:{}}));return{settings:{EnvironmentVariables:a,ConnectionReferences:s},...i.length>0?{warnings:i}:{}}}catch(o){throw(0,br.withCleanupWarnings)(o,i)}}me.getDeploymentSettingsTemplate=Hte;function $g(e,t){return[...e].sort((n,r)=>{let i=t(n).toLowerCase(),o=t(r).toLowerCase();return i<o?-1:i>o?1:0})}function rl(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function nr(e,t=120){var n;let r=(n=JSON.stringify(e))!==null&&n!==void 0?n:String(e);return r.length>t?`${r.slice(0,t)}\u2026`:r}async function G$(e,t,n,r){var i;let a=(i=(0,rr.ensureSuccess)(await e.post("/StageSolution",{CustomizationFile:t}),e.apiUrl("/StageSolution")).body)===null||i===void 0?void 0:i.StageSolutionResults;try{return Jte(a,n)}finally{await Kte(e,rl(a)?a.StageSolutionUploadId:void 0,r)}}async function Kte(e,t,n){let r;try{r=(0,Ur.normalizeGuid)(t,"StageSolutionUploadId")}catch{n.push(`StageSolution's reply named no usable staging upload id (${nr(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(${r})`;try{let o=await e.delete(i);o.status!==404&&(0,rr.ensureSuccess)(o,e.apiUrl(i))}catch(o){n.push(`The staged copy of the package (stagesolutionupload ${r}) could not be deleted: ${o instanceof Error?o.message:String(o)}. It stays until it is deleted (DELETE ${i}).`)}}function Fr(e,t){return new br.SdkError("SOLUTION_STAGING_UNREADABLE",`${e}: StageSolution's reply could not be read \u2014 ${t}.${e===lp?" Nothing was imported.":""}`)}function F$(e){return!Array.isArray(e)||e.length===0?"none":`${e.slice(0,5).map(n=>rl(n)&&typeof n.Message=="string"?n.Message:nr(n,200)).join("; ")}${e.length>5?` (+${e.length-5} more)`:""}`}function Jte(e,t){if(!rl(e))throw Fr(t,`it holds no StageSolutionResults (${nr(e,60)})`);let n=e.StageSolutionStatus;if(n==="Failed"||n===0)throw new br.SdkError("SOLUTION_STAGING_FAILED",`${t}: the package did not pass StageSolution in this environment (status ${nr(n)}). Missing dependencies: ${F$(e.MissingDependencies)}. Validation: ${F$(e.SolutionValidationResults)}.${t===lp?" Its components cannot be checked against deploymentSettings. Nothing was imported.":" Stage it in the environment it was exported from."}`);if(n!=="Passed"&&n!==1)throw Fr(t,`StageSolutionStatus is ${nr(n)}, neither "Passed" nor "Failed"`);let r=e.SolutionComponentsDetails;if(!Array.isArray(r))throw Fr(t,`SolutionComponentsDetails is not a list (${nr(r,60)})`);let i=[],o=[],a=new Set,s=new Set;return r.forEach((u,l)=>{let c=`SolutionComponentsDetails[${l}]`;if(!rl(u))throw Fr(t,`${c} is not an object`);if(typeof u.ComponentTypeName!="string")throw Fr(t,`${c}.ComponentTypeName is not a string`);let d=u.ComponentTypeName.toLowerCase();if(d!=="environmentvariabledefinition"&&d!=="connectionreference")return;let f=Yte(u.Attributes,`${c}.Attributes`,t),p=(m,h)=>{let g=f.get(m);if(g==null){if(h)throw Fr(t,`${c}.${m} is missing`);return}if(typeof g!="string"||h&&g.length===0)throw Fr(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 Fr(t,`${c}.schemaname '${m}' is listed twice`);a.add(m.toLowerCase());let h=p("defaultvalue",!1),g=Qte(f.get("type"),`${c}.type`,t),y=Xte(f.get("isrequired"),`${c}.isrequired`,t);i.push({SchemaName:m,...h!==void 0?{DefaultValue:h}:{},...g!==void 0?{TypeId:g}:{},...y!==void 0?{IsRequired:y}:{}})}else{let m=p("connectionreferencelogicalname",!0);if(s.has(m.toLowerCase()))throw Fr(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 Yte(e,t,n){if(!rl(e)||!Array.isArray(e.Keys)||!Array.isArray(e.Values))throw Fr(n,`${t} is not { Keys: [...], Values: [...] }`);let{Keys:r,Values:i}=e;if(r.length!==i.length)throw Fr(n,`${t} has ${r.length} keys but ${i.length} values`);let o=new Map;return r.forEach((a,s)=>{if(typeof a!="string")throw Fr(n,`${t}.Keys[${s}] is not a string`);if(o.has(a))throw Fr(n,`${t}.Keys lists '${a}' twice`);o.set(a,i[s])}),o}function Qte(e,t,n){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 Fr(n,`${t} is not a whole number (${nr(e,40)})`)}}function Xte(e,t,n){if(e!=null){if(typeof e=="boolean")return e;if(typeof e=="string"&&/^(true|false)$/i.test(e))return e.toLowerCase()==="true";throw Fr(n,`${t} is not true or false (${nr(e,40)})`)}}var Zte=new Set(["EnvironmentVariables","ConnectionReferences","Workflows","CanvasApps","CopilotAgents","$schema"]),ene=["Workflows","CanvasApps","CopilotAgents"],tne=new Set(["SchemaName","Value","DefaultValue","TypeId","IsRequired","Name"]),nne=new Set(["LogicalName","ConnectionId","ConnectorId"]);function xr(e,t){return new br.InvalidArgumentError(`${lp}: deploymentSettings is not a deployment-settings file this SDK applies \u2014 ${e} ${t}. Nothing was imported.`)}function rne(e){let t="deploymentSettings";if(!rl(e))throw xr(t,`must be an object \u2014 the settings file, parsed (it was ${nr(e,40)})`);for(let u of Object.keys(e))if(!Zte.has(u))throw xr(`${t}.${u}`,"is not part of the format (EnvironmentVariables, ConnectionReferences; Workflows, CanvasApps and CopilotAgents only empty; $schema)");for(let u of ene){let l=e[u];if(l!==void 0&&!(Array.isArray(l)&&l.length===0))throw xr(`${t}.${u}`,"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 xr(`${t}.$schema`,"must be a string");let n=u=>{let l=e[u];if(l===void 0)return[];if(!Array.isArray(l))throw xr(`${t}.${u}`,`must be a list (it was ${nr(l,40)})`);return l.map((c,d)=>{if(!rl(c))throw xr(`${t}.${u}[${d}]`,`must be an object (it was ${nr(c,40)})`);return c})},r=(u,l,c)=>{let d=u[l];if(typeof d!="string"||d.length===0)throw xr(c,`must be a non-empty string (it was ${nr(d,40)})`);if(d.trim()!==d)throw xr(c,`must not begin or end with whitespace (it was ${nr(d,60)})`);return d},i=(u,l,c)=>{if(u.has(l.toLowerCase()))throw xr(c,`names '${l}' a second time (names are case-insensitive)`);u.add(l.toLowerCase())},o={variables:[],references:[]},a=new Set;n("EnvironmentVariables").forEach((u,l)=>{let c=`${t}.EnvironmentVariables[${l}]`;for(let f of Object.keys(u))if(!tne.has(f))throw xr(`${c}.${f}`,"is not part of a variable (SchemaName, Value; DefaultValue, TypeId, IsRequired, Name)");let d=r(u,"SchemaName",`${c}.SchemaName`);if(i(a,d,`${c}.SchemaName`),typeof u.Value!="string")throw xr(`${c}.Value`,`must be a string \u2014 empty to override nothing (it was ${nr(u.Value,40)})`);u.Value.length>0&&o.variables.push({name:d,value:u.Value})});let s=new Set;return n("ConnectionReferences").forEach((u,l)=>{let c=`${t}.ConnectionReferences[${l}]`;for(let p of Object.keys(u))if(!nne.has(p))throw xr(`${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=r(u,"LogicalName",`${c}.LogicalName`);i(s,d,`${c}.LogicalName`);let f=u.ConnectionId;if(typeof f!="string")throw xr(`${c}.ConnectionId`,`must be a string \u2014 empty to bind nothing (it was ${nr(f,40)})`);if(f.trim()!==f)throw xr(`${c}.ConnectionId`,`must not begin or end with whitespace (it was ${nr(f,60)})`);if(u.ConnectorId!==void 0&&typeof u.ConnectorId!="string")throw xr(`${c}.ConnectorId`,`must be a string (it was ${nr(u.ConnectorId,40)})`);f.length>0&&o.references.push({name:d,connectionId:f,...u.ConnectorId?{connectorId:u.ConnectorId}:{}})}),o}function U$(e,t=20){return e.length===0?"none":`${e.slice(0,t).join(", ")}${e.length>t?` (+${e.length-t} more)`:""}`}function ine(e,t){var n;let r=new Map(e.variables.map(u=>[u.SchemaName.toLowerCase(),u])),i=new Map(e.references.map(u=>[u.LogicalName.toLowerCase(),u])),o=[],a=[],s={environmentVariables:[],connectionReferences:[]};for(let u of t.variables){let l=r.get(u.name.toLowerCase());if(!l){o.push(`EnvironmentVariables: '${u.name}' is not a variable of the package`);continue}a.push({"@odata.type":"Microsoft.Dynamics.CRM.environmentvariablevalue",schemaname:l.SchemaName,value:u.value}),s.environmentVariables.push(l.SchemaName)}for(let u of t.references){let l=i.get(u.name.toLowerCase());if(!l){o.push(`ConnectionReferences: '${u.name}' is not a connection reference of the package`);continue}if(u.connectorId!==void 0&&u.connectorId.toLowerCase()!==((n=l.ConnectorId)===null||n===void 0?void 0:n.toLowerCase())){o.push(`ConnectionReferences: '${u.name}' names connector '${u.connectorId}', but the package's reference is for ${l.ConnectorId?`'${l.ConnectorId}'`:"no connector"}`);continue}a.push({"@odata.type":"Microsoft.Dynamics.CRM.connectionreference",connectionreferencelogicalname:l.LogicalName,connectionid:u.connectionId,...l.ConnectorId!==void 0?{connectorid:l.ConnectorId}:{}}),s.connectionReferences.push(l.LogicalName)}if(o.length>0){let u=o.join("; "),l=U$($g(e.variables,d=>d.SchemaName).map(d=>d.SchemaName)),c=U$($g(e.references,d=>d.LogicalName).map(d=>d.LogicalName));throw new br.InvalidArgumentError(`${lp}: deploymentSettings does not match the package \u2014 ${u}. The package's variables: ${l}; its connection references: ${c}. Nothing was imported.`)}return{parameters:a,applied:s}}async function one(e,t){let r=`/solutions(${(0,Ur.normalizeGuid)(t,"solutionId")})`;(0,rr.ensureSuccess)(await e.delete(r),e.apiUrl(r))}me.deleteSolution=one});var zE=C(Mg=>{"use strict";Object.defineProperty(Mg,"__esModule",{value:!0});Mg.OrgReader=void 0;var ane=Ke(),sne=Y(),bt=ae(),une=ia(),tt=Ya(),lne=kg(),ve=Pg(),j$=il(),mt={state:"unreadable"},jE={state:"absent"},ir=e=>({state:"present",value:e});function Xa(e){if(e instanceof sne.PromotionError&&e.code==="PROMOTION_READ_BUDGET_EXCEEDED")throw e}var W$=["Basic","Local","Deep","Global"],WE=class{constructor(t,n,r){this.client=t,this.budget=n,this.codec=r,this.cache=new Map}once(t,n){let r=this.cache.get(t);return r||(r=n(),this.cache.set(t,r)),r}async get(t){return this.client.get(t)}async rows(t,n=Number.MAX_SAFE_INTEGER,r){let i=[],o=new Set,a=await this.get(t);for(let s=0;;s+=1){r?.(s);let u=a.body;if(a.status!==200||!Array.isArray(u?.value))return;i.push(...u?.value);let l=(0,ane.pageEnd)(u);if(l.kind==="end")return i;if(l.kind==="incomplete"||o.has(l.link))return;if(s+1>=n){r?.(s+1);return}o.add(l.link),a=await this.client.getAbsolute(l.link)}}async unique(t){try{let n=await this.rows(t);return!n||n.length>1?mt:n.length===0?jE:ir(n[0])}catch(n){return Xa(n),mt}}async byId(t,n,r){try{let i=await this.get(`/${t}(${n})${(0,bt.odataQuery)([["$select",r]])}`);if(i.status===404)return jE;let o=i.body;return i.status===200&&o&&typeof o=="object"?ir(o):mt}catch(i){return Xa(i),mt}}rootBusinessUnit(){return this.once("rootBu",async()=>{let t=await this.unique(`/businessunits${(0,bt.odataQuery)([["$select","businessunitid"],["$filter","_parentbusinessunitid_value eq null"]])}`);return t.state==="present"?(0,tt.canonicalGuid)(t.value.businessunitid):void 0})}solution(t){return this.once(`solution:${t.toLowerCase()}`,async()=>{let n=(0,ve.columnsOf)(ve.PUBLISHER_FIELDS,(0,ve.ADDRESS_FIELDS)(1),(0,ve.ADDRESS_FIELDS)(2)),r=await this.unique(`/solutions${(0,bt.odataQuery)([["$select",["solutionid","uniquename","version","ismanaged",...(0,ve.columnsOf)(ve.SOLUTION_FIELDS)].join(",")],["$expand",`publisherid($select=${["uniquename","customizationprefix",...n].join(",")})`],["$filter",`uniquename eq '${(0,bt.odataLiteral)(t)}'`]])}`);if(r.state!=="present")return r;let i=r.value,o=i.publisherid,a=(0,tt.canonicalGuid)(i.solutionid),s=(0,ve.projectRow)(i,ve.SOLUTION_FIELDS),u=o?(0,ve.projectRow)(o,ve.PUBLISHER_FIELDS,(0,ve.ADDRESS_FIELDS)(1),(0,ve.ADDRESS_FIELDS)(2)):void 0;return!a||typeof i.version!="string"||typeof i.ismanaged!="boolean"||typeof o?.uniquename!="string"||typeof i["@odata.etag"]!="string"||!s||!u?mt:ir({id:a,version:i.version,managed:i.ismanaged,publisherUniqueName:o.uniquename,publisherPrefix:typeof o.customizationprefix=="string"?o.customizationprefix:"",fields:s,publisherFields:u,etag:i["@odata.etag"]})})}async patches(t){try{let n=await this.rows(`/solutions${(0,bt.odataQuery)([["$select","solutionid"],["$filter",`_parentsolutionid_value eq ${t}`]])}`);return n?.map(r=>{var i;return(i=(0,tt.canonicalGuid)(r.solutionid))!==null&&i!==void 0?i:""}).sort(tt.byCodeUnit)}catch(n){Xa(n);return}}members(t){return this.once(`members:${t}`,async()=>{try{let n=await this.rows(`/solutioncomponents${(0,bt.odataQuery)([["$select","componenttype,objectid"],["$filter",`_solutionid_value eq ${t}`]])}`);if(!n)return;let r=[];for(let i of n){let o=(0,tt.canonicalGuid)(i.objectid);if(!o||typeof i.componenttype!="number")return;r.push({type:i.componenttype,id:o})}return r}catch(n){Xa(n);return}})}componentType(t){return this.once(`componenttype:${t}`,async()=>{try{let n=t==="connectionreference"?await(0,j$.resolveConnectionReferenceComponentType)(this.client):await(0,j$.resolveAppPartComponentType)(this.client,t);return n===void 0?jE:ir(n)}catch(n){return Xa(n),mt}})}async fieldById(t,n,r){let i=await this.byId(t,n,r);if(i.state!=="present")return i;let o=i.value[r];return typeof o=="string"?ir(o):mt}app(t,n){return this.once(`app:${n}:${t}`,async()=>{var r;let i=n?"/appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()":"/appmodules",o=await this.unique(`${i}${(0,bt.odataQuery)([["$select",["appmoduleid","appmoduleidunique","uniquename","webresourceid",...(0,ve.columnsOf)(ve.APP_FIELDS)].join(",")],["$filter",`uniquename eq '${(0,bt.odataLiteral)(t)}'`]])}`);if(o.state!=="present")return o;let a=o.value,s=(0,tt.canonicalGuid)(a.appmoduleid),u=(0,tt.canonicalGuid)(a.appmoduleidunique),l=(0,ve.projectRow)(a,ve.APP_FIELDS);if(!s||!u||!l||typeof a["@odata.etag"]!="string")return mt;try{let c=await this.rows(`/appmodules(${s})/appmoduleroles_association${(0,bt.odataQuery)([["$select","roleid"]])}`),d=await this.rows(`/appmodulecomponents${(0,bt.odataQuery)([["$select","componenttype,objectid"],["$filter",`_appmoduleidunique_value eq ${u}`]])}`),f=await this.appSettings(s,n);if(!c||!d||!f)return mt;let p=c.map(h=>(0,tt.canonicalGuid)(h.roleid)),m=d.map(h=>{let g=(0,tt.canonicalGuid)(h.objectid);return typeof h.componenttype=="number"&&g?`${h.componenttype}:${g}`:void 0});return p.some(h=>!h)||m.some(h=>!h)?mt:ir({id:s,unique:u,fields:l,webResourceId:(r=(0,tt.canonicalGuid)(a.webresourceid))!==null&&r!==void 0?r:null,etag:a["@odata.etag"],roles:p.sort(tt.byCodeUnit),components:m.sort(tt.byCodeUnit),settings:f})}catch(c){return Xa(c),mt}})}async appSettings(t,n){let r=n?"/appsettings/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()":"/appsettings",i=await this.rows(`${r}${(0,bt.odataQuery)([["$select",["appsettingid","value","_settingdefinitionid_value",...(0,ve.columnsOf)(ve.APP_SETTING_FIELDS)].join(",")],["$filter",`_parentappmoduleid_value eq ${t}`]])}`);if(!i)return;let o=[...new Set(i.map(u=>(0,tt.canonicalGuid)(u._settingdefinitionid_value)))];if(o.some(u=>!u))return;let a=new Map;if(o.length>0){let u=await this.rows(`/settingdefinitions${(0,bt.odataQuery)([["$select","settingdefinitionid,uniquename"],["$filter",o.map(l=>`settingdefinitionid eq ${l}`).join(" or ")]])}`);for(let l of u??[]){let c=(0,tt.canonicalGuid)(l.settingdefinitionid);c&&typeof l.uniquename=="string"&&a.set(c,l.uniquename)}}let s=[];for(let u of i){let l=a.get((0,tt.canonicalGuid)(u._settingdefinitionid_value)),c=(0,tt.canonicalGuid)(u.appsettingid),d=(0,ve.projectRow)(u,ve.APP_SETTING_FIELDS);if(!l||!c||!d||typeof u["@odata.etag"]!="string")return;s.push({definition:l,value:typeof u.value=="string"?u.value:"",fields:d,etag:u["@odata.etag"],id:c})}return s.sort((u,l)=>(0,tt.byCodeUnit)(u.definition,l.definition))}settingDefinition(t){return this.once(`settingdefinition:${t}`,async()=>{let n=await this.unique(`/settingdefinitions${(0,bt.odataQuery)([["$select","settingdefinitionid,uniquename"],["$filter",`uniquename eq '${(0,bt.odataLiteral)(t)}'`]])}`);if(n.state!=="present")return n;let r=(0,tt.canonicalGuid)(n.value.settingdefinitionid);return r?ir(r):mt})}sitemap(t,n){return this.once(`sitemap:${n}:${t}`,async()=>{let r=n?"/sitemaps/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()":"/sitemaps",i=await this.unique(`${r}${(0,bt.odataQuery)([["$select",["sitemapid","sitemapnameunique","sitemapxml",...(0,ve.columnsOf)(ve.SITEMAP_FIELDS)].join(",")],["$filter",`sitemapnameunique eq '${(0,bt.odataLiteral)(t)}'`]])}`);if(i.state!=="present")return i;let o=(0,tt.canonicalGuid)(i.value.sitemapid),a=i.value.sitemapxml,s=typeof a=="string"?(0,lne.canonicalSitemapText)(a):void 0,u=(0,ve.projectRow)(i.value,ve.SITEMAP_FIELDS);return!o||!s||!u||typeof i.value["@odata.etag"]!="string"?mt:ir({id:o,canonical:s,fields:u,etag:i.value["@odata.etag"]})})}webResource(t){return this.once(`webresource:${t}`,async()=>{let n=await this.unique(`/webresourceset${(0,bt.odataQuery)([["$select",["webresourceid","name","webresourcetype","content",...(0,ve.columnsOf)(ve.WEB_RESOURCE_FIELDS)].join(",")],["$filter",`name eq '${(0,bt.odataLiteral)(t)}'`]])}`);if(n.state!=="present")return n;let r=n.value,i=(0,tt.canonicalGuid)(r.webresourceid),o=(0,ve.projectRow)(r,ve.WEB_RESOURCE_FIELDS);if(!i||!o||typeof r.webresourcetype!="number"||typeof r["@odata.etag"]!="string")return mt;let a=typeof r.content=="string"?r.content:"";return ir({id:i,type:r.webresourcetype,sha256:await(0,tt.sha256Of)(this.codec,(0,une.base64ToBytes)(a)),fields:o,etag:r["@odata.etag"]})})}variable(t){return this.once(`variable:${t}`,async()=>{let n=await this.unique(`/environmentvariabledefinitions${(0,bt.odataQuery)([["$select",["environmentvariabledefinitionid","schemaname","type","isrequired","defaultvalue",...(0,ve.columnsOf)(ve.VARIABLE_FIELDS)].join(",")],["$filter",`schemaname eq '${(0,bt.odataLiteral)(t)}'`]])}`);if(n.state!=="present")return n;let r=n.value,i=(0,tt.canonicalGuid)(r.environmentvariabledefinitionid),o=(0,ve.projectRow)(r,ve.VARIABLE_FIELDS);if(!i||!o||typeof r.type!="number"||typeof r["@odata.etag"]!="string")return mt;try{let a=await this.rows(`/environmentvariablevalues${(0,bt.odataQuery)([["$select","environmentvariablevalueid,value"],["$filter",`_environmentvariabledefinitionid_value eq ${i}`]])}`);if(!a)return mt;let s=[];for(let u of a){let l=(0,tt.canonicalGuid)(u.environmentvariablevalueid);if(!l||typeof u["@odata.etag"]!="string")return mt;s.push({id:l,valueDigest:await(0,tt.digestOf)(this.codec,typeof u.value=="string"?u.value:null),etag:u["@odata.etag"]})}return ir({id:i,type:r.type,isRequired:r.isrequired===!0,defaultValue:typeof r.defaultvalue=="string"?r.defaultvalue:null,fields:o,etag:r["@odata.etag"],values:s.sort((u,l)=>(0,tt.byCodeUnit)(u.id,l.id))})}catch(a){return Xa(a),mt}})}reference(t){return this.once(`reference:${t}`,async()=>{let n=await this.unique(`/connectionreferences${(0,bt.odataQuery)([["$select",["connectionreferenceid","connectionreferencelogicalname","connectorid","connectionid",...(0,ve.columnsOf)(ve.REFERENCE_FIELDS)].join(",")],["$filter",`connectionreferencelogicalname eq '${(0,bt.odataLiteral)(t)}'`]])}`);if(n.state!=="present")return n;let r=n.value,i=(0,tt.canonicalGuid)(r.connectionreferenceid),o=(0,ve.projectRow)(r,ve.REFERENCE_FIELDS);return!i||!o||typeof r["@odata.etag"]!="string"?mt:ir({id:i,connectorId:typeof r.connectorid=="string"?r.connectorid:null,connectionId:typeof r.connectionid=="string"?r.connectionid:null,fields:o,etag:r["@odata.etag"]})})}role(t){return this.once(`role:${t}`,async()=>{var n,r;let i=await this.byId("roles",t,["roleid","name","_businessunitid_value","_roletemplateid_value",...(0,ve.columnsOf)(ve.ROLE_FIELDS)].join(","));if(i.state!=="present")return i;let o=i.value,a=(0,ve.projectRow)(o,ve.ROLE_FIELDS);return!a||typeof o["@odata.etag"]!="string"?mt:ir({id:t,name:typeof o.name=="string"?o.name:null,businessUnitId:(n=(0,tt.canonicalGuid)(o._businessunitid_value))!==null&&n!==void 0?n:null,templateId:(r=(0,tt.canonicalGuid)(o._roletemplateid_value))!==null&&r!==void 0?r:null,fields:a,etag:o["@odata.etag"]})})}rolePrivileges(t){return this.once(`privileges:${t}`,async()=>{var n;try{let r=await this.get(`/RetrieveRolePrivilegesRole(RoleId=${t})`),i=(n=r.body)===null||n===void 0?void 0:n.RolePrivileges;if(r.status!==200||!Array.isArray(i))return;let o=[];for(let a of i){let s=typeof a?.Depth=="number"?W$[a.Depth]:typeof a?.Depth=="string"?a.Depth:void 0;if(typeof a?.PrivilegeName!="string"||!s||!W$.includes(s))return;o.push(`${a.PrivilegeName}:${s}`)}return[...new Set(o)].sort(tt.byCodeUnit)}catch(r){Xa(r);return}})}templateRole(t){return this.once(`template:${t}`,async()=>{let n=await this.rootBusinessUnit();if(!n)return mt;let r=await this.unique(`/roles${(0,bt.odataQuery)([["$select","roleid"],["$filter",`_roletemplateid_value eq ${t} and _businessunitid_value eq ${n}`]])}`);if(r.state!=="present")return r;let i=(0,tt.canonicalGuid)(r.value.roleid);return i?ir(i):mt})}webResourceName(t){return this.once(`webresourcename:${t}`,()=>this.fieldById("webresourceset",t,"name"))}search(t){return this.once(`search:${t}`,async()=>{let n=await this.byId("dvtablesearchs",t,["dvtablesearchid",...(0,ve.columnsOf)(ve.SEARCH_FIELDS)].join(","));if(n.state!=="present")return n;let r=(0,ve.projectRow)(n.value,ve.SEARCH_FIELDS),i=n.value["@odata.etag"];return r&&typeof i=="string"?ir({id:t,fields:r,etag:i}):mt})}tableExists(t){return this.once(`table:${t}`,async()=>{let n=await this.byId("EntityDefinitions",`LogicalName='${(0,bt.odataLiteral)(t)}'`,"LogicalName");return n.state!=="present"?n:typeof n.value.LogicalName=="string"?ir(!0):mt})}async topLayer(t,n){this.budget.layerLookups+=1;try{let r=0,i=await this.rows(`/msdyn_componentlayers${(0,bt.odataQuery)([["$select","msdyn_order,msdyn_solutionname"],["$filter",`(msdyn_componentid eq '${n}' and msdyn_solutioncomponentname eq '${(0,bt.odataLiteral)(t)}')`]])}`,this.budget.limits.maxLayerPagesPerComponent,()=>{this.budget.spendLayerPage(r),r+=1});if(!i||i.length===0)return mt;let o=i.map(a=>{var s;return{order:Number(a.msdyn_order),name:String((s=a.msdyn_solutionname)!==null&&s!==void 0?s:"")}}).sort((a,s)=>s.order-a.order);return o.some(a=>!Number.isFinite(a.order))?mt:ir({top:o[0].name,digest:await(0,tt.digestOf)(this.codec,o.map(a=>[a.order,a.name]))})}catch(r){return Xa(r),mt}}async variableExists(t){let n=await this.variable(t);return n.state==="present"?ir(!0):n}};Mg.OrgReader=WE});var cp=C(kt=>{"use strict";Object.defineProperty(kt,"__esModule",{value:!0});kt.environmentVariablePushIssues=kt.environmentVariableShapeIssues=kt.environmentVariableMutationIssues=kt.requiredStringOrNull=kt.rowBagIssues=kt.valueTypeProblem=kt.isGuidText=kt.ENVIRONMENT_VARIABLE_BAG_COLUMNS=kt.ENVIRONMENT_VARIABLE_TYPES=void 0;kt.ENVIRONMENT_VARIABLE_TYPES=["string","number","boolean","json","dataSource","secret"];kt.ENVIRONMENT_VARIABLE_BAG_COLUMNS=["hint","learnmoreurl","inputcontrolconfig"];function cne(e){return/^-?\d+$/.test(e)||/^-?\d+\.\d+$/.test(e)||/^-?\.\d+$/.test(e)}var dne=/^\{?[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 yn(e,t,n){return{pointer:e,rule:t,message:n}}function KE(e){return typeof e=="string"&&dne.test(e)&&e.startsWith("{")===e.endsWith("}")}kt.isGuidText=KE;function H$(e,t){switch(e){case"number":return cne(t)?void 0:"is not a decimal number: write digits with an optional leading '-' and an optional '.' fraction, e.g. 42 or -1.5 (no exponent, no hex)";case"boolean":return t==="yes"||t==="no"?void 0:"is not a Boolean value: write 'yes' or 'no' (lower case, the platform's own form)";case"json":try{JSON.parse(t);return}catch{return"is not JSON text: it does not parse"}default:return}}kt.valueTypeProblem=H$;function Fg(e,t,n,r){if(typeof t!="string")return[];if(t==="")return[yn(n,"empty-string",`${r} is the empty string, which the platform stores as no value: use null for none`+(n==="/defaultValue"?"":", or set /currentValue to null to remove the value"))];if(!kt.ENVIRONMENT_VARIABLE_TYPES.includes(e))return[];let i=H$(e,t);return i===void 0?[]:[yn(n,"value-type",`${r} ${i} (type '${String(e)}')`)]}function K$(e,t){if(e===void 0)return[];let n=e?.a;if(!Array.isArray(n))return[yn("/bag","bag-column","bag must be { a: [[column, value], \u2026] }")];let r=[],i=new Set;return n.forEach((o,a)=>{let s=Array.isArray(o)&&o.length===2?o[0]:void 0;if(typeof s!="string"||!t.includes(s)||i.has(s)){r.push(yn(`/bag/a/${a}`,"bag-column",`a bag entry must be a [column, value] pair naming one of ${t.join(", ")}, each at most once (a typed field is edited through its own property)`));return}i.add(s)}),r}kt.rowBagIssues=K$;function xg(e,t){return e==null||typeof e=="string"?[]:[yn(t,"type","must be a string or null")]}function HE(e,t,n="a string"){return e===void 0?[yn(t,"required",`must be present: ${n}, or null for none (to clear it, set it to null \u2014 removing it is refused)`)]:e===null||typeof e=="string"?[]:[yn(t,"type",`must be ${n} or null`)]}kt.requiredStringOrNull=HE;function z$(e,t){return e==null||KE(e)?[]:[yn(t,"guid","must be a GUID or null")]}function J$(e){let t=e,n=[];KE(t.id)||n.push(yn("/id","guid","must be a GUID")),(typeof t.schemaName!="string"||t.schemaName.trim()==="")&&n.push(yn("/schemaName","required","must be a non-empty string")),typeof t.name!="string"&&n.push(yn("/name","type","must be a string")),n.push(...HE(t.description,"/description")),kt.ENVIRONMENT_VARIABLE_TYPES.includes(t.type)||n.push(yn("/type","type",`must be one of ${kt.ENVIRONMENT_VARIABLE_TYPES.join(", ")}`)),n.push(...HE(t.defaultValue,"/defaultValue"));let r=t.currentValue;if(r!==null&&(typeof r!="object"||Array.isArray(r)))n.push(yn("/currentValue","type","must be { value } or null"));else if(r!==null){let i=r;n.push(...xg(i.value,"/currentValue/value")),i.value===void 0&&n.push(yn("/currentValue/value","required","must be present (a string)")),i.id!==void 0&&n.push(...z$(i.id,"/currentValue/id"))}return typeof t.isRequired!="boolean"&&n.push(yn("/isRequired","type","must be true or false")),n.push(...xg(t.valueSchema,"/valueSchema")),n.push(...xg(t.connectorId,"/connectorId")),n.push(...xg(t.parameterKey,"/parameterKey")),n.push(...z$(t.parentId,"/parentId")),n.push(...K$(t.bag,kt.ENVIRONMENT_VARIABLE_BAG_COLUMNS)),n}function fne(e,t){var n;let r=J$(e);return t==="/defaultValue"?r.push(...Fg(e.type,e.defaultValue,"/defaultValue","defaultValue")):(t==="/currentValue"||t==="/currentValue/value")&&r.push(...Fg(e.type,(n=e.currentValue)===null||n===void 0?void 0:n.value,"/currentValue/value","currentValue.value")),r}kt.environmentVariableMutationIssues=fne;function pne(e){return J$(e)}kt.environmentVariableShapeIssues=pne;function mne(e,t){var n,r,i;let o=[];if(t){e.type!==t.type&&o.push(yn("/type","immutable-after-create","type is fixed once the variable exists (the platform ignores a change)")),e.schemaName!==t.schemaName&&o.push(yn("/schemaName","immutable-after-create","schemaName is fixed once the variable exists (the platform ignores a change)"));let u=(n=t.currentValue)===null||n===void 0?void 0:n.id,l=(r=e.currentValue)===null||r===void 0?void 0:r.id;u!==void 0&&l!==void 0&&l.toLowerCase()!==u.toLowerCase()&&o.push(yn("/currentValue/id","immutable-after-create","the value row's id is fixed: omit it (the SDK keeps the existing row's), or set /currentValue to null to delete the row"))}(!t||e.defaultValue!==t.defaultValue)&&o.push(...Fg(e.type,e.defaultValue,"/defaultValue","defaultValue"));let a=e.currentValue,s=(i=t?.currentValue)!==null&&i!==void 0?i:null;return a&&(a.value===null?(s===null||s.value!==null)&&o.push(yn("/currentValue/value","value-required","a value row needs a value: to remove the value, set /currentValue to null")):(s===null||a.value!==s.value)&&o.push(...Fg(e.type,a.value,"/currentValue/value","currentValue.value"))),e.parentId!=null&&e.type!=="dataSource"&&o.push(yn("/parentId","parent-not-data-source","parentId is accepted only on a 'dataSource' variable (and must name another 'dataSource' variable)")),o}kt.environmentVariablePushIssues=mne});var QE=C(ot=>{"use strict";Object.defineProperty(ot,"__esModule",{value:!0});ot.ROW_SUMMARY_TEMPLATE_NOT_FOUND_CODE=ot.ROW_SUMMARY_REMOVAL_UNCONFIRMED_CODE=ot.ROW_SUMMARY_MODEL_NOT_DELETED_CODE=ot.removeRowSummary=ot.configureRowSummary=ot.buildGptDynamicPrompt=ot.setAppAiFeatures=ot.getAiReadiness=ot.saveSettingValue=ot.retrieveSetting=ot.AI_GATE=void 0;var fi=Ke(),Ji=pe(),$t=ae(),Y$=ft(),st=Y(),dp="answered no row but says more rows exist, so it proves no absence";ot.AI_GATE={formFill:"FormFillBarUXEnabled",formFillSuggestions:"FormPredictEnabled",formFillSmartPaste:"FormPredictSmartPasteEnabled",formFillFiles:"FormFillFileUploadEnabled",nlSearch:"EnableNLGridSearch",nlChart:"NLChartVisualizationSetting",summaries:"EnableFormInsights",m365:"m365copilotmodelappenabled"};var nL={formFill:"FormFillBarUXEnabled",formFillSuggestions:"FormPredictEnabled",formFillSmartPaste:"FormPredictSmartPasteEnabledOnByDefault",formFillFiles:"FormFillFileUploadEnabled",nlSearch:"NLGridSearchSetting",nlChart:"NLChartDataVisualizationSetting",m365:"m365copilotmodelappenabled"},hne=new Set(Object.entries(ot.AI_GATE).filter(([e,t])=>nL[e]===t).map(([e])=>e)),gne={formFill:{enabled:"2",disabled:"1"},formFillSuggestions:{enabled:"2",disabled:"1"},formFillSmartPaste:{enabled:"2",disabled:"1"},formFillFiles:{enabled:"2",disabled:"1"}};function JE(e){return gne[e]}var Ug=1e6;function yne(e,t){let n=JE(t),r=()=>{throw new st.InvalidArgumentError(`setAppAiFeatures: '${t}' must be a boolean or an integer between 0 and ${Ug} (e.g. 0, 1, 2); got '${String(e)}'.`)},i=o=>n?o?n.enabled:n.disabled:o?"1":"0";if(typeof e=="boolean")return i(e);if(typeof e=="number")return!Number.isSafeInteger(e)||e<0||e>Ug?r():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(Ug).length||Number(s)>Ug?r():s}}return r()}function bne(e,t){let n=JE(t);return n?e===n.enabled:e!=="0"}async function vne(e,t){var n,r;let i=`/appmodules${(0,$t.odataQuery)([["$select","appmoduleid"],["$filter",`uniquename eq '${(0,$t.odataLiteral)(t)}'`]])}`,o=await e.get(i);if(o.status<200||o.status>=300)return;let a=(n=o.body)===null||n===void 0?void 0:n.value;if(!Array.isArray(a))throw new st.ConnectionError(e.apiUrl(i),o.status,`the app lookup for '${t}' returned a malformed answer \u2014 expected an OData 'value' array but got ${(0,fi.describeMalformedValue)(a)}`);if(!(0,fi.boundedPageComplete)(o.body,a.length))throw new st.ConnectionError(e.apiUrl(i),o.status,`the app lookup for '${t}' ${dp}`);return(r=a[0])===null||r===void 0?void 0:r.appmoduleid}async function wne(e,t){var n,r;let i=`/appmodules${(0,$t.odataQuery)([["$select","appmoduleid"],["$filter",`uniquename eq '${(0,$t.odataLiteral)(t)}'`]])}`,o;try{o=await e.get(i)}catch(u){throw new st.InvalidArgumentError(`setAppAiFeatures: cannot confirm that the supplied appModuleId belongs to app '${t}' \u2014 the lookup failed (${u.message}). Retry, or omit appModuleId to verify by name.`)}if(o.status<200||o.status>=300)throw new st.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=(n=o.body)===null||n===void 0?void 0:n.value;if(!Array.isArray(a))throw new st.InvalidArgumentError(`setAppAiFeatures: cannot confirm that the supplied appModuleId belongs to app '${t}' \u2014 the lookup returned a malformed body.`);if(!(0,fi.boundedPageComplete)(o.body,a.length))throw new st.InvalidArgumentError(`setAppAiFeatures: cannot confirm that the supplied appModuleId belongs to app '${t}' \u2014 the lookup ${dp}.`);if(a.length===0)return;let s=(r=a[0])===null||r===void 0?void 0:r.appmoduleid;if(!s)throw new st.InvalidArgumentError(`setAppAiFeatures: cannot confirm that the supplied appModuleId belongs to app '${t}' \u2014 the lookup returned a row with no appmoduleid.`);return s}var Q$=new WeakMap;async function Ene(e,t){var n,r;let i=Q$.get(e);if(i||(i=new Map,Q$.set(e,i)),i.has(t))return i.get(t);let o=`/settingdefinitions${(0,$t.odataQuery)([["$select","settingdefinitionid"],["$filter",`uniquename eq '${(0,$t.odataLiteral)(t)}'`]])}`,a=await e.get(o);if(a.status<200||a.status>=300)return;let s=(n=a.body)===null||n===void 0?void 0:n.value;if(!Array.isArray(s))throw new st.ConnectionError(e.apiUrl(o),a.status,`the setting definition lookup returned a malformed answer \u2014 expected an OData 'value' array but got ${(0,fi.describeMalformedValue)(s)}`);if(!(0,fi.boundedPageComplete)(a.body,s.length))throw new st.ConnectionError(e.apiUrl(o),a.status,`the setting definition lookup ${dp}`);let u=(r=s[0])===null||r===void 0?void 0:r.settingdefinitionid;return u&&i.set(t,u),u}async function Ane(e,t,n){var r;let i=await Ene(e,n);if(!t||!i)return;let o=`/appsettings/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()${(0,$t.odataQuery)([["$select","value,componentstate"],["$filter",`_parentappmoduleid_value eq ${t} and _settingdefinitionid_value eq ${i}`]])}`,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 st.ConnectionError(e.apiUrl(o),a.status,`the app-scope override read returned a malformed answer \u2014 expected an OData 'value' array but got ${(0,fi.describeMalformedValue)(s)}`);let u=s,l=u.find(d=>d?.componentstate===1);if(!l&&(0,fi.pageEnd)(a.body).kind!=="end")throw new st.ConnectionError(e.apiUrl(o),a.status,u.length===0?`the app-scope override read ${dp}`:"the app-scope override read answered no authored row but says more rows exist, so it proves no value");if(u.length===0)return{exists:!1};let c=l??u[0];return{exists:!0,value:c.value,pendingPublish:c.componentstate===1}}var Cne=4,Sne=500,X$=20,Z$=3e4;function Nne(e){if(e===void 0)return Cne;if(!Number.isFinite(e))throw new st.InvalidArgumentError(`setAppAiFeatures: verifyAttempts must be a finite integer between 1 and ${X$}; got ${e}.`);return Math.min(X$,Math.max(1,Math.floor(e)))}function _ne(e){if(e===void 0)return Sne;if(!Number.isFinite(e))throw new st.InvalidArgumentError(`setAppAiFeatures: verifyDelayMs must be a finite number between 0 and ${Z$}; got ${e}.`);return Math.min(Z$,Math.max(0,Math.floor(e)))}async function Ine(e,t,n,r,i,o,a){let s,u,l,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 Ane(e,p,r),f===void 0&&(l="the app-scope override row could not be read (insufficient access or unresolvable ids)")):l=`the app '${n}' 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,l=p.message}c=f!==void 0,u=f?.exists;try{s=(await qg(e,r,{appUniqueName:n})).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:u}:{result:"unverifiable",effectiveValue:s,appOverrideExists:void 0,reason:l}}function rL(e,t,n){if(t===2)return String(e).toLowerCase()==="true";let r=n?JE(n):void 0;return r?e===r.enabled:e!=null&&e!=="0"&&e!==""}async function qg(e,t,n={}){var r;let i=[`SettingName='${(0,$t.odataPathLiteral)(t)}'`];n.appUniqueName&&i.push(`AppUniqueName='${(0,$t.odataPathLiteral)(n.appUniqueName)}'`);let o=`/RetrieveSetting(${i.join(",")})`,a=(0,Ji.ensureSuccess)(await e.get(o),e.apiUrl(o)),s=(r=a.body)===null||r===void 0?void 0:r.SettingDetail;if(s===null||typeof s!="object"||Array.isArray(s)||!("Value"in s))throw new st.ConnectionError(e.apiUrl(o),a.status,`RetrieveSetting for '${t}' returned a malformed answer \u2014 expected a SettingDetail with a Value`);let{Value:u,DataType:l}=s;return{value:u,dataType:l}}ot.retrieveSetting=qg;async function iL(e,t,n,r={}){let i={SettingName:t,Value:n};r.appUniqueName&&(i.AppUniqueName=r.appUniqueName),r.solutionUniqueName&&(i.SolutionUniqueName=r.solutionUniqueName),(0,Ji.ensureSuccess)(await e.post("/SaveSettingValue",i),e.apiUrl("/SaveSettingValue"))}ot.saveSettingValue=iL;async function Tne(e,t={}){let n={};for(let[r,i]of Object.entries(ot.AI_GATE)){let{value:o,dataType:a}=await qg(e,i,t);n[r]={enabled:rL(o,a,r),setting:i,value:o}}return n}ot.getAiReadiness=Tne;async function One(e,t,n,r={}){var i;if(!t||!t.trim())throw new st.InvalidArgumentError("setAppAiFeatures: a non-empty appUniqueName is required (an empty value would write the setting at organization scope, affecting every app).");let o=Nne(r.verifyAttempts),a=_ne(r.verifyDelayMs),s=[];for(let[m,h]of Object.entries(n)){if(h===void 0)continue;let g=nL[m];g&&s.push({feature:m,setting:g,requestedValue:yne(h,m)})}let u=[],l=r.appModuleId?(0,$t.normalizeGuid)(r.appModuleId,"appModuleId"):void 0;if(l){let m=await wne(e,t);if(m&&(0,$t.normalizeGuid)(m,"appModuleId")!==l)throw new st.InvalidArgumentError(`setAppAiFeatures: appModuleId '${l}' does not belong to app '${t}' (which resolves to '${m}'). 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()=>l||(c||(c=await vne(e,t)),c),f=new Map,p=async m=>{if(hne.has(m))return;let h=ot.AI_GATE[m];if(h){if(!f.has(h))try{let{value:g,dataType:y}=await qg(e,h);f.set(h,{enabled:rL(g,y,m),setting:h,value:g})}catch{f.set(h,void 0)}return f.get(h)}};for(let{feature:m,setting:h,requestedValue:g}of s)try{await iL(e,h,g,{appUniqueName:t,solutionUniqueName:r.solutionUniqueName});let y=await Ine(e,d,t,h,g,o,a),b={feature:m,setting:h,requestedValue:g,effectiveValue:y.effectiveValue,appOverrideExists:y.appOverrideExists};if(y.result==="proven")u.push({...b,status:"applied",...y.pendingPublish?{pendingPublish:!0}:{}});else if(y.result==="absent"){let E=bne(g,m)?await p(m):void 0;E&&!E.enabled?u.push({...b,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 '${E.setting}' reads '${E.value}', so an environment admin must enable it before this app can turn the feature on`}):u.push({...b,status:"notPersisted",reason:`the write reported success but no app-scope override holding '${g}' was observed for '${h}' after ${o} attempt(s) \u2014 ${y.effectiveValue===void 0?"the value in effect for this app could not be read":`it reads '${y.effectiveValue}' for this app`} (Dataverse can accept an app-scope write without storing it)`})}else u.push({...b,status:"unverified",reason:`the write was issued but could not be confirmed: ${(i=y.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(y){u.push({feature:m,setting:h,requestedValue:g,status:"failed",reason:y.message})}return{applied:u.filter(m=>m.status==="applied").map(m=>m.feature),skipped:u.filter(m=>m.status==="skipped").map(m=>m.feature),notPersisted:u.filter(m=>m.status==="notPersisted").map(m=>m.feature),unverified:u.filter(m=>m.status==="unverified").map(m=>m.feature),failed:u.filter(m=>m.status==="failed").map(m=>m.feature),outcomes:u}}ot.setAppAiFeatures=One;var oL="GptPowerPrompt",Dne='{ "consumptionSource": "Api", "partnerSource": "AIBuilder", "consumptionSourceVersion": "GptApiClient"}';function aL(e){var t,n,r,i;let o=e.entityLogicalName,a=[{type:"literal",text:e.instruction.replace(/\s*$/,"")+" "}];return e.columns.forEach((s,u)=>{a.push({type:"data",id:`${o}.${s.logical}`,text:s.display}),u<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:(n=e.temperature)!==null&&n!==void 0?n:0}},settings:{recordRetrievalLimit:(r=e.recordRetrievalLimit)!==null&&r!==void 0?r:30,shouldPreserveRecordLinks:null,runtime:null,enableReasoning:(i=e.enableReasoning)!==null&&i!==void 0?i:!0},code:"",signature:""}}ot.buildGptDynamicPrompt=aL;async function Pne(e,t){var n;let r=`/EntityDefinitions(LogicalName='${(0,$t.odataPathLiteral)(t)}')${(0,$t.odataQuery)([["$select","MetadataId"]])}`,i=(0,Ji.ensureSuccess)(await e.get(r),e.apiUrl(r)),o=(n=i.body)===null||n===void 0?void 0:n.MetadataId;if(typeof o!="string"||o==="")throw new st.ConnectionError(e.apiUrl(r),i.status,`the table metadata read for '${t}' returned a malformed answer \u2014 expected a MetadataId but got ${o===""?"an empty string":(0,fi.describeMalformedValue)(o)}`);return o}function YE(e,t,n,r,i){if(e.length===0){if(!(0,fi.boundedPageComplete)(i,0))throw new st.ConnectionError(t,n,`${r} ${dp}`);return}let o=e[0];if(typeof o!="object"||o===null||Array.isArray(o))throw new st.ConnectionError(t,n,`${r} returned a malformed row \u2014 expected an object but got ${Array.isArray(o)?"an array":(0,fi.describeMalformedValue)(o)}`);return o}async function sL(e){var t;let n=`/msdyn_aitemplates${(0,$t.odataQuery)([["$select","msdyn_aitemplateid"],["$filter",`msdyn_uniquename eq '${oL}'`],["$top",1]])}`,r=(0,Ji.ensureSuccess)(await e.get(n),e.apiUrl(n)),i=(t=r.body)===null||t===void 0?void 0:t.value;if(!Array.isArray(i))throw new st.ConnectionError(e.apiUrl(n),r.status,`the row-summary template lookup returned a malformed answer \u2014 expected an OData 'value' array but got ${(0,fi.describeMalformedValue)(i)}`);let o=YE(i,e.apiUrl(n),r.status,"the row-summary template lookup",r.body);if(!o)return;let a=o.msdyn_aitemplateid;if(typeof a=="string"&&a!=="")try{return(0,$t.normalizeGuid)(a,"msdyn_aitemplateid")}catch{}throw new st.ConnectionError(e.apiUrl(n),r.status,`the row-summary template lookup returned a malformed row \u2014 expected a GUID 'msdyn_aitemplateid' but got ${a===""?"an empty string":typeof a=="string"?"a string that is not a GUID":(0,fi.describeMalformedValue)(a)}`)}function uL(e){return`${e} row summary`}async function Rne(e,t,n){var r;let i=`/msdyn_aimodels(${t})${(0,$t.odataQuery)([["$select","msdyn_name,_msdyn_templateid_value"]])}`,o=await e.get(i);if(o.status===404)return!1;let a=(r=(0,Ji.ensureSuccess)(o,e.apiUrl(i)).body)!==null&&r!==void 0?r:{},s=await sL(e);return typeof a.msdyn_name=="string"&&a.msdyn_name.toLowerCase()===uL(n).toLowerCase()&&typeof a._msdyn_templateid_value=="string"&&s!==void 0&&a._msdyn_templateid_value.toLowerCase()===s.toLowerCase()}async function kne(e,t,n={}){var r;let i=`ais_RowSummary_${t.entityLogicalName}`,o=`/aiskillconfigs${(0,$t.odataQuery)([["$select","aiskillconfigid,_aimodel_value"],["$filter",`uniquename eq '${(0,$t.odataLiteral)(i)}'`],["$top",1]])}`,a=(0,Ji.ensureSuccess)(await e.get(o),e.apiUrl(o)),s=(r=a.body)===null||r===void 0?void 0:r.value;if(!Array.isArray(s))throw new st.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,fi.describeMalformedValue)(s)}`);let u=YE(s,e.apiUrl(o),a.status,"the existing row-summary skill lookup",a.body);if(u)return{modelId:u._aimodel_value,aiSkillConfigId:u.aiskillconfigid};let l=await Pne(e,t.entityLogicalName),c=await sL(e);if(c===void 0)throw new st.SdkError(ot.ROW_SUMMARY_TEMPLATE_NOT_FOUND_CODE,`Cannot configure the row summary of '${t.entityLogicalName}': this org has no AI template '${oL}' (msdyn_aitemplates), which a row-summary model is built from. Nothing was written.`);let d=(0,Y$.newId)(),f=(0,Y$.newId)(),p=JSON.stringify(aL(t)),m={ModelId:d,RunConfigurationId:f,ModelName:uL(t.entityLogicalName),TemplateId:c,CustomConfiguration:p,Source:Dne,RunConfiguration:""};(0,Ji.ensureSuccess)(await e.post("/AIModelPublish",m),e.apiUrl("/AIModelPublish"));try{let h={uniquename:i,description:`${t.entityLogicalName} row summary`,"[email protected]":`/entities(${l})`,"[email protected]":`/msdyn_aimodels(${d})`,aiskill:"RowSummary"},g=(0,Ji.ensureSuccess)(await e.post("/aiskillconfigs",h),e.apiUrl("/aiskillconfigs")),y=(0,Ji.requireCreatedId)(g,"aiskillconfigid","row-summary skill");return{modelId:d,aiSkillConfigId:y}}catch(h){try{await e.delete(`/msdyn_aimodels(${d})`)}catch{}throw h}}ot.configureRowSummary=kne;async function $ne(e,t){var n;let r=`ais_RowSummary_${t.entityLogicalName}`,i=`/aiskillconfigs${(0,$t.odataQuery)([["$select","aiskillconfigid,_aimodel_value"],["$filter",`uniquename eq '${(0,$t.odataLiteral)(r)}'`],["$top",1]])}`,o=(0,Ji.ensureSuccess)(await e.get(i),e.apiUrl(i)),a=(n=o.body)===null||n===void 0?void 0:n.value;if(!Array.isArray(a))throw new st.ConnectionError(e.apiUrl(i),o.status,`the row-summary skill lookup returned a malformed answer \u2014 expected an OData 'value' array but got ${(0,fi.describeMalformedValue)(a)}`);let s=YE(a,e.apiUrl(i),o.status,"the row-summary skill lookup",o.body);if(!s)return{removed:!1};let u=(0,$t.normalizeGuid)(s.aiskillconfigid,"aiskillconfigid"),l=s._aimodel_value?(0,$t.normalizeGuid)(s._aimodel_value,"_aimodel_value"):void 0,c=l?await Rne(e,l,t.entityLogicalName):!1,d=t.entityLogicalName,f=`/aiskillconfigs(${u})`,p=await eL(e,f,`${f}${(0,$t.odataQuery)([["$select","aiskillconfigid"]])}`);if(p.kind==="failed")throw p.stillThere===void 0&&l&&c?(0,st.attachCause)(new st.SdkError(ot.ROW_SUMMARY_REMOVAL_UNCONFIRMED_CODE,`Removing the row summary of '${d}' could not be confirmed: deleting its skill row failed (${tL(p.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.`),p.failure):p.failure;if(l&&c){let m=`/msdyn_aimodels(${l})`,h=await eL(e,m,`${m}${(0,$t.odataQuery)([["$select","msdyn_aimodelid"]])}`,Mne);if(h.kind==="failed")throw(0,st.attachCause)(new st.SdkError(ot.ROW_SUMMARY_MODEL_NOT_DELETED_CODE,`The row summary of '${d}' was removed, but its AI model '${l}' ${h.stillThere?"was not deleted":"could not be confirmed deleted"} (${tL(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)}return{removed:!0}}ot.removeRowSummary=$ne;ot.ROW_SUMMARY_MODEL_NOT_DELETED_CODE="ROW_SUMMARY_MODEL_NOT_DELETED";ot.ROW_SUMMARY_REMOVAL_UNCONFIRMED_CODE="ROW_SUMMARY_REMOVAL_UNCONFIRMED";ot.ROW_SUMMARY_TEMPLATE_NOT_FOUND_CODE="ROW_SUMMARY_TEMPLATE_NOT_FOUND";var Lne="0x8004f01f";function Mne(e){var t,n;let r=(n=(t=e.body)===null||t===void 0?void 0:t.error)===null||n===void 0?void 0:n.code;return e.status===400&&typeof r=="string"&&r.toLowerCase()===Lne}function xne(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 eL(e,t,n,r=()=>!1){let i;try{let o=await(0,Ji.resendWhile)(xne,()=>e.delete(t));if(o.status>=200&&o.status<300||o.status===404)return{kind:"gone"};if(r(o))return{kind:"kept"};try{(0,Ji.ensureSuccess)(o,e.apiUrl(t))}catch(a){i=a}}catch(o){i=o}try{let o=await e.get(n);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 tL(e){return e instanceof Error?e.message:String(e)}});var ZE=C(Yi=>{"use strict";Object.defineProperty(Yi,"__esModule",{value:!0});Yi.readWebResourceByName=Yi.deleteWebResource=Yi.getWebResource=Yi.updateWebResource=Yi.createWebResource=void 0;var lL=Ke(),Fne=mo(),Qs=pe(),Ys=ae(),XE=ia(),Za=Y(),Une={html:1,css:2,js:3,xml:4,png:5,jpg:6,gif:7,xsl:9,ico:10,svg:11,resx:12};function cL(e){if(e.contentBase64!==void 0)return e.contentBase64;if(e.content!==void 0)return(0,XE.utf8ToBase64)(e.content)}async function dL(e,t){return(0,Fne.publishWebResourceById)(e,t)}async function fL(e,t,n){try{await dL(e,t)}catch(r){let i=n?`Web resource '${n.name}' (${t})`:`Web resource ${t}`,o=`write its content again with updateWebResource('${t}', \u2026), which publishes and verifies again`+(n?" \u2014 it exists, and a second create of this name is refused":""),a=(0,Qs.isConcurrencyLockRefusalError)(r)?`Another customization operation holds the environment's lock, and content has been observed missing after a publish the lock refused, so publishing again alone may not recover it: once the lock frees, ${o}.`:`Resolve that failure first, then ${o}.`;throw(0,Za.attachCause)(new Za.WebResourceUnverifiedError(t,n?.name,`${i} was written, but publishing it failed, so whether its published content is what was sent is unconfirmed (${r instanceof Error?r.message:String(r)}). ${a}`),r)}}function qne(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}async function pL(e,t,n,r){var i;let o=r?`Web resource '${r.name}' (${t})`:`Web resource ${t}`,a=r?`It exists: write its content again with updateWebResource('${t}', \u2026), which publishes and verifies again \u2014 a second create of this name is refused.`:"Writing it again is safe.",s=c=>new Za.WebResourceUnverifiedError(t,r?.name,`${o} ${c} ${a}`),u=`/webresourceset(${t})${(0,Ys.odataQuery)([["$select","content"]])}`,l;try{l=(i=(0,Qs.ensureSuccess)(await e.get(u),e.apiUrl(u)).body)===null||i===void 0?void 0:i.content}catch(c){throw(0,Za.attachCause)(s("was written and published, but reading its published content back failed, so whether the write applied is unknown."),c)}if(typeof l!="string")throw s("was written and published, but the read-back carried no content, so whether the write applied is unknown.");if(!qne((0,XE.base64ToBytes)(l),(0,XE.base64ToBytes)(n)))throw s("was written and published, but the published content is not what was sent, so the write did not apply.")}async function Bne(e,t){var n;let r=cL(t);if(r===void 0)throw new Za.InvalidArgumentError(`web resource '${t.name}' requires content or contentBase64`);let i={name:t.name,displayname:(n=t.displayName)!==null&&n!==void 0?n:t.name,webresourcetype:Une[t.type],content:r};t.description&&(i.description=t.description);let o=(0,Qs.ensureSuccess)(await e.post("/webresourceset",i),e.apiUrl("/webresourceset")),a=(0,Qs.readCreatedId)(o,"webresourceid");if(!a)throw new Za.InvalidArgumentError(`Dataverse did not return an id for web resource '${t.name}'`);return t.publish!==!1&&(await fL(e,a,{name:t.name}),await pL(e,a,r,{name:t.name})),{id:a,name:t.name}}Yi.createWebResource=Bne;async function Vne(e,t,n){let r=(0,Ys.normalizeGuid)(t,"id"),i={},o=cL(n);o!==void 0&&(i.content=o),n.displayName!==void 0&&(i.displayname=n.displayName),n.description!==void 0&&(i.description=n.description);let a=`/webresourceset(${r})`;(0,Qs.ensureSuccess)(await e.patch(a,i),e.apiUrl(a)),n.publish!==!1&&(o!==void 0?(await fL(e,r,void 0),await pL(e,r,o,void 0)):await dL(e,r))}Yi.updateWebResource=Vne;async function Gne(e,t){let r=`/webresourceset(${(0,Ys.normalizeGuid)(t,"id")})${(0,Ys.odataQuery)([["$select","name,displayname,webresourcetype,content,description"]])}`,i=e.apiUrl(r),o=(0,Qs.ensureSuccess)(await e.get(r),i),a=o.body;if(a===null||typeof a!="object"||Array.isArray(a))throw new Za.ConnectionError(i,o.status,`getWebResource: the answer is not a web resource row (${Array.isArray(a)?"an array":(0,lL.describeMalformedValue)(a)}); an unreadable answer is never returned as an empty record.`);return a}Yi.getWebResource=Gne;async function jne(e,t){let r=`/webresourceset(${(0,Ys.normalizeGuid)(t,"id")})`;(0,Qs.ensureSuccess)(await e.delete(r),e.apiUrl(r))}Yi.deleteWebResource=jne;async function Wne(e,t,n={}){var r;let i=`/webresourceset${(0,Ys.odataQuery)([["$select",`webresourceid,name,webresourcetype${n.content?",content":""}`],["$filter",`name eq '${(0,Ys.odataLiteral)(t)}'`]])}`,o=(0,Qs.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 Za.ConnectionError(e.apiUrl(i),o.status,`the web resource lookup for '${t}' answered without a value array`);let s=a.find(u=>typeof u?.name=="string"&&u.name.toLowerCase()===t.toLowerCase());if(!s&&(0,lL.pageEnd)(o.body).kind!=="end")throw new Za.ConnectionError(e.apiUrl(i),o.status,`the web resource lookup for '${t}' answered no match but says more rows exist`);if(s?.webresourceid)return{id:(0,Ys.normalizeGuid)(s.webresourceid,"webresourceid"),name:s.name,type:Number(s.webresourcetype),...typeof s.content=="string"?{content:s.content}:{}}}Yi.readWebResourceByName=Wne});var eA=C(Bg=>{"use strict";Object.defineProperty(Bg,"__esModule",{value:!0});Bg.THEME_PALETTE_SLOTS=void 0;Bg.THEME_PALETTE_SLOTS=["darker70","darker60","darker50","darker40","darker30","darker20","darker10","primary","lighter10","lighter20","lighter30","lighter40","lighter50","lighter60","lighter70","lighter80"]});var mL=C(Vg=>{"use strict";Object.defineProperty(Vg,"__esModule",{value:!0});Vg.fnv1a64Hex=void 0;function zne(e){let t=8997,n=33826,r=40164,i=52210;for(let o=0;o<e.length;o++){t^=e[o];let a=t*435,s=n*435+(a>>>16),u=r*435+(s>>>16),l=i*435+(u>>>16),c=(u&65535)+(t<<8&65535),d=(l&65535)+(t>>>8)+(n<<8&65535)+(c>>>16);t=a&65535,n=s&65535,r=c&65535,i=d&65535}return[i,r,n,t].map(o=>o.toString(16).padStart(4,"0")).join("")}Vg.fnv1a64Hex=zne});var aA=C(Ct=>{"use strict";Object.defineProperty(Ct,"__esModule",{value:!0});Ct.settingValueIsNone=Ct.validatePublisherPrefix=Ct.isSdkVersion=Ct.isSdkVersionName=Ct.themeVersionName=Ct.imageDimensions=Ct.themeWarnings=Ct.contrastRatio=Ct.parseAppThemeXml=Ct.serializeAppTheme=Ct.validateAppTheme=Ct.LOGO_IMAGE_TYPES=void 0;var Hne=Ms(),Kne=Y(),Gg=eA(),Jne=ia(),wL=mL(),Yne=["basePaletteColor","lockPrimary","vibrancy","hueTorsion","font","logoWebResource","logoTooltip"],fp=["background","foreground","backgroundHover","foregroundHover","backgroundPressed","foregroundPressed","backgroundSelected","foregroundSelected"],EL=new Map([...Yne,...Gg.THEME_PALETTE_SLOTS].map(e=>[e.toLowerCase(),e])),AL=new Map(fp.map(e=>[e.toLowerCase(),e])),Qne=["basePaletteColor","lockPrimary","vibrancy","hueTorsion","font","palette","appHeader","logo","additionalAttributes"],rA=/^#[0-9A-Fa-f]{6}$/,Xne=/^[A-Za-z_][A-Za-z0-9_.-]*$/,Zne=/^[A-Za-z0-9_./-]{1,256}$/,ere=/[\u0000-\u001F\u007F]/,hL=200;Ct.LOGO_IMAGE_TYPES=[5,6,7,10,11];var CL=/^[A-Za-z][A-Za-z0-9]{1,7}_\/apptheme\/([0-9a-f]{16})\.xml$/;function Zs(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Hn(e,t,n){return{pointer:e,rule:t,message:n}}function iA(e,t,n){(typeof e!="string"||e.length===0||e.length>hL||ere.test(e))&&n.push(Hn(t,"theme-text",`must be 1\u2013${hL} characters with no control character (got ${Pc(e)})`))}function tA(e,t,n){(typeof e!="string"||!rA.test(e))&&n.push(Hn(t,"theme-color-hex",`must be a #RRGGBB colour (got ${Pc(e)})`))}function Pc(e){return typeof e=="string"?e.length>40?`a ${e.length}-character string`:JSON.stringify(e):e===null?"null":typeof e}function gL(e,t,n,r){if(!Zs(e)){r.push(Hn(t,"theme-attribute-name","must be an object of attribute name \u2192 value"));return}let i=new Set;for(let[o,a]of Object.entries(e)){let s=`${t}/${o}`;if(!Xne.test(o)||/^xml/i.test(o)){r.push(Hn(s,"theme-attribute-name",`'${o}' is not an unqualified attribute name (letters, digits, _ . -, not starting with a digit or 'xml'; no namespace prefix)`));continue}let u=o.toLowerCase();if(n.has(u)){r.push(Hn(s,"theme-attribute-collision",`'${o}' is the modelled attribute '${n.get(u)}' \u2014 set it typed`));continue}if(i.has(u)){r.push(Hn(s,"theme-attribute-duplicate",`'${o}' repeats another additional attribute ignoring case`));continue}i.add(u),iA(a,s,r)}}function SL(e){let t=[];if(!Zs(e))return[Hn("","theme-empty","a theme must be an object with at least one property (use null to remove it)")];e.basePaletteColor!==void 0&&tA(e.basePaletteColor,"/basePaletteColor",t),e.lockPrimary!==void 0&&typeof e.lockPrimary!="boolean"&&t.push(Hn("/lockPrimary","theme-boolean",`must be true or false (got ${Pc(e.lockPrimary)})`));for(let r of["vibrancy","hueTorsion"]){let i=e[r];i!==void 0&&(typeof i!="number"||!Number.isInteger(i)||i<-100||i>100)&&t.push(Hn(`/${r}`,"theme-number-range",`must be an integer from -100 to 100 (got ${Pc(i)})`))}e.font!==void 0&&iA(e.font,"/font",t);let n=["basePaletteColor","lockPrimary","vibrancy","hueTorsion","font"].some(r=>e[r]!==void 0);if(e.palette!==void 0)if(!Zs(e.palette))t.push(Hn("/palette","theme-palette-slot","must be an object of slot \u2192 colour"));else for(let[r,i]of Object.entries(e.palette))n=!0,Gg.THEME_PALETTE_SLOTS.includes(r)?tA(i,`/palette/${r}`,t):t.push(Hn(`/palette/${r}`,"theme-palette-slot",`'${r}' is not one of the 16 palette slots`));if(e.appHeader!==void 0){n=!0;let r=e.appHeader;if((!Zs(r)||r.background===void 0)&&t.push(Hn("/appHeader/background","theme-app-header-background-required","header colours need a background")),Zs(r)){for(let i of fp)r[i]!==void 0&&tA(r[i],`/appHeader/${i}`,t);r.additionalAttributes!==void 0&&gL(r.additionalAttributes,"/appHeader/additionalAttributes",AL,t);for(let i of Object.keys(r))!fp.includes(i)&&i!=="additionalAttributes"&&t.push(Hn(`/appHeader/${i}`,"theme-unknown-property",`'${i}' is not a header property`))}}if(e.logo!==void 0){n=!0;let r=e.logo;if((!Zs(r)||r.webResourceName===void 0&&r.tooltip===void 0)&&t.push(Hn("/logo","theme-empty","a logo needs a webResourceName, a tooltip, or both")),Zs(r)){r.webResourceName!==void 0&&(typeof r.webResourceName!="string"||!Zne.test(r.webResourceName))&&t.push(Hn("/logo/webResourceName","theme-logo-name",`must be a web resource name (letters, digits, _ - . /) (got ${Pc(r.webResourceName)})`)),r.tooltip!==void 0&&iA(r.tooltip,"/logo/tooltip",t);for(let i of Object.keys(r))i!=="webResourceName"&&i!=="tooltip"&&t.push(Hn(`/logo/${i}`,"theme-unknown-property",`'${i}' is not a logo property`))}}e.additionalAttributes!==void 0&&(Zs(e.additionalAttributes)&&Object.keys(e.additionalAttributes).length>0&&(n=!0),gL(e.additionalAttributes,"/additionalAttributes",EL,t));for(let r of Object.keys(e))Qne.includes(r)||t.push(Hn(`/${r}`,"theme-unknown-property",`'${r}' is not a theme property`));return!n&&t.length===0&&t.push(Hn("","theme-empty","a theme needs at least one property (use null to remove it)")),t}Ct.validateAppTheme=SL;function tre(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function nA(e){return e.map(([t,n])=>` ${t}="${tre(n)}"`).join("")}function NL(e){var t,n,r,i,o;let a=[],s=(l,c)=>{c!==void 0&&a.push([l,String(c)])};s("basePaletteColor",e.basePaletteColor),s("lockPrimary",e.lockPrimary),s("vibrancy",e.vibrancy),s("hueTorsion",e.hueTorsion),s("font",e.font),s("logoWebResource",(t=e.logo)===null||t===void 0?void 0:t.webResourceName),s("logoTooltip",(n=e.logo)===null||n===void 0?void 0:n.tooltip);for(let l of Gg.THEME_PALETTE_SLOTS)s(l,(r=e.palette)===null||r===void 0?void 0:r[l]);for(let[l,c]of Object.entries((i=e.additionalAttributes)!==null&&i!==void 0?i:{}))a.push([l,c]);if(!e.appHeader)return`<CustomTheme${nA(a)} />`;let u=[];for(let l of fp){let c=e.appHeader[l];c!==void 0&&u.push([l,c])}for(let[l,c]of Object.entries((o=e.appHeader.additionalAttributes)!==null&&o!==void 0?o:{}))u.push([l,c]);return`<CustomTheme${nA(a)}><AppHeaderColors${nA(u)} /></CustomTheme>`}Ct.serializeAppTheme=NL;var nre=1,oA=3,rre=7;function Xs(e){return{exact:!1,diagnostics:[`not representable by AppTheme: ${e}`]}}function _L(e,t){let n=new Map,r=[],i=new Map,o=!1,a=e.attributes;for(let s=0;s<a.length;s++){let u=a.item(s);if(!u)continue;let l=u.name;if(l==="xmlns"||l.startsWith("xmlns:"))return`a namespace declaration (${l})`;if(u.prefix||l.includes(":"))return`a qualified attribute (${l})`;let c=l.toLowerCase(),d=t.get(c);if(i.has(c)&&(d||t.has(c)))return`two attributes differ only by case (${i.get(c)}, ${l})`;i.set(c,l),d?(n.set(d,u.value),o=o||d!==l):r.push([l,u.value])}return{modelled:n,additional:r,spelling:o}}function IL(e,t){var n;let r=[],i=e.childNodes;for(let o=0;o<i.length;o++){let a=i[o];if(!(a.nodeType===oA&&/^\s*$/.test((n=a.nodeValue)!==null&&n!==void 0?n:""))){if(a.nodeType===nre){let s=a;if(!t.includes(s.nodeName)||s.namespaceURI)return`an unexpected element <${s.nodeName}>`;r.push(s);continue}return a.nodeType===oA?"text content":`an unsupported node (type ${a.nodeType})`}}return r}function ire(e){let t=e.toLowerCase();return t==="true"?!0:t==="false"?!1:e}function yL(e){return/^-?\d+$/.test(e)?parseInt(e,10):e===""?e:Number(e)}function bL(e){let t=_L(e,AL);if(typeof t=="string")return t;let n=IL(e,[]);if(typeof n=="string")return n;let r={};for(let i of fp){let o=t.modelled.get(i);o!==void 0&&(r[i]=o)}return t.additional.length>0&&(r.additionalAttributes=Object.fromEntries(t.additional)),r}function ore(e){var t,n;let r=[],i=h=>g=>{r.push(`${h}: ${g}`)},o=new Hne.DOMParser({errorHandler:{warning:i("warning"),error:i("error"),fatalError:i("fatalError")}}).parseFromString(String(e??""),"text/xml"),a=(t=o?.documentElement)!==null&&t!==void 0?t:null;if(!o||!a||r.length>0)return Xs(`not well-formed XML${r.length>0?` (${r[0]})`:""}`);let s=!1,u=o.childNodes;for(let h=0;h<u.length;h++){let g=u[h];if(!(g===a||g.nodeType===oA&&/^\s*$/.test((n=g.nodeValue)!==null&&n!==void 0?n:""))){if(g.nodeType===rre&&g.target.toLowerCase()==="xml"){s=!0;continue}return Xs(`an unsupported node outside the root (type ${g.nodeType})`)}}if(a.namespaceURI||a.nodeName!=="CustomTheme"&&a.nodeName!=="AppHeaderColors")return Xs(`the root is <${a.nodeName}>, not <CustomTheme> or <AppHeaderColors>`);let l={},c=!1;if(a.nodeName==="AppHeaderColors"){let h=bL(a);if(typeof h=="string")return Xs(h);l.appHeader=h}else{let h=_L(a,EL);if(typeof h=="string")return Xs(h);c=h.spelling;let g=IL(a,["AppHeaderColors"]);if(typeof g=="string")return Xs(g);if(g.length>1)return Xs("more than one <AppHeaderColors>");let y=_=>h.modelled.get(_),b=(_,I)=>{I!==void 0&&(l[_]=I)};b("basePaletteColor",y("basePaletteColor")),b("lockPrimary",y("lockPrimary")===void 0?void 0:ire(y("lockPrimary"))),b("vibrancy",y("vibrancy")===void 0?void 0:yL(y("vibrancy"))),b("hueTorsion",y("hueTorsion")===void 0?void 0:yL(y("hueTorsion"))),b("font",y("font"));let E={};y("logoWebResource")!==void 0&&(E.webResourceName=y("logoWebResource")),y("logoTooltip")!==void 0&&(E.tooltip=y("logoTooltip")),Object.keys(E).length>0&&(l.logo=E);let w={};for(let _ of Gg.THEME_PALETTE_SLOTS){let I=y(_);I!==void 0&&(w[_]=I)}if(Object.keys(w).length>0&&(l.palette=w),g.length===1){let _=bL(g[0]);if(typeof _=="string")return Xs(_);l.appHeader=_}h.additional.length>0&&(l.additionalAttributes=Object.fromEntries(h.additional))}let d=SL(l);if(d.length>0)return{exact:!1,diagnostics:d.map(h=>`not representable by AppTheme: ${h.pointer||"/"} ${h.message} [${h.rule}]`)};let f=l,p=NL(f)===e,m=[];if(!p){let h=[...s?["an XML declaration"]:[],...c?["attribute spelling"]:[],...a.nodeName==="AppHeaderColors"?["the header-only root"]:[]];m.push(`writing this theme back creates a NEW version: its canonical bytes differ from the stored document${h.length>0?` (${h.join(", ")})`:" (attribute order, whitespace or value spelling)"}`)}return{theme:f,exact:p,diagnostics:m}}Ct.parseAppThemeXml=ore;function vL(e){let t=n=>{let r=parseInt(e.slice(n,n+2),16)/255;return r<=.03928?r/12.92:Math.pow((r+.055)/1.055,2.4)};return .2126*t(1)+.7152*t(3)+.0722*t(5)}function TL(e,t){let[n,r]=[vL(e),vL(t)].sort((i,o)=>o-i);return(n+.05)/(r+.05)}Ct.contrastRatio=TL;function are(e){let t=[],n=e.appHeader;if(n){let r=[["rest",n.foreground,n.background],["hover",n.foregroundHover,n.backgroundHover],["pressed",n.foregroundPressed,n.backgroundPressed],["selected",n.foregroundSelected,n.backgroundSelected]];for(let[i,o,a]of r)if(o&&a&&rA.test(o)&&rA.test(a)){let s=TL(o,a);s<4.5&&t.push(`App header ${i} colours ${o} on ${a} have a contrast of ${s.toFixed(2)}:1, below the 4.5:1 Learn asks makers to verify.`)}}return(e.vibrancy!==void 0||e.hueTorsion!==void 0)&&e.lockPrimary!==!0&&t.push('vibrancy/hueTorsion are set without lockPrimary: true \u2014 Learn says they apply only with lockPrimary="true" (its own example contradicts that; the effect is not verified).'),t}Ct.themeWarnings=are;function sre(e){let t=r=>{var i;return(i=e[r])!==null&&i!==void 0?i:0},n=r=>t(r)*256+t(r+1);if(e.length>=24&&t(0)===137&&t(1)===80&&t(2)===78&&t(3)===71)return{width:n(16)*65536+n(18),height:n(20)*65536+n(22)};if(e.length>=10&&t(0)===71&&t(1)===73&&t(2)===70&&t(3)===56)return{width:t(6)+t(7)*256,height:t(8)+t(9)*256};if(e.length>=4&&t(0)===255&&t(1)===216){let r=2;for(;r+3<e.length;){if(t(r)!==255)return;let i=t(r+1);if(i===216||i===1||i>=208&&i<=215){r+=2;continue}if(i>=192&&i<=207&&i!==196&&i!==200&&i!==204)return r+8<e.length?{width:n(r+7),height:n(r+5)}:void 0;r+=2+n(r+2)}}}Ct.imageDimensions=sre;function ure(e,t){return`${e}_/apptheme/${(0,wL.fnv1a64Hex)((0,Jne.utf8ToBytes)(t))}.xml`}Ct.themeVersionName=ure;function lre(e){return typeof e=="string"&&CL.test(e)}Ct.isSdkVersionName=lre;function cre(e,t){let n=typeof e=="string"?CL.exec(e):null;return!!n&&n?.[1]===(0,wL.fnv1a64Hex)(t)}Ct.isSdkVersion=cre;function dre(e){if(typeof e!="string"||!/^[A-Za-z][A-Za-z0-9]{1,7}$/.test(e)||/^mscrm/i.test(e))throw new Kne.InvalidArgumentError(`setAppTheme: publisherPrefix must be 2\u20138 letters or digits starting with a letter, not 'mscrm\u2026' (got ${Pc(e)}).`);return e}Ct.validatePublisherPrefix=dre;function fre(e){return e==null||e===""||e==='""'}Ct.settingValueIsNone=fre});var hA=C(Lt=>{"use strict";Object.defineProperty(Lt,"__esModule",{value:!0});Lt.getAppTheme=Lt.setAppTheme=Lt.HEADER_SETTING=Lt.THEME_SETTING=void 0;var pre=QE(),uA=vc(),mre=Ff(),hre=Ke(),lA=il(),kc=ZE(),bn=aA(),ht=Y(),pA=pe(),mp=ia(),wo=ae();Lt.THEME_SETTING="CustomThemeDefinition";Lt.HEADER_SETTING="OverrideAppHeaderColor";var cA=4,OL=61,gre=80,DL=3;function yre(e){return new Promise(t=>setTimeout(t,e))}function ol(e){return e.plain?e.unpublished?e.unpublished.componentstate===1?"publishedWithDraft":"published":"removalPending":e.unpublished?"draft":"absent"}function mA(e){return e==="published"||e==="publishedWithDraft"||e==="removalPending"}function Rc(e){var t,n,r;return ol(e)==="removalPending"?void 0:(n=(t=e.unpublished)===null||t===void 0?void 0:t.value)!==null&&n!==void 0?n:(r=e.plain)===null||r===void 0?void 0:r.value}function dA(e,t){return(0,bn.settingValueIsNone)(e)&&(0,bn.settingValueIsNone)(t)||e===t}function PL(e){let t=e.plain,n=e.unpublished;return JSON.stringify([t?.id,t?.value,t?.etag,n?.id,n?.value,n?.etag,n?.componentstate])}function LL(e){var t,n;if(e instanceof ht.ConnectionError){let r=(n=(t=e.cause)===null||t===void 0?void 0:t.error)===null||n===void 0?void 0:n.code;return typeof r=="string"?r.toLowerCase():void 0}}function RL(e){return e instanceof ht.SdkError&&e.code===pA.VERSION_CONFLICT_CODE}function $c(e,t,n){return(0,hre.collectPages)(e,t,n)}async function ML(e,t){let r=(await $c(e,(0,uA.unpublishedAppModulesQuery)("appmoduleid,uniquename,name",`appmoduleid eq ${t}`),`the app lookup for '${t}'`))[0];if(!r||typeof r.appmoduleid!="string"||typeof r.uniquename!="string")throw new ht.SdkError("APP_NOT_FOUND",`App '${t}' was not found (checked the unpublished-aware projection, which includes drafts).`);return{id:t,uniqueName:r.uniquename,name:typeof r.name=="string"?r.name:r.uniquename}}async function pp(e,t,n){let r=`_parentappmoduleid_value eq ${t} and (`+n.map(c=>`_settingdefinitionid_value eq ${c}`).join(" or ")+")",i=`/appsettings${(0,wo.odataQuery)([["$select","appsettingid,value,_settingdefinitionid_value"],["$filter",r]])}`,o=`/appsettings/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()${(0,wo.odataQuery)([["$select","appsettingid,value,componentstate,_settingdefinitionid_value"],["$filter",r]])}`,a=await $c(e,i,"the app setting read"),s=await $c(e,o,"the unpublished app setting read"),u=new Map,l=(c,d)=>{var f,p,m;for(let h of c){let g=String((f=h._settingdefinitionid_value)!==null&&f!==void 0?f:"").toLowerCase(),y=(p=u.get(g))!==null&&p!==void 0?p:{};if(y[d])throw new ht.ConnectionError(e.apiUrl(i),200,`two ${d} app setting rows for one setting`);y[d]={id:(0,wo.normalizeGuid)(String((m=h.appsettingid)!==null&&m!==void 0?m:""),"appsettingid"),value:typeof h.value=="string"?h.value:"",etag:typeof h["@odata.etag"]=="string"?h["@odata.etag"]:null,...typeof h.componentstate=="number"?{componentstate:h.componentstate}:{}},u.set(g,y)}};return l(a,"plain"),l(s,"unpublished"),u}async function xL(e,t){var n,r;let i=await(0,mre.resolveSettingDefinitions)(e,[Lt.THEME_SETTING,Lt.HEADER_SETTING]),o=(n=i.get(Lt.THEME_SETTING))===null||n===void 0?void 0:n.settingdefinitionid;if(!o)throw new ht.AppThemeError("APP_THEME_UNAVAILABLE",t,`The modern theme is not available in this environment: no settingdefinition '${Lt.THEME_SETTING}' exists (it is a Preview setting and may be version-gated). Nothing was written.`);let a=(r=i.get(Lt.HEADER_SETTING))===null||r===void 0?void 0:r.settingdefinitionid;return{theme:(0,wo.normalizeGuid)(o,"settingdefinitionid"),...a?{header:(0,wo.normalizeGuid)(a,"settingdefinitionid")}:{}}}async function al(e,t,n){return(await(0,pre.retrieveSetting)(e,t,n?{appUniqueName:n}:{})).value}function FL(e,t,n,r){return(0,bn.settingValueIsNone)(e)?"none":mA(t)?n===e?"app":"unknown":r===e?"environment":"unknown"}function UL(e,t,n,r){let i=[];(e==="draft"||e==="publishedWithDraft")&&i.push("rowDraft"),e==="removalPending"&&i.push("removalPending");let o=mA(e)?t:r;return dA(n,o)||i.push("resolvedDiffers"),i}function bre(e){return typeof e=="string"&&e.length>2&&e.startsWith('"')&&e.endsWith('"')}async function vre(e,t,n){if((await $c(e,`/publishers${(0,wo.odataQuery)([["$select","publisherid"],["$filter",`customizationprefix eq '${(0,wo.odataLiteral)(n)}'`]])}`,`the publisher lookup for prefix '${n}'`)).length===0)throw new ht.InvalidArgumentError(`setAppTheme: no publisher in this environment has the customization prefix '${n}' \u2014 a web resource name must carry an existing publisher's prefix. Nothing was written for app ${t}.`)}var kL=new WeakMap;async function wre(e){var t;let n=kL.get(e);if(n!==void 0)return n;let r=await $c(e,`/solutioncomponentdefinitions${(0,wo.odataQuery)([["$select","solutioncomponenttype,primaryentityname"],["$filter","primaryentityname eq 'appsetting'"]])}`,"the appsetting component definition read"),i=Number((t=r[0])===null||t===void 0?void 0:t.solutioncomponenttype);if(!Number.isInteger(i)||i<=0)throw new ht.ConnectionError(e.apiUrl("/solutioncomponentdefinitions"),200,"the appsetting solution component type could not be read");return kL.set(e,i),i}async function $L(e,t,n){let r=await $c(e,`/solutioncomponents${(0,wo.odataQuery)([["$select","objectid,componenttype"],["$filter",`_solutionid_value eq ${t} and (${n.map(i=>`objectid eq ${i}`).join(" or ")})`]])}`,"the solution membership read");return new Set(r.map(i=>{var o;return`${Number(i.componenttype)}:${String((o=i.objectid)!==null&&o!==void 0?o:"").toLowerCase()}`}))}function qL(e,t,n){if(!(t.type===cA&&typeof t.content=="string"&&Ere((0,mp.base64ToBytes)(t.content),(0,mp.utf8ToBytes)(n))))throw new ht.AppThemeError("APP_THEME_NAME_TAKEN",e,`The theme's version name '${t.name}' (web resource ${t.id}) already holds ${t.type===cA?"different bytes":`a non-XML resource (type ${t.type})`}. Theme versions are never overwritten: nothing was written. A name is not proof of ownership. If it is a version an earlier setAppTheme failed to verify, only an operator can remove it: in a quiet window (no one changing app themes), check that no app resolves it (getAppTheme for each app), no app's setting row names it in either layer, and the environment value does not name it \u2014 then deleteWebResource('${t.id}') and run again.`,t.name)}function Ere(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}async function Are(e,t,n,r){var i;let o=(i=n.logo)===null||i===void 0?void 0:i.webResourceName;if(!o)return;let a=await(0,kc.readWebResourceByName)(e,o,{content:!0});if(!a||!bn.LOGO_IMAGE_TYPES.includes(a.type))throw new ht.AppThemeError("APP_THEME_LOGO_INVALID",t,a?`The logo '${o}' is a web resource of type ${a.type}, not an image (png, jpg, gif, ico or svg). Nothing was written.`:`The logo '${o}' names no web resource \u2014 upload it with createWebResource first. Nothing was written.`,o);let s=typeof a.content=="string"?(0,bn.imageDimensions)((0,mp.base64ToBytes)(a.content)):void 0;s&&(s.width>156||s.height>48)&&r.push(`The logo '${o}' is ${s.width} \xD7 ${s.height} px, larger than the 156 \xD7 48 px Learn recommends; Learn says logos that are too large are not displayed (the limit is not measured \u2014 check in a browser).`)}function fA(e,t){return new ht.VersionConflictError("appTheme",e,null,null,t)}async function Cre(e,t,n,r,i,o){var a,s,u;let l=ol(r),c=f=>{throw f instanceof ht.VersionConflictError?f:RL(f)||LL(f)==="0x80072013"?(0,ht.attachCause)(fA(t,`Another writer changed the app's theme setting at the moment of the write (${RL(f)?"its token moved":"a row for this app was created"}); nothing was written to it and nothing is re-sent.${o}`),f):f},d=()=>{var f;if(!(!((f=r.plain)===null||f===void 0)&&f.etag))throw fA(t,`The app's published theme setting row carried no token, so it cannot be written safely.${o}`);return r.plain.etag};try{if(i!==null){if(l==="absent"){let w="/appsettings",_=await e.post(w,{"[email protected]":`/appmodules(${t})`,"[email protected]":`/settingdefinitions(${n})`,value:i});return sA(e,w,_),{outcome:"created",createdId:(a=(0,pA.readCreatedId)(_,"appsettingid"))!==null&&a!==void 0?a:void 0}}let g=Rc(r);if(l!=="removalPending"&&g===i)return{outcome:"unchanged"};let y=((s=r.plain)!==null&&s!==void 0?s:r.unpublished).id,b=l==="draft"?"*":d(),E=`/appsettings(${y})`;return sA(e,E,await e.patch(E,{value:i},{headers:{"If-Match":b}})),{outcome:"updated"}}if(l==="absent")return{outcome:"unchanged"};if(l==="removalPending")return{outcome:"removed"};let f=((u=r.plain)!==null&&u!==void 0?u:r.unpublished).id,p=l==="draft"?"*":d(),m=`/appsettings(${f})`;return sA(e,m,await e.delete(m,{headers:{"If-Match":p}})),{outcome:"removed"}}catch(f){return c(f)}}function sA(e,t,n){var r,i;if(n.status===412)throw new ht.SdkError(pA.VERSION_CONFLICT_CODE,`Version conflict (412) from ${e.apiUrl(t)}`);if(n.status<200||n.status>=300){let o=(i=(r=n.body)===null||r===void 0?void 0:r.error)===null||i===void 0?void 0:i.message;throw new ht.ConnectionError(e.apiUrl(t),n.status,typeof o=="string"?o:"request failed",n.body)}}async function Sre(e,t,n,r={},i={}){var o,a,s,u,l,c,d,f,p,m,h,g,y,b;let E=(0,wo.normalizeGuid)(t,"appId");if(n!==null){let Kt=(0,bn.validateAppTheme)(n);if(Kt.length>0)throw new ht.ValidationError("appTheme",E,Kt)}let w;if(n!==null){if(r.publisherPrefix!==void 0)w=(0,bn.validatePublisherPrefix)(r.publisherPrefix);else if(!e.solutionName)throw new ht.InvalidArgumentError("setAppTheme: a theme version needs a publisher prefix for its web resource name \u2014 pass options.publisherPrefix, or create the SDK with the solution to write into (solutionUniqueName).")}let I=(o=i.sleep)!==null&&o!==void 0?o:yre,T=n!==null?(0,bn.serializeAppTheme)(n):void 0,O=await ML(e,E),v=await xL(e,E),N=[];v.header||N.push(`The setting ${Lt.HEADER_SETTING} is not available in this environment, so a header-colour override was not checked.`);let S=await pp(e,E,[v.theme,...v.header?[v.header]:[]]),R=(a=S.get(v.theme))!==null&&a!==void 0?a:{},x=v.header?S.get(v.header):void 0;n!==null&&x&&!(0,bn.settingValueIsNone)(Rc(x))&&N.push(`The app also has an "Override app header colors" value ('${Rc(x)}'); the platform ignores it while a custom theme is set (Learn).`);let G,U,M;if(n!==null&&T!==void 0){if(w!==void 0&&await vre(e,E,w),e.solutionName&&(G=await(0,lA.getSolution)(e,e.solutionName),w===void 0)){if(!G.publisherPrefix)throw new ht.InvalidArgumentError(`setAppTheme: the publisher of solution '${G.uniqueName}' has no customization prefix \u2014 pass options.publisherPrefix.`);w=G.publisherPrefix}U=(0,bn.themeVersionName)(w,T),await Are(e,E,n,N),M=await(0,kc.readWebResourceByName)(e,U,{content:!0}),M&&qL(E,M,T),N.push(...(0,bn.themeWarnings)(n))}if(r.publish===!0)try{await(0,uA.assertAppPublicationProvable)(e,E)}catch(Kt){throw(0,ht.attachCause)(new ht.AppThemeError("APP_THEME_PUBLISH_BLOCKED",E,`Nothing was written: setAppTheme with publish: true is refused because the app publication it asks for would be refused. ${Kt instanceof Error?Kt.message:String(Kt)}`,U),Kt)}let q;n!==null&&T!==void 0&&U!==void 0&&(M?q={id:M.id,name:U,created:!1}:q=await Nre(e,E,U,T));let X=q?` The theme version '${q.name}' (${q.id}) exists and a re-run reuses it.`:"",ye=(s=(await pp(e,E,[v.theme])).get(v.theme))!==null&&s!==void 0?s:{};if(PL(ye)!==PL(R))throw fA(E,`The app's theme setting changed after it was read (another writer); nothing was written to it.${X}`);let Ve=await Cre(e,E,v.theme,R,(u=q?.name)!==null&&u!==void 0?u:null,X),_e=(l=(await pp(e,E,[v.theme])).get(v.theme))!==null&&l!==void 0?l:{},wt=ol(_e);if(!(q?Rc(_e)===q.name:wt==="absent"||wt==="removalPending"))throw new ht.AppThemeError("APP_THEME_NOT_SAVED",E,q?`The app's theme setting read back holds '${(c=Rc(_e))!==null&&c!==void 0?c:"(nothing)"}', not '${q.name}'.${X}`:`The app's theme override was removed, but the read-back still shows it (state ${wt}).`,q?.name);let xe=[];if(q&&G){let Kt=(p=(f=(d=_e.unpublished)!==null&&d!==void 0?d:_e.plain)===null||f===void 0?void 0:f.id)!==null&&p!==void 0?p:Ve.createdId;Kt&&xe.push(...await _re(e,E,G,q,Kt,X))}let Et,zt;if(r.publish===!0){try{await(0,uA.publishApp)(e,E)}catch(Yr){let Ql=Yr?.code,dT=Ql==="APP_MAIN_FORM_PUBLISH_WITHHELD"||Ql==="APP_MAIN_FORM_PUBLISH_CONFLICT";throw(0,ht.attachCause)(new ht.AppThemeError("APP_THEME_PUBLISH_FAILED",E,`The app's theme setting is saved (${q?`naming '${q.name}'`:"override removed"}, ${Ve.outcome}), but ${dT?`its app publication was refused (${String(Ql)})`:"publishing the app failed"}, so it does not resolve yet: ${Yr instanceof Error?Yr.message:String(Yr)}. ${dT?"Nothing was published; nothing was re-sent.":"Publish the app again; nothing was re-sent."}`,q?.name),Yr)}zt=q?void 0:await al(e,Lt.THEME_SETTING);let Kt=q?q.name:zt,Lu=!1;for(let Yr=0;Yr<DL&&!Lu;Yr++){Yr>0&&await I(1e3*Yr),Et=await al(e,Lt.THEME_SETTING,O.uniqueName),_e=(m=(await pp(e,E,[v.theme])).get(v.theme))!==null&&m!==void 0?m:{};let Ql=ol(_e);Lu=q?Ql==="published"&&((h=_e.plain)===null||h===void 0?void 0:h.value)===q.name&&dA(Et,q.name):Ql==="absent"&&dA(Et,Kt)}if(!Lu)throw new ht.AppThemeError("APP_THEME_NOT_RESOLVED",E,`The app was published, but the platform's resolved theme for it is '${Et}' (expected '${Kt}', row ${ol(_e)}) after ${DL} reads. This is about stored/resolved state, not rendering.`,q?.name)}else Et=await al(e,Lt.THEME_SETTING,O.uniqueName);let Ht=ol(_e),W=(g=_e.plain)===null||g===void 0?void 0:g.value;zt===void 0&&!mA(Ht)&&(zt=await al(e,Lt.THEME_SETTING));let Fe=Et,Ie=FL(Fe,Ht,W,zt),At=UL(Ht,W,Fe,zt),Ts=[(y=R.plain)===null||y===void 0?void 0:y.value,(b=R.unpublished)===null||b===void 0?void 0:b.value].filter((Kt,Lu,Yr)=>typeof Kt=="string"&&!(0,bn.settingValueIsNone)(Kt)&&Yr.indexOf(Kt)===Lu&&Kt!==q?.name),f6=Ts.filter(Kt=>(0,bn.isSdkVersionName)(Kt));if(Ve.outcome!=="unchanged")for(let Kt of Ts.filter(Lu=>!(0,bn.isSdkVersionName)(Lu)))N.push(`The app's previous theme '${Kt}' is not an SDK theme version; it was ${q?"replaced":"unset"} for this app and left untouched.`);return{appId:E,outcome:Ve.outcome,...q?{webResource:q}:{},published:r.publish===!0,resolved:{source:Ie,...Ie!=="none"?{webResourceName:Fe}:{}},rowState:Ht,pendingPublish:At.length>0,pendingReasons:At,superseded:f6,solutionComponentsAdded:xe,warnings:N}}Lt.setAppTheme=Sre;async function Nre(e,t,n,r){let i=n.slice(n.lastIndexOf("/")+1,-4);try{return{id:(await(0,kc.createWebResource)(e,{name:n,type:"xml",content:r,displayName:`Modern app theme ${i}`,description:"Immutable modern-theme XML written by setAppTheme (cds-maker-sdk). Changing a theme creates a new version.",publish:!0})).id,name:n,created:!0}}catch(o){let a=LL(o);if(a==="0x8004f115"){let s=await(0,kc.readWebResourceByName)(e,n,{content:!0});if(s)return qL(t,s,r),{id:s.id,name:n,created:!1}}throw a==="0x8004f118"?(0,ht.attachCause)(new ht.InvalidArgumentError(`setAppTheme: '${n}' does not carry a valid customization prefix (an existing publisher's). Nothing was written.`),o):o}}async function _re(e,t,n,r,i,o){let a=(s,u)=>{let l=new ht.AppThemeError("APP_THEME_NOT_IN_SOLUTION",t,`The theme setting is saved, but ${s} in solution '${n.uniqueName}'.${o} Run again to retry the membership.`,r.name);throw u===void 0?l:(0,ht.attachCause)(l,u)};try{let s=await wre(e),u=[r.id,i,t].map(h=>h.toLowerCase()),l=await $L(e,n.solutionId,u),c=[],d=`${OL}:${u[0]}`,f=`${s}:${u[1]}`;if(l.has(d)||(await(0,lA.addSolutionComponent)(e,{componentId:r.id,componentType:OL,solutionUniqueName:n.uniqueName,addRequiredComponents:!1}),c.push("webResource")),l.has(f)||(await(0,lA.addSolutionComponent)(e,{componentId:i,componentType:s,solutionUniqueName:n.uniqueName,addRequiredComponents:!1}),c.push("appSetting")),c.length===0)return c;let p=await $L(e,n.solutionId,u);if(!p.has(d)||!p.has(f))return a("the theme version or the setting row is still not a member after adding it");let m=`${gre}:${u[2]}`;return p.has(m)&&!l.has(m)&&c.push("app"),c}catch(s){if(s instanceof ht.AppThemeError)throw s;return a("the theme version or the setting row could not be added",s)}}async function Ire(e,t){var n,r,i;let o=(0,wo.normalizeGuid)(t,"appId"),a=await ML(e,o),s=await xL(e,o),u=[],l=await pp(e,o,[s.theme,...s.header?[s.header]:[]]),c=(n=l.get(s.theme))!==null&&n!==void 0?n:{},d=ol(c),f=(r=c.plain)===null||r===void 0?void 0:r.value,p=Rc(c),m=await al(e,Lt.THEME_SETTING,a.uniqueName),h=await al(e,Lt.THEME_SETTING),g=UL(d,f,m,h),y=new Map,b=(I,T)=>{if(I==="none"||T===void 0||(0,bn.settingValueIsNone)(T))return Promise.resolve({source:"none"});let O=`${I}\0${T}`;return y.has(O)||y.set(O,Tre(e,I,T,u)),y.get(O)},E=await b(FL(m,d,f,h),m),w=d==="absent"||d==="removalPending"?await b((0,bn.settingValueIsNone)(h)?"none":"environment",h):await b((0,bn.settingValueIsNone)(p)?"none":"app",p);for(let I of[f,p,h])bre(I)&&u.push(`The theme setting value ${I} is wrapped in quotes \u2014 Learn says to remove them; it is reported verbatim.`);g.includes("resolvedDiffers")&&!g.includes("rowDraft")&&!g.includes("removalPending")&&u.push("The app's theme setting row is published but the app is not \u2014 publish the app so it resolves (a setting-only publish does not change what the app resolves).");for(let I of new Set([E,w]))await Ore(e,I,u);let _;if(s.header){let I=await al(e,Lt.HEADER_SETTING,a.uniqueName);if(!(0,bn.settingValueIsNone)(I)){let T=l.get(s.header);_={source:((i=T?.plain)===null||i===void 0?void 0:i.value)===I?"app":"environment",webResourceName:I},E.source!=="none"&&u.push(`"Override app header colors" ('${I}') is set, but it is ignored by the platform while a custom theme is set (Learn).`)}}else u.push(`The setting ${Lt.HEADER_SETTING} is not available in this environment, so it was not read.`);return{appId:o,appUniqueName:a.uniqueName,resolved:E,row:{state:d,...f!==void 0?{publishedValue:f}:{},...p!==void 0?{latestValue:p}:{}},afterPublish:w,pendingPublish:g.length>0,pendingReasons:g,..._?{headerColorOverride:_}:{},warnings:u}}Lt.getAppTheme=Ire;async function Tre(e,t,n,r){let i;try{i=await(0,kc.readWebResourceByName)(e,n,{content:!0})}catch(s){let u=s instanceof Error?s.message:String(s);return r.push(`The theme web resource '${n}' (${t}) could not be read, so its content is unverified: ${u}`),{source:t,webResourceName:n,diagnostics:[`unreadable: ${u}`]}}if(!i)return r.push(`The theme web resource '${n}' (${t}) does not exist \u2014 the setting names nothing readable.`),{source:t,webResourceName:n};if(i.type!==cA||typeof i.content!="string")return r.push(`The theme web resource '${n}' is not an XML web resource (type ${i.type}).`),{source:t,webResourceName:n,diagnostics:["not an XML web resource"],sdkVersion:!1};let o=(0,mp.base64ToBytes)(i.content),a=(0,bn.parseAppThemeXml)((0,mp.base64ToUtf8)(i.content));return a.theme||r.push(`The theme web resource '${n}' is not representable as an AppTheme (see its diagnostics).`),{source:t,webResourceName:n,...a.theme?{theme:a.theme}:{},exact:a.exact,diagnostics:a.diagnostics,sdkVersion:(0,bn.isSdkVersion)(n,o)}}async function Ore(e,t,n){var r,i;let o=(i=(r=t.theme)===null||r===void 0?void 0:r.logo)===null||i===void 0?void 0:i.webResourceName;if(o)try{await(0,kc.readWebResourceByName)(e,o)||n.push(`The theme '${t.webResourceName}' names the logo '${o}', which no longer exists.`)}catch(a){n.push(`The logo '${o}' named by the theme '${t.webResourceName}' could not be checked: ${a instanceof Error?a.message:String(a)}`)}}});var Kg=C(we=>{"use strict";Object.defineProperty(we,"__esModule",{value:!0});we.buildRecipe=we.roleIdentity=we.readPlanInput=we.readLimits=we.requireCodec=we.unknown=we.refusal=we.CERTIFIED_GATES=void 0;var BL=cp(),ze=Ya(),Dre=kg(),VL=hA(),Pre=aA(),Rre=new Set([VL.THEME_SETTING,VL.HEADER_SETTING].map(e=>e.toLowerCase())),kre=e=>Rre.has(e.definition.toLowerCase())&&!(0,Pre.settingValueIsNone)(e.value);we.CERTIFIED_GATES=Object.freeze({connectionReferences:!1,secretReferences:!1,unmanagedImport:!1,stageCleanup:!1});var $re=(e,t={})=>({problem:(0,ze.promotionProblem)(e,"preflight",t),unknown:!1});we.refusal=$re;var Lre=(e={})=>({problem:(0,ze.promotionProblem)("PROMOTION_VERIFICATION_UNAVAILABLE","preflight",e),unknown:!0});we.unknown=Lre;var Mre=new Set(["packageBase64","appUniqueName","mode","values","connections","settingOverrides","requirements","overwriteUnmanagedCustomizations","publishWorkflows","acknowledgeNonAtomicImport","publishApp","codec","limits"]),xre=new Set(["upgrade","stageAndUpgrade","holdingSolution","importAsHolding","convertToManaged","deleteSolution","uninstall","applyUpgrade"]),un=e=>(0,ze.promotionError)("INVALID_ARGUMENT","preflight",{reason:e}),Hg=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function ki(e,t,n,r){if(!Hg(e))throw un(`${r} must be an object`);for(let i of Object.keys(e))if(!t.includes(i)&&!n.includes(i))throw un(`${r} has an unsupported field`);for(let i of t)if(e[i]===void 0)throw un(`${r} lacks a required field`);return e}function es(e,t){if(typeof e!="string"||e.length===0||e.trim()!==e)throw un(`${t} must be a non-empty string without surrounding whitespace`);return e}function jg(e,t,n){if(!(e===void 0&&n)){if(typeof e!="boolean")throw un(`${t} must be true or false`);return e}}function Wg(e,t){if(!Array.isArray(e))throw un(`${t} must be an array`);return e}function zg(e,t,n){let r=new Set;for(let i of e){let o=t(i).toLowerCase();if(r.has(o))throw un(`${n} names one item twice`);r.add(o)}return[...e].sort((i,o)=>(0,ze.byCodeUnit)(t(i).toLowerCase(),t(o).toLowerCase()))}function GL(e){let t=e;if(!t||typeof t.inflateRaw!="function"||typeof t.sha256!="function")throw(0,ze.promotionError)("PROMOTION_CODEC_REQUIRED","preflight");return t}we.requireCodec=GL;function jL(e){if(e===void 0)return{...ze.DEFAULT_LIMITS};let t=ki(e,[],Object.keys(ze.DEFAULT_LIMITS),"limits"),n={...ze.DEFAULT_LIMITS};for(let r of Object.keys(t)){let i=t[r];if(i!==void 0){if(typeof i!="number"||!Number.isSafeInteger(i)||i<=0)throw un("a limit must be a positive safe integer");n[r]=i}}return n}we.readLimits=jL;function Fre(e){let t=ki(e,["kind","identity","businessUnit"],[],"a requirement role");if(t.kind!=="role"||t.businessUnit!=="root")throw un("a requirement role must be a root role identity");let n=ki(t.identity,["scheme"],["templateId","packageRoleId"],"a role identity"),r=(0,ze.canonicalGuid)(n.scheme==="template"?n.templateId:n.packageRoleId);if(!r||n.scheme!=="template"&&n.scheme!=="package")throw un("a role identity must be a template or package role GUID");return{kind:"role",identity:n.scheme==="template"?{scheme:"template",templateId:r}:{scheme:"package",packageRoleId:r},businessUnit:"root"}}function Ure(e){var t,n,r;let i=Hg(e)?e.kind:void 0,o=(a,s)=>{if(typeof a!="string"||!s.includes(a))throw un("requiredBefore is not a supported phase");return a};if(i==="organizationSetting"){let a=ki(e,["id","kind","settingUniqueName","expectedValue","requiredBefore"],[],"a requirement");if(typeof a.expectedValue!="string")throw un("a requirement expectedValue must be a string");return{id:es(a.id,"a requirement id"),kind:i,settingUniqueName:es(a.settingUniqueName,"a requirement setting"),expectedValue:a.expectedValue,requiredBefore:o(a.requiredBefore,["import","completion"])}}if(i==="roleAssignment"){let a=ki(e,["id","kind","role","principal","requiredBefore"],[],"a requirement"),s=Hg(a.principal)?a.principal:{},u;if(s.kind==="user")ki(s,["kind","aadObjectId"],[],"a principal"),u={kind:"user",aadObjectId:(t=(0,ze.canonicalGuid)(s.aadObjectId))!==null&&t!==void 0?t:gA("a principal id")};else if(s.kind==="groupTeam")ki(s,["kind","aadGroupObjectId"],[],"a principal"),u={kind:"groupTeam",aadGroupObjectId:(n=(0,ze.canonicalGuid)(s.aadGroupObjectId))!==null&&n!==void 0?n:gA("a principal id")};else if(s.kind==="targetTeam")ki(s,["kind","teamId"],[],"a principal"),u={kind:"targetTeam",teamId:(r=(0,ze.canonicalGuid)(s.teamId))!==null&&r!==void 0?r:gA("a principal id")};else throw un("a requirement principal is not a user, group team or target team");return{id:es(a.id,"a requirement id"),kind:i,role:Fre(a.role),principal:u,requiredBefore:o(a.requiredBefore,["completion"])}}if(i==="manual"){let a=ki(e,["id","kind","desiredState","requiredBefore"],[],"a requirement");return{id:es(a.id,"a requirement id"),kind:i,desiredState:es(a.desiredState,"a manual requirement desiredState"),requiredBefore:o(a.requiredBefore,["import","completion"])}}throw un("a requirement kind is not supported")}function gA(e){throw un(`${e} is not a GUID`)}function qre(e){var t,n,r;if(!Hg(e))throw un("the input must be an object");let i=GL(e.codec);for(let l of Object.keys(e))if(xre.has(l))throw(0,ze.promotionError)("PROMOTION_UPGRADE_NOT_SUPPORTED","preflight");if(ki(e,["packageBase64","appUniqueName","values","connections","requirements","overwriteUnmanagedCustomizations","publishWorkflows","codec"],[...Mre],"the input"),typeof e.packageBase64!="string"||e.packageBase64.length===0)throw un("packageBase64 must be a non-empty string");if(e.mode!==void 0&&e.mode!=="managed"&&e.mode!=="unmanaged")throw un("mode must be 'managed' or 'unmanaged'");let o=zg(Wg(e.values,"values").map(l=>{let c=ki(l,["schemaName","value"],[],"a value");if(typeof c.value!="string")throw un("a value must be a string");return{schemaName:es(c.schemaName,"a value schemaName"),value:c.value}}),l=>l.schemaName,"values"),a=zg(Wg(e.connections,"connections").map(l=>{let c=ki(l,["logicalName","connectionId"],[],"a connection");if(typeof c.connectionId!="string"||c.connectionId.trim()!==c.connectionId)throw un("a connectionId must be a string without surrounding whitespace");return{logicalName:es(c.logicalName,"a connection logicalName"),connectionId:c.connectionId}}),l=>l.logicalName,"connections"),s=zg(e.settingOverrides===void 0?[]:Wg(e.settingOverrides,"settingOverrides").map(l=>{let c=ki(l,["settingUniqueName","value"],[],"a setting override");if(typeof c.value!="string")throw un("a setting override value must be a string");return{settingUniqueName:es(c.settingUniqueName,"a setting name"),value:c.value}}),l=>l.settingUniqueName,"settingOverrides"),u=zg(Wg(e.requirements,"requirements").map(Ure),l=>l.id,"requirements");return{codec:i,packageBase64:e.packageBase64,limits:jL(e.limits),intent:{appUniqueName:es(e.appUniqueName,"appUniqueName"),mode:(t=e.mode)!==null&&t!==void 0?t:"managed",values:o,connections:a,settingOverrides:s,requirements:u,overwriteUnmanagedCustomizations:jg(e.overwriteUnmanagedCustomizations,"overwriteUnmanagedCustomizations",!1),publishWorkflows:jg(e.publishWorkflows,"publishWorkflows",!1),acknowledgeNonAtomicImport:(n=jg(e.acknowledgeNonAtomicImport,"acknowledgeNonAtomicImport",!0))!==null&&n!==void 0?n:!1,publishApp:(r=jg(e.publishApp,"publishApp",!0))!==null&&r!==void 0?r:!1}}}we.readPlanInput=qre;var Bre=(e,t)=>e.roles.some(n=>n.id===t)?{kind:"role",identity:{scheme:"package",packageRoleId:t},businessUnit:"root"}:{kind:"role",identity:{scheme:"template",templateId:t},businessUnit:"root"};we.roleIdentity=Bre;var Vre=/^\/subscriptions\/[0-9a-fA-F-]{36}\/resourceGroups\/[^/]+\/providers\/Microsoft\.KeyVault\/vaults\/[^/]+\/secrets\/[^/]+$/;async function Gre(e,t,n,r,i){var o,a,s,u,l,c,d;let f=[...i.findings],p=[],m={kind:"solution",uniqueName:e.solutionUniqueName},h=v=>p.push(v);t.mode==="managed"!==e.managed?f.push((0,we.refusal)("PROMOTION_PACKAGE_MODE_MISMATCH",{subject:m})):t.mode==="unmanaged"&&!n.unmanagedImport&&f.push((0,we.refusal)("PROMOTION_VERIFICATION_UNAVAILABLE",{subject:m,reason:"unmanaged import is not certified"})),t.acknowledgeNonAtomicImport!==!0&&f.push((0,we.refusal)("PROMOTION_NON_ATOMIC_IMPORT_NOT_ACKNOWLEDGED",{subject:m})),t.publishWorkflows&&f.push((0,we.refusal)("PROMOTION_VERIFICATION_UNAVAILABLE",{subject:m,reason:"no certified process activation reader"}));let g=e.apps.find(v=>v.uniqueName.toLowerCase()===t.appUniqueName.toLowerCase()),y={kind:"app",uniqueName:(o=g?.uniqueName)!==null&&o!==void 0?o:t.appUniqueName};g||f.push((0,we.refusal)("PROMOTION_APP_NOT_IN_PACKAGE",{subject:y})),t.publishApp&&f.push((0,we.refusal)("PROMOTION_PUBLICATION_SCOPE_UNKNOWN",{subject:y}));for(let v of t.settingOverrides){let N={kind:"appSetting",appUniqueName:y.uniqueName,settingUniqueName:v.settingUniqueName};f.push((0,we.refusal)("PROMOTION_VERIFICATION_UNAVAILABLE",{subject:N,reason:"app setting overrides are not certified"})),t.publishApp||f.push((0,we.refusal)("PROMOTION_PUBLISH_REQUIRED",{subject:N}))}let b=new Set(((a=g?.sitemapNames)!==null&&a!==void 0?a:[]).map(v=>v.toLowerCase())),E={sitemaps:b,roles:new Set((s=g?.roleIds)!==null&&s!==void 0?s:[]),icon:(u=g?.iconWebResourceId)!==null&&u!==void 0?u:null,webResources:new Set(e.sitemaps.filter(v=>b.has(v.uniqueName.toLowerCase())).flatMap(v=>v.webResources.map(N=>N.toLowerCase())))},w=v=>v?"namedApp":"packageExtra";h({coverageId:"C32",subject:m,relevance:"namedApp",delivery:"solution",complete:!0,checks:[{subject:m,aspect:"definition",expected:{version:e.version,managed:e.managed,publisherUniqueName:e.publisherUniqueName,fields:e.solutionFields},verifierVersion:"solution-v2"}]});let _={kind:"publisher",uniqueName:e.publisherUniqueName};h({coverageId:"C32",subject:_,relevance:"dependency",delivery:"solution",complete:!0,checks:[{subject:_,aspect:"presence",expected:{prefix:e.publisherPrefix,fields:e.publisherFields},verifierVersion:"publisher-v2"}]}),t.publishWorkflows||h({coverageId:"C28",subject:m,relevance:"namedApp",delivery:"solution",complete:!0,checks:[{subject:m,aspect:"activation",expected:{policy:"noActivationRequest"},verifierVersion:"activation-trace-v1"}]});for(let v of e.apps){let N={kind:"app",uniqueName:v.uniqueName},S=v===g,R=v.iconWebResourceId?e.webResources.find(G=>G.id===v.iconWebResourceId):void 0,x=v.sitemapNames.some(G=>!e.sitemaps.some(U=>U.uniqueName.toLowerCase()===G.toLowerCase()));(x||v.iconWebResourceId&&!R)&&f.push((0,we.refusal)("PROMOTION_COVERAGE_GAP",{subject:N,reason:"an app reference is not in the package"})),h({coverageId:"C01",subject:N,relevance:w(S),delivery:x||v.iconWebResourceId&&!R?"refused":"solution",complete:!(x||v.iconWebResourceId&&!R),checks:[{subject:N,aspect:"definition",expected:{icon:R?R.name:null,fields:v.fields},verifierVersion:"app-v2"},{subject:N,aspect:"references",expected:{sitemaps:v.sitemapNames,otherComponents:0},verifierVersion:"app-components-v1"}]}),h({coverageId:"C23",subject:N,relevance:w(S),delivery:"solution",complete:!0,checks:[{subject:N,aspect:"references",expected:{roles:v.roleIds.map(G=>(0,ze.identityKey)((0,we.roleIdentity)(e,G))).sort(ze.byCodeUnit)},verifierVersion:"app-roles-v1"}]});for(let G of v.roleIds.filter(U=>!e.roles.some(M=>M.id===U))){let U=(0,we.roleIdentity)(e,G);h({coverageId:"C23",subject:U,relevance:"dependency",delivery:"existingTarget",complete:!0,checks:[{subject:U,aspect:"presence",expected:{present:!0},verifierVersion:"template-role-v1"}]})}for(let G of v.settings){let U={kind:"appSetting",appUniqueName:v.uniqueName,settingUniqueName:G.definition};if(kre(G)){f.push((0,we.refusal)("PROMOTION_COVERAGE_GAP",{subject:U,reason:"a theme pointer is not certified"})),h({coverageId:"C16",subject:U,relevance:w(S),delivery:"refused",complete:!1,checks:[]});continue}h({coverageId:"C03",subject:U,relevance:w(S),delivery:"solution",complete:!0,checks:[{subject:U,aspect:"setting",expected:{value:G.value,fields:G.fields},verifierVersion:"app-setting-v2"}]});let M={kind:"settingDefinition",uniqueName:G.definition};p.some(q=>q.coverageId==="C05"&&(0,ze.identityKey)(q.subject)===(0,ze.identityKey)(M))||h({coverageId:"C05",subject:M,relevance:"dependency",delivery:"existingTarget",complete:!0,checks:[{subject:M,aspect:"presence",expected:{present:!0},verifierVersion:"setting-definition-v1"}]})}}let I=(v,N,S)=>({coverageId:v,subject:N,relevance:"dependency",delivery:"existingTarget",complete:!0,checks:[{subject:N,aspect:"presence",expected:{present:!0},verifierVersion:S}]}),T=(v,N)=>p.some(S=>S.coverageId===v&&(0,ze.identityKey)(S.subject)===(0,ze.identityKey)(N));for(let v of e.sitemaps){let N={kind:"sitemap",uniqueName:v.uniqueName};h({coverageId:"C02",subject:N,relevance:w(E.sitemaps.has(v.uniqueName.toLowerCase())),delivery:"solution",complete:!0,checks:[{subject:N,aspect:"definition",expected:{canonicalDigest:await(0,ze.digestOf)(r,v.canonicalXml),fields:v.fields},verifierVersion:"sitemap-v2"}]});for(let S of v.webResources){let R={kind:"webResource",name:S};!e.webResources.some(x=>x.name.toLowerCase()===S.toLowerCase())&&!T("C15",R)&&h(I("C15",R,"web-resource-presence-v1"))}for(let S of v.tables){let R={kind:"table",logicalName:S};T("C32",R)||h(I("C32",R,"table-presence-v1"))}}for(let v of e.webResources){let N={kind:"webResource",name:v.name};h({coverageId:"C15",subject:N,relevance:w(E.icon===v.id||E.webResources.has(v.name.toLowerCase())),delivery:"solution",complete:!0,checks:[{subject:N,aspect:"bytes",expected:{sha256:await(0,ze.sha256Of)(r,v.bytes),type:v.type,fields:v.fields},verifierVersion:"web-resource-v2"}]})}for(let v of e.searches){if(!e.apps.some(S=>S.uniqueName.toLowerCase()===v.appUniqueName.toLowerCase()))continue;let N={kind:"appSearch",packageId:v.id,appUniqueName:v.appUniqueName};h({coverageId:"C31",subject:N,relevance:w(v.appUniqueName.toLowerCase()===g?.uniqueName.toLowerCase()),delivery:"solution",complete:!0,checks:[{subject:N,aspect:"definition",expected:{fields:v.fields,member:!0},verifierVersion:"app-search-v2"}]})}for(let v of t.values)e.variables.some(N=>N.schemaName.toLowerCase()===v.schemaName.toLowerCase())||f.push((0,we.refusal)("INVALID_ARGUMENT",{subject:{kind:"environmentVariable",schemaName:v.schemaName},reason:"not a variable of the package"}));for(let v of e.variables){let N={kind:"environmentVariable",schemaName:v.schemaName},S=t.values.find(U=>U.schemaName.toLowerCase()===v.schemaName.toLowerCase()),R=v.type===Dre.SECRET_TYPE,x=!1;R&&(v.hasCurrentValue||((l=v.defaultValue)!==null&&l!==void 0?l:"")!=="")&&(f.push((0,we.refusal)("PROMOTION_SECRET_VALUE",{subject:N})),x=!0);let G=v.isRequired||v.hasCurrentValue;if(G&&(!S||S.value==="")?(f.push((0,we.refusal)("PROMOTION_VALUE_REQUIRED",{subject:N})),x=!0):!G&&S&&S.value===""&&(f.push((0,we.refusal)("INVALID_ARGUMENT",{subject:N,reason:"an empty value is not a clear"})),x=!0),R&&S&&S.value!=="")Vre.test(S.value)?n.secretReferences||(f.push((0,we.refusal)("PROMOTION_VERIFICATION_UNAVAILABLE",{subject:N,reason:"Key Vault reference parameters are not certified"})),x=!0):(f.push((0,we.refusal)("PROMOTION_SECRET_VALUE",{subject:N,reason:"a Secret input must be a Key Vault reference"})),x=!0);else if(S&&S.value!==""){let U=BL.ENVIRONMENT_VARIABLE_TYPES[v.type-1e8];(0,BL.valueTypeProblem)(U,S.value)!==void 0&&(f.push((0,we.refusal)("INVALID_ARGUMENT",{subject:N,reason:`the value is not a valid ${U} value`})),x=!0)}h({coverageId:"C19",subject:N,relevance:"packageExtra",delivery:"solution",complete:!0,checks:[{subject:N,aspect:"definition",expected:{type:v.type,isRequired:v.isRequired,defaultValueDigest:await(0,ze.digestOf)(r,v.defaultValue),fields:v.fields},verifierVersion:"variable-v2"}]}),S&&S.value!==""&&h({coverageId:"C20",subject:N,relevance:"packageExtra",delivery:x?"refused":"parameter",complete:!x,checks:[{subject:N,aspect:"setting",expected:{valueDigest:await(0,ze.digestOf)(r,S.value)},verifierVersion:"variable-value-v1"}]})}for(let v of t.connections)e.references.some(N=>N.logicalName.toLowerCase()===v.logicalName.toLowerCase())||f.push((0,we.refusal)("INVALID_ARGUMENT",{subject:{kind:"connectionReference",logicalName:v.logicalName},reason:"not a connection reference of the package"}));for(let v of e.references){let N={kind:"connectionReference",logicalName:v.logicalName},S=t.connections.find(x=>x.logicalName.toLowerCase()===v.logicalName.toLowerCase()),R=!S||S.connectionId==="";R&&f.push((0,we.refusal)("PROMOTION_CONNECTION_UNMAPPED",{subject:N})),n.connectionReferences||f.push((0,we.refusal)("PROMOTION_VERIFICATION_UNAVAILABLE",{subject:N,reason:"bound connection references are not certified"})),h({coverageId:"C21",subject:N,relevance:"packageExtra",delivery:R?"refused":"parameter",complete:!R&&n.connectionReferences,checks:R?[]:[{subject:N,aspect:"references",expected:{connectorId:v.connectorId.toLowerCase(),connectionId:S.connectionId,fields:v.fields},verifierVersion:"connection-reference-v2"}]})}for(let v of e.roles){if(i.refusedRoles.has(v.id)){h({coverageId:"C22",subject:{kind:"unsupportedComponent",componentType:20,packageId:v.id},relevance:w(E.roles.has(v.id)),delivery:"refused",complete:!1,checks:[]});continue}let N=(0,we.roleIdentity)(e,v.id);h({coverageId:"C22",subject:N,relevance:w(E.roles.has(v.id)),delivery:"solution",complete:!0,checks:[{subject:N,aspect:"presence",expected:{businessUnit:"root",name:v.name,fields:v.fields},verifierVersion:"role-v2"},{subject:N,aspect:"privileges",expected:{privileges:v.privileges},verifierVersion:"role-privileges-v1"}]})}for(let v of e.dependencies){if(v.type==="SettingDefinition"&&v.uniqueName){let R={kind:"settingDefinition",uniqueName:v.uniqueName};T("C05",R)||h(I("C05",R,"setting-definition-v1"));continue}let N=v.type==="EnvironmentVariableDefinition"&&v.schemaName,S=N?{kind:"environmentVariable",schemaName:v.schemaName}:{kind:"unsupportedComponent",componentType:0,packageId:(d=(c=v.schemaName)!==null&&c!==void 0?c:v.uniqueName)!==null&&d!==void 0?d:v.id};N||f.push((0,we.refusal)("PROMOTION_DEPENDENCY_IDENTITY_UNRESOLVED",{subject:S})),h({coverageId:"C32",subject:S,relevance:"dependency",delivery:N?"existingTarget":"refused",complete:!!N,checks:N?[{subject:S,aspect:"presence",expected:{present:!0},verifierVersion:"dependency-v1"}]:[]})}for(let v of e.gaps)f.push((0,we.refusal)("PROMOTION_COVERAGE_GAP",{subject:v.subject,reason:v.reason})),h({coverageId:"C42",subject:v.subject,relevance:"packageExtra",delivery:"refused",complete:!1,checks:[]});let O=[];for(let v of t.requirements){let N={kind:"requirement",requirementId:v.id};v.requiredBefore==="import"&&f.push((0,we.refusal)("PROMOTION_VERIFICATION_UNAVAILABLE",{reason:"no certified reader for a before-import requirement"}));let S=v.kind==="roleAssignment"?"assignment":v.kind==="organizationSetting"?"setting":"manual",R=v.kind==="roleAssignment"?{role:(0,ze.identityKey)(v.role),principal:(0,ze.identityKey)(v.principal)}:v.kind==="organizationSetting"?{settingUniqueName:v.settingUniqueName,expectedValue:v.expectedValue}:{desiredState:v.desiredState},x={subject:N,aspect:S,expected:R,verifierVersion:"requirement-manual-v1"};h({coverageId:v.kind==="roleAssignment"?"C33":"C34",subject:N,relevance:"callerRequirement",delivery:"manual",complete:v.requiredBefore!=="import",checks:[x]}),O.push({requirementId:v.id,checks:[x]})}return{...jre(p,O),findings:f}}we.buildRecipe=Gre;function jre(e,t){let n=[...e].sort((s,u)=>(0,ze.byCodeUnit)(s.coverageId,u.coverageId)||(0,ze.byCodeUnit)((0,ze.identityKey)(s.subject),(0,ze.identityKey)(u.subject))),r=[],i=new Map,o=n.map((s,u)=>{let l=[...s.checks].sort((c,d)=>(0,ze.byCodeUnit)((0,ze.identityKey)(c.subject),(0,ze.identityKey)(d.subject))||(0,ze.byCodeUnit)(c.aspect,d.aspect)).map(c=>{let d=`chk-${r.length+1}`;return i.set(c,d),r.push({id:d,coverageId:s.coverageId,subject:c.subject,aspect:c.aspect,expected:c.expected,required:!0,verifierVersion:c.verifierVersion}),d});return{id:`cov-${u+1}`,coverageId:s.coverageId,subject:s.subject,relevance:s.relevance,delivery:s.delivery,required:!0,checks:l,complete:s.complete}}),a=t.sort((s,u)=>(0,ze.byCodeUnit)(s.requirementId,u.requirementId)).map((s,u)=>({id:`step-${u+1}`,kind:"manual",requirementId:s.requirementId,required:!0,checkIds:s.checks.map(l=>i.get(l))}));return{coverage:o,checks:r,steps:a}}});var bA=C(or=>{"use strict";Object.defineProperty(or,"__esModule",{value:!0});or.verifyChecks=or.readStageAnswer=or.UNREADABLE_STAGE=or.sameObservations=or.observeTarget=or.correspondSource=or.judgeSource=void 0;var yA=Y(),Ue=Kg(),sa=Pg(),Ae=Ya(),Jg="promotion-target-v2",sl={app:"AppModule",sitemap:"SiteMap",webResource:"WebResource",variable:"EnvironmentVariableDefinition",reference:"connectionreference",role:"Role",search:"DVTableSearch"},Wre={61:["webresourceset","name",(e,t)=>e.webResources.some(n=>n.name===t)],62:["sitemaps","sitemapnameunique",(e,t)=>e.sitemaps.some(n=>n.uniqueName===t)],80:["appmodules","uniquename",(e,t)=>e.apps.some(n=>n.uniqueName===t)],380:["environmentvariabledefinitions","schemaname",(e,t)=>e.variables.some(n=>n.schemaName===t)]},zre=381;async function Hre(e,t){let n=[],r=new Set,i={kind:"solution",uniqueName:e.solutionUniqueName},o=l=>n.push((0,Ue.refusal)("PROMOTION_SOURCE_PACKAGE_MISMATCH",{subject:i,reason:l})),a=await t.solution(e.solutionUniqueName);if(a.state==="unreadable")n.push((0,Ue.unknown)({subject:i,reason:"the source solution could not be read"}));else if(a.state==="absent")o("no such source solution");else{let l=a.value,c=(0,Ae.parseVersion)(l.version);l.publisherUniqueName.toLowerCase()!==e.publisherUniqueName.toLowerCase()&&o("another publisher"),(!c||(0,Ae.compareVersions)(c,(0,Ae.parseVersion)(e.version))!==0)&&o("another version");let d=await t.members(l.id);if(!d)n.push((0,Ue.unknown)({subject:i,reason:"the source solution members could not be read"}));else for(let f of[...d].sort((p,m)=>(0,Ae.byCodeUnit)(p.id,m.id)))await Kre(e,t,f,n,o)}let s=await t.rootBusinessUnit();for(let l of e.roles){let c=await t.role(l.id);(!s||c.state!=="present"||c.value.businessUnitId!==s)&&(r.add(l.id),n.push((0,Ue.refusal)("PROMOTION_COVERAGE_GAP",{subject:{kind:"unsupportedComponent",componentType:20,packageId:l.id},reason:"the role is not provably a root business unit role"})))}let u=new Set;for(let l of e.apps)for(let c of l.roleIds)e.roles.some(d=>d.id===c)||u.add(c);for(let l of[...u].sort(Ae.byCodeUnit)){let c=await t.templateRole(l);c.state==="unreadable"?n.push((0,Ue.unknown)({subject:(0,Ue.roleIdentity)(e,l),reason:"a source template role could not be read"})):c.state==="absent"&&n.push((0,Ue.refusal)("PROMOTION_DEPENDENCY_IDENTITY_UNRESOLVED",{subject:(0,Ue.roleIdentity)(e,l)}))}return{refusedRoles:r,findings:n}}or.judgeSource=Hre;async function Kre(e,t,n,r,i){let o={kind:"solution",uniqueName:e.solutionUniqueName},a=()=>r.push((0,Ue.unknown)({subject:o,reason:"a source member could not be named"}));if(n.type===20){e.roles.some(f=>f.id===n.id)||i("a source role member is not in the package");return}if(n.type===zre)return;let s=Wre[n.type];if(s){let f=await t.fieldById(s[0],n.id,s[1]);f.state==="unreadable"?a():(f.state==="absent"||!s[2](e,f.value))&&i("a source member is not in the package");return}let[u,l,c]=[await t.componentType("connectionreference"),await t.componentType("appsetting"),await t.componentType("dvtablesearch")],d=f=>f.state==="present"&&f.value===n.type;if(d(u)){let f=await t.fieldById("connectionreferences",n.id,"connectionreferencelogicalname");f.state==="unreadable"?a():(f.state==="absent"||!e.references.some(p=>p.logicalName===f.value))&&i("a source member is not in the package");return}if(d(l)){let f=await t.byId("appsettings",n.id,"_parentappmoduleid_value,_settingdefinitionid_value"),p=f.state==="present"?(0,Ae.canonicalGuid)(f.value._parentappmoduleid_value):void 0,m=f.state==="present"?(0,Ae.canonicalGuid)(f.value._settingdefinitionid_value):void 0,h=p?await t.fieldById("appmodules",p,"uniquename"):void 0,g=m?await t.fieldById("settingdefinitions",m,"uniquename"):void 0;f.state==="absent"?i("a source member is not in the package"):h?.state!=="present"||g?.state!=="present"?a():e.apps.some(y=>y.uniqueName===h.value&&y.settings.some(b=>b.definition===g.value))||i("a source member is not in the package");return}if(d(c)){e.searches.some(f=>f.id===n.id)||i("a source member is not in the package");return}if([u,l,c].some(f=>f.state==="unreadable")){a();return}r.push((0,Ue.refusal)("PROMOTION_COVERAGE_GAP",{subject:{kind:"unsupportedComponent",componentType:n.type,packageId:n.id},reason:"a source member of a kind without a certified provider"}))}async function Jre(e,t,n,r){let i=[],o=(a,s)=>{let u={...s};return a.subject.kind==="solution"&&delete u.managed,a.subject.kind==="connectionReference"&&delete u.connectionId,u};for(let a of e){let s=a.expected;if(a.subject.kind==="requirement"||a.aspect==="activation"||a.coverageId==="C20"||a.aspect==="presence"&&s?.present===!0)continue;let u=a.subject,l;try{l=await WL(a,t,n,r)}catch(c){if(c instanceof yA.PromotionError&&c.code==="PROMOTION_READ_BUDGET_EXCEEDED")throw c;l=void 0}l===void 0?i.push((0,Ue.unknown)({subject:u,reason:"the source could not be read"})):(0,Ae.canonicalJson)(o(a,l))!==(0,Ae.canonicalJson)(o(a,s))&&i.push((0,Ue.refusal)("PROMOTION_SOURCE_PACKAGE_MISMATCH",{subject:u,reason:"the source differs from its package"}))}return i}or.correspondSource=Jre;async function Yre(e,t,n,r,i,o){let a=[],s=[],u={kind:"solution",uniqueName:e.solutionUniqueName},l={state:"unreadable",reasonCode:"PROMOTION_VERIFICATION_UNAVAILABLE"},c=await n.solution(e.solutionUniqueName),d="undetermined",f,p=!1;if(c.state==="unreadable")a.push((0,Ue.unknown)({subject:u,reason:"the target solution could not be read"})),s.push({subject:u,purpose:"affected",image:l});else if(c.state==="absent")d="install",s.push({subject:u,purpose:"affected",image:{state:"absent"}});else{let v=c.value,N=await n.patches(v.id);N?N.length>0&&(a.push((0,Ue.refusal)("PROMOTION_HOLDING_PRESENT",{subject:u,reason:"the solution has patches"})),p=!0):a.push((0,Ue.unknown)({subject:u,reason:"patches could not be read"})),v.publisherUniqueName.toLowerCase()!==e.publisherUniqueName.toLowerCase()&&(a.push((0,Ue.refusal)("PROMOTION_PUBLISHER_MISMATCH",{subject:u})),p=!0),v.managed!==e.managed&&(a.push((0,Ue.refusal)("PROMOTION_TARGET_MODE_MISMATCH",{subject:u})),p=!0);let S=(0,Ae.parseVersion)(v.version);(!S||(0,Ae.compareVersions)((0,Ae.parseVersion)(e.version),S)<=0)&&(a.push((0,Ue.refusal)("PROMOTION_VERSION_REFUSED",{subject:u})),p=!0);let R=await n.members(v.id);f=R?new Set(R.map(x=>x.id)):void 0,R||a.push((0,Ue.unknown)({subject:u,reason:"the target solution members could not be read"})),d=p?"undetermined":"update",s.push({subject:u,purpose:"affected",image:{state:"present",projectionVersion:Jg,contentDigest:await(0,Ae.digestOf)(r,{version:v.version,managed:v.managed,publisher:v.publisherUniqueName.toLowerCase(),prefix:v.publisherPrefix,fields:v.fields,publisherFields:v.publisherFields,patches:N??null,members:R?R.map(x=>`${x.type}:${x.id}`).sort(Ae.byCodeUnit):null}),layerDigest:null,versions:[{entitySet:"solutions",id:v.id,etag:v.etag}]}})}let m=`${e.solutionUniqueName}_Upgrade`,h=await n.solution(m),g={kind:"solution",uniqueName:m};h.state==="unreadable"?(a.push((0,Ue.unknown)({subject:g,reason:"the holding solution could not be read"})),s.push({subject:g,purpose:"affected",image:l})):(h.state==="present"&&(a.push((0,Ue.refusal)("PROMOTION_HOLDING_PRESENT",{subject:g})),d="undetermined"),s.push({subject:g,purpose:"affected",image:h.state==="absent"?{state:"absent"}:{state:"present",projectionVersion:Jg,contentDigest:await(0,Ae.digestOf)(r,{version:h.value.version}),layerDigest:null,versions:[{entitySet:"solutions",id:h.value.id,etag:h.value.etag}]}}));let y=async(v,N,S)=>{if(S.state==="unreadable"){a.push((0,Ue.unknown)({subject:v,reason:"a target component could not be read"})),s.push({subject:v,purpose:"affected",image:l});return}if(S.state==="absent"){s.push({subject:v,purpose:"affected",image:{state:"absent"}});return}let R=null;if(c.state==="absent")a.push((0,Ue.refusal)("PROMOTION_COMPONENT_COLLISION",{subject:v}));else if(c.state==="present"){f&&!f.has(S.value.id)&&a.push((0,Ue.refusal)("PROMOTION_COMPONENT_COLLISION",{subject:v,reason:"not a component of the target solution"}));let x=await n.topLayer(N,S.value.id);x.state!=="present"?a.push((0,Ue.unknown)({subject:v,reason:"its solution layers could not be read"})):(R=x.value.digest,x.value.top.toLowerCase()!==e.solutionUniqueName.toLowerCase()&&a.push((0,Ue.refusal)("PROMOTION_COMPONENT_COLLISION",{subject:v,reason:"another layer is on top"})))}s.push({subject:v,purpose:"affected",image:{state:"present",projectionVersion:Jg,contentDigest:await(0,Ae.digestOf)(r,S.value.digestInput),layerDigest:R,versions:S.value.versions}})},b=(v,N)=>v.state==="present"?{state:"present",value:N(v.value)}:v;for(let v of e.apps){let N=await n.app(v.uniqueName,!0);await y({kind:"app",uniqueName:v.uniqueName},sl.app,b(N,S=>({id:S.id,digestInput:{...S,etag:void 0,settings:S.settings.map(R=>[R.definition,R.value,R.fields])},versions:[{entitySet:"appmodules",id:S.id,etag:S.etag},...S.settings.map(R=>({entitySet:"appsettings",id:R.id,etag:R.etag}))]})))}for(let v of e.sitemaps){let N=await n.sitemap(v.uniqueName,!0);await y({kind:"sitemap",uniqueName:v.uniqueName},sl.sitemap,b(N,S=>({id:S.id,digestInput:{canonical:S.canonical,fields:S.fields},versions:[{entitySet:"sitemaps",id:S.id,etag:S.etag}]})))}for(let v of e.webResources){let N=await n.webResource(v.name);await y({kind:"webResource",name:v.name},sl.webResource,b(N,S=>({id:S.id,digestInput:{type:S.type,sha256:S.sha256,fields:S.fields},versions:[{entitySet:"webresourceset",id:S.id,etag:S.etag}]})))}for(let v of e.variables){let N=await n.variable(v.schemaName);await y({kind:"environmentVariable",schemaName:v.schemaName},sl.variable,b(N,S=>({id:S.id,digestInput:{type:S.type,isRequired:S.isRequired,defaultValue:S.defaultValue,fields:S.fields,values:S.values},versions:[{entitySet:"environmentvariabledefinitions",id:S.id,etag:S.etag},...S.values.map(R=>({entitySet:"environmentvariablevalues",id:R.id,etag:R.etag}))]})))}for(let v of e.references){let N=await n.reference(v.logicalName);await y({kind:"connectionReference",logicalName:v.logicalName},sl.reference,b(N,S=>({id:S.id,digestInput:{connectorId:S.connectorId,connectionId:S.connectionId,fields:S.fields},versions:[{entitySet:"connectionreferences",id:S.id,etag:S.etag}]})))}for(let v of e.roles){let N=await n.role(v.id),S=N.state==="present"?{state:"unreadable"}:N;if(N.state==="present"){let R=await n.rolePrivileges(v.id),x=N.value;S=R?{state:"present",value:{id:x.id,digestInput:{businessUnitId:x.businessUnitId,templateId:x.templateId,name:x.name,fields:x.fields,privileges:R},versions:[{entitySet:"roles",id:x.id,etag:x.etag}]}}:{state:"unreadable"}}await y((0,Ue.roleIdentity)(e,v.id),sl.role,S)}for(let v of e.searches){let N=await n.search(v.id);await y({kind:"appSearch",packageId:v.id,appUniqueName:v.appUniqueName},sl.search,b(N,S=>({id:S.id,digestInput:{fields:S.fields},versions:[{entitySet:"dvtablesearchs",id:S.id,etag:S.etag}]})))}let E=async(v,N,S)=>{if(N.state==="unreadable"){a.push((0,Ue.unknown)({subject:v,reason:"a prerequisite could not be read"})),s.push({subject:v,purpose:"dependency",image:l});return}if(N.state==="absent"){a.push((0,Ue.refusal)(S,{subject:v})),s.push({subject:v,purpose:"dependency",image:{state:"absent"}});return}s.push({subject:v,purpose:"dependency",image:{state:"present",projectionVersion:Jg,contentDigest:await(0,Ae.digestOf)(r,N.value),layerDigest:null,versions:[]}})},w=new Set,_=new Set;for(let v of e.apps)v.roleIds.filter(N=>!e.roles.some(S=>S.id===N)).forEach(N=>w.add(N)),v.settings.forEach(N=>_.add(N.definition));for(let v of e.dependencies)v.type==="SettingDefinition"&&v.uniqueName&&_.add(v.uniqueName);for(let v of[...w].sort(Ae.byCodeUnit))await E((0,Ue.roleIdentity)(e,v),await n.templateRole(v),"PROMOTION_DEPENDENCY_MISSING");for(let v of[..._].sort(Ae.byCodeUnit))await E({kind:"settingDefinition",uniqueName:v},await n.settingDefinition(v),"PROMOTION_SETTING_UNAVAILABLE");for(let v of e.dependencies){if(v.type!=="EnvironmentVariableDefinition"||!v.schemaName)continue;let N=e.variables.some(S=>{var R;return S.schemaName.toLowerCase()===((R=v.schemaName)===null||R===void 0?void 0:R.toLowerCase())});await E({kind:"environmentVariable",schemaName:v.schemaName},N?{state:"present",value:"package"}:await n.variableExists(v.schemaName),"PROMOTION_DEPENDENCY_MISSING")}let I=new Set,T=new Set;for(let v of e.sitemaps)v.webResources.filter(N=>!e.webResources.some(S=>S.name.toLowerCase()===N.toLowerCase())).forEach(N=>I.add(N)),v.tables.forEach(N=>T.add(N));for(let v of[...I].sort(Ae.byCodeUnit)){let N=await n.webResource(v);await E({kind:"webResource",name:v},N.state==="present"?{state:"present",value:{present:!0}}:N,"PROMOTION_DEPENDENCY_MISSING")}for(let v of[...T].sort(Ae.byCodeUnit))await E({kind:"table",logicalName:v},await n.tableExists(v),"PROMOTION_DEPENDENCY_MISSING");if(i){let v=e.references.map(N=>({reference:N,map:t.connections.find(S=>S.logicalName.toLowerCase()===N.logicalName.toLowerCase())})).filter(N=>N.map&&N.map.connectionId!=="");if(v.length>0){let N;try{N=o?await o():void 0}catch(S){if(S instanceof yA.PromotionError&&S.code==="PROMOTION_READ_BUDGET_EXCEEDED")throw S;N=void 0}for(let{reference:S,map:R}of v){let x={kind:"connectionReference",logicalName:S.logicalName},G=N?.find(U=>U.connectionId===R?.connectionId);N?G?G.connectorId.toLowerCase()!==S.connectorId.toLowerCase()&&a.push((0,Ue.refusal)("PROMOTION_CONNECTION_CONNECTOR_MISMATCH",{subject:x})):a.push((0,Ue.refusal)("PROMOTION_CONNECTION_NOT_IN_TARGET",{subject:x})):a.push((0,Ue.unknown)({subject:x,reason:"the target connections could not be read"}))}}}return{observations:s.sort((v,N)=>(0,Ae.byCodeUnit)(v.purpose,N.purpose)||(0,Ae.byCodeUnit)((0,Ae.identityKey)(v.subject),(0,Ae.identityKey)(N.subject))).map((v,N)=>({id:`obs-${N+1}`,subject:v.subject,purpose:v.purpose,image:v.image})),importKind:d,findings:a,solution:c}}or.observeTarget=Yre;function Qre(e,t){return(0,Ae.canonicalJson)(e)===(0,Ae.canonicalJson)(t)}or.sameObservations=Qre;or.UNREADABLE_STAGE={status:"unreadable",missing:0,validationErrors:0,apps:[],webResources:[],variables:[],references:[]};function Xre(e){var t;let n=or.UNREADABLE_STAGE,r=e?.StageSolutionResults;if(!r||typeof r!="object")return n;let i=r.StageSolutionStatus,o=(0,Ae.canonicalGuid)(r.StageSolutionUploadId),a=Array.isArray(r.MissingDependencies)?r.MissingDependencies.length:-1,s=Array.isArray(r.SolutionValidationResults)?r.SolutionValidationResults:void 0;if(a<0||!s)return n;let u=s.filter(h=>h?.SolutionValidationResultType==="Error").length;if(i==="Failed"||i===0)return{...n,status:"Failed",...o?{uploadId:o}:{},missing:a,validationErrors:u};if(i!=="Passed"&&i!==1||!o||!Array.isArray(r.SolutionComponentsDetails))return n;let l=[],c=[],d=[],f=[];for(let h of r.SolutionComponentsDetails){let g=typeof h?.ComponentTypeName=="string"?h.ComponentTypeName.toLowerCase():void 0;if(!g)return n;if(!["appmodule","webresource","environmentvariabledefinition","connectionreference"].includes(g))continue;let y=h.Attributes,b=y?.Keys,E=y?.Values;if(!Array.isArray(b)||!Array.isArray(E)||b.length!==E.length)return n;let w=I=>{let T=E[b.indexOf(I)];return b.includes(I)&&typeof T=="string"?T:null},_=typeof h.ComponentName=="string"?h.ComponentName:null;if(g==="appmodule"){let I=(t=w("uniquename"))!==null&&t!==void 0?t:_;if(!I)return n;l.push(I.toLowerCase())}else if(g==="webresource"){if(!_)return n;c.push(_.toLowerCase())}else if(g==="environmentvariabledefinition"){let I=w("schemaname");if(!I)return n;d.push({schemaName:I.toLowerCase(),type:w("type"),isRequired:w("isrequired"),defaultValue:w("defaultvalue")})}else{let I=w("connectionreferencelogicalname");if(!I)return n;f.push({logicalName:I.toLowerCase(),connectorId:w("connectorid")})}}let p=r.SolutionDetails,m=p&&typeof p=="object"&&typeof p.SolutionUniqueName=="string"&&typeof p.PublisherUniqueName=="string"&&typeof p.IsManaged=="boolean"&&typeof p.SolutionVersion=="string"&&typeof p.IsPatchSolution=="boolean"&&typeof p.HasPendingUpgrade=="boolean"?{solutionName:p.SolutionUniqueName,publisherName:p.PublisherUniqueName,managed:p.IsManaged,version:p.SolutionVersion,patch:p.IsPatchSolution,pendingUpgrade:p.HasPendingUpgrade}:void 0;return{status:"Passed",uploadId:o,missing:a,validationErrors:u,...m?{details:m}:{},apps:l.sort(Ae.byCodeUnit),webResources:c.sort(Ae.byCodeUnit),variables:d.sort((h,g)=>(0,Ae.byCodeUnit)(h.schemaName,g.schemaName)),references:f.sort((h,g)=>(0,Ae.byCodeUnit)(h.logicalName,g.logicalName))}}or.readStageAnswer=Xre;var Zre=e=>{var t,n;return Object.keys((n=(t=e.expected)===null||t===void 0?void 0:t.fields)!==null&&n!==void 0?n:{})};async function WL(e,t,n,r){var i;let o=e.subject,a=Zre(e),s=async()=>n.solution(t.solutionUniqueName);switch(o.kind){case"solution":{let u=await s();return u.state==="unreadable"?void 0:u.state==="absent"?{absent:!0}:{version:u.value.version,managed:u.value.managed,publisherUniqueName:u.value.publisherUniqueName,fields:(0,sa.pickFields)(u.value.fields,a)}}case"publisher":{let u=await s();return u.state==="unreadable"?void 0:u.state==="absent"?{absent:!0}:{prefix:u.value.publisherPrefix,fields:(0,sa.pickFields)(u.value.publisherFields,a)}}case"app":{let u=await n.app(o.uniqueName,!1);if(u.state!=="present")return u.state==="absent"?{absent:!0}:void 0;let l=u.value;if(e.aspect==="definition"){let f=null;if(l.webResourceId){let p=await n.webResourceName(l.webResourceId);if(p.state!=="present")return;f=p.value}return{icon:f,fields:(0,sa.pickFields)(l.fields,a)}}if(e.coverageId==="C23"){let f=await n.rootBusinessUnit(),p=[];for(let m of l.roles){if(t.roles.some(g=>g.id===m)){p.push((0,Ae.identityKey)((0,Ue.roleIdentity)(t,m)));continue}let h=await n.role(m);if(h.state==="unreadable"||!f)return;p.push(h.state==="present"&&h.value.templateId&&h.value.businessUnitId===f?(0,Ae.identityKey)((0,Ue.roleIdentity)(t,h.value.templateId)):`unresolved:${m}`)}return{roles:p.sort(Ae.byCodeUnit)}}let c=[],d=0;for(let f of l.components){let[p,m]=f.split(":");if(p!=="62"){d+=1;continue}let h=await n.fieldById("sitemaps",m,"sitemapnameunique");if(h.state==="unreadable")return;c.push(h.state==="present"?h.value:`missing:${m}`)}return{sitemaps:c.sort(Ae.byCodeUnit),otherComponents:d}}case"appSetting":{let u=await n.app(o.appUniqueName,!1);if(u.state==="unreadable")return;let l=u.state==="present"?u.value.settings.find(c=>c.definition===o.settingUniqueName):void 0;return l?{value:l.value,fields:(0,sa.pickFields)(l.fields,a)}:{value:null}}case"settingDefinition":{let u=await n.settingDefinition(o.uniqueName);return u.state==="unreadable"?void 0:{present:u.state==="present"}}case"table":{let u=await n.tableExists(o.logicalName);return u.state==="unreadable"?void 0:{present:u.state==="present"}}case"sitemap":{let u=await n.sitemap(o.uniqueName,!1);return u.state==="unreadable"?void 0:u.state==="absent"?{absent:!0}:{canonicalDigest:await(0,Ae.digestOf)(r,u.value.canonical),fields:(0,sa.pickFields)(u.value.fields,a)}}case"webResource":{let u=await n.webResource(o.name);return u.state==="unreadable"?void 0:e.aspect==="presence"?{present:u.state==="present"}:u.state==="absent"?{absent:!0}:{sha256:u.value.sha256,type:u.value.type,fields:(0,sa.pickFields)(u.value.fields,a)}}case"environmentVariable":{let u=await n.variable(o.schemaName);return u.state==="unreadable"?void 0:e.aspect==="presence"?{present:u.state==="present"}:u.state==="absent"?{absent:!0}:e.aspect==="setting"?{valueDigest:u.value.values.length===1?u.value.values[0].valueDigest:null}:{type:u.value.type,isRequired:u.value.isRequired,defaultValueDigest:await(0,Ae.digestOf)(r,u.value.defaultValue),fields:(0,sa.pickFields)(u.value.fields,a)}}case"connectionReference":{let u=await n.reference(o.logicalName);return u.state==="unreadable"?void 0:u.state==="absent"?{absent:!0}:{connectorId:((i=u.value.connectorId)!==null&&i!==void 0?i:"").toLowerCase(),connectionId:u.value.connectionId,fields:(0,sa.pickFields)(u.value.fields,a)}}case"role":{if(o.identity.scheme==="template"){let d=await n.templateRole(o.identity.templateId);return d.state==="unreadable"?void 0:{present:d.state==="present"}}let u=o.identity.packageRoleId;if(e.aspect==="privileges"){let d=await n.rolePrivileges(u);return d?{privileges:d}:void 0}let l=await n.role(u),c=await n.rootBusinessUnit();return l.state==="unreadable"||!c?void 0:l.state==="absent"?{absent:!0}:{businessUnit:l.value.businessUnitId===c?"root":"other",name:l.value.name,fields:(0,sa.pickFields)(l.value.fields,a)}}case"appSearch":{let u=await n.search(o.packageId);if(u.state==="unreadable")return;if(u.state==="absent")return{absent:!0};let l=await s(),c=await n.componentType("dvtablesearch"),d=l.state==="present"?await n.members(l.value.id):void 0;if(l.state==="unreadable"||c.state==="unreadable"||l.state==="present"&&!d)return;let f=c.state==="present"&&(d??[]).some(p=>p.id===u.value.id&&p.type===c.value);return{fields:(0,sa.pickFields)(u.value.fields,a),member:f}}default:return}}async function eie(e,t,n,r,i,o){let a=[],s=!1;for(let u of e){let l=o.get(u.id);if(u.aspect==="activation"){a.push(l&&l.evidence==="attemptTrace"?l:await i(u));continue}if(u.subject.kind==="requirement"){a.push({checkId:u.id,state:"manualPending",evidence:"notAvailable"});continue}let c=u.subject,d,f;if(!s)try{d=await WL(u,t,n,r),f=d===void 0?void 0:await(0,Ae.digestOf)(r,d)}catch(m){if(!(m instanceof yA.PromotionError))throw m;s=m.code==="PROMOTION_READ_BUDGET_EXCEEDED",d=void 0}if(d===void 0||f===void 0){a.push({checkId:u.id,state:"unreadable",evidence:"notAvailable",problem:(0,Ae.promotionProblem)("PROMOTION_VERIFICATION_FAILED","verify",{subject:c,reason:"the target could not be read"})});continue}let p=(0,Ae.canonicalJson)(d)===(0,Ae.canonicalJson)(u.expected);a.push({checkId:u.id,state:p?"matched":"mismatched",evidence:"targetRead",observedDigest:f,...p?{}:{problem:(0,Ae.promotionProblem)("PROMOTION_VERIFICATION_FAILED","verify",{subject:c})}})}return a}or.verifyChecks=eie});var AA=C(Mt=>{"use strict";Object.defineProperty(Mt,"__esModule",{value:!0});Mt.planPromotion=Mt.modelOf=Mt.packageIdentity=Mt.outcomeOf=Mt.sortProblems=Mt.planDigestOf=Mt.digestInput=Mt.decodePackage=Mt.latched=Mt.readClient=Mt.IssuedPlans=void 0;var HL=Y(),tie=ia(),nie=ft(),KL=kg(),zL=zE(),hp=Kg(),vA=bA(),ua=Ya(),wA=class{constructor(t=256){this.capacity=t,this.digests=new Set}add(t){for(this.digests.delete(t),this.digests.add(t);this.digests.size>this.capacity;)this.digests.delete(this.digests.values().next().value)}has(t){return this.digests.has(t)}};Mt.IssuedPlans=wA;function EA(e,t){return e.withoutSolution().withTransport(n=>t.wrap(n)).readOnly()}Mt.readClient=EA;async function JL(e,t){let n=()=>{let i=e.flatMap(o=>o.refusedWrites);if(i.length>0)throw new HL.SdkError("PREVIEW_WRITE_REFUSED",`A promotion plan attempted ${i.length} write(s); it may only read. Nothing was written. This is a defect in the SDK.`)},r;try{r=await t()}catch(i){throw n(),i}return n(),r}Mt.latched=JL;function YL(e){if(!(e.length%4!==0||!/^[A-Za-z0-9+/]*={0,2}$/.test(e)))return(0,tie.base64ToBytes)(e)}Mt.decodePackage=YL;function QL(e){return{schemaVersion:e.schemaVersion,package:e.package,source:e.source,target:e.target,intent:e.intent,limits:e.limits,importKind:e.importKind,observations:e.observations,coverage:e.coverage,checks:e.checks,steps:e.steps,outcome:e.outcome,problems:e.problems.map(t=>{var n,r;return{code:t.code,phase:t.phase,blocking:t.blocking,subject:(n=t.subject)!==null&&n!==void 0?n:null,stepId:(r=t.stepId)!==null&&r!==void 0?r:null}})}}Mt.digestInput=QL;function XL(e,t){return(0,ua.digestOf)(e,QL(t))}Mt.planDigestOf=XL;function ZL(e){let t=new Set;return e.map(n=>n.problem).filter(n=>{var r;let i=`${n.code}\0${(0,ua.identityKey)((r=n.subject)!==null&&r!==void 0?r:null)}\0${n.message}`;return t.has(i)?!1:(t.add(i),!0)}).sort((n,r)=>{var i,o;return(0,ua.byCodeUnit)(n.code,r.code)||(0,ua.byCodeUnit)((0,ua.identityKey)((i=n.subject)!==null&&i!==void 0?i:null),(0,ua.identityKey)((o=r.subject)!==null&&o!==void 0?o:null))})}Mt.sortProblems=ZL;function eM(e,t){return e.some(n=>n.problem.blocking&&!n.unknown)?"refused":!t||e.some(n=>n.problem.blocking&&n.unknown)?"unknown":"ready"}Mt.outcomeOf=eM;function tM(e){return{sha256:e.sha256,solutionUniqueName:e.solutionUniqueName,version:e.version,managed:e.managed,publisherUniqueName:e.publisherUniqueName,publisherPrefix:e.publisherPrefix,projectionVersion:KL.PACKAGE_PROJECTION_VERSION}}Mt.packageIdentity=tM;async function nM(e,t,n){let r=YL(e);if(!r)throw(0,ua.promotionError)("PROMOTION_PACKAGE_UNREADABLE","preflight",{reason:"not base64"});return(0,KL.readPackage)(r,t,n)}Mt.modelOf=nM;async function rie(e,t,n){var r,i;let{intent:o,codec:a,limits:s,packageBase64:u}=(0,hp.readPlanInput)(n),l=(r=e.gates)!==null&&r!==void 0?r:hp.CERTIFIED_GATES,c=new ua.ReadBudget(s,(i=e.now)!==null&&i!==void 0?i:Date.now,!0),d=EA(t,c),f=EA(e.client,c);return JL([d.guard,f.guard],async()=>{var p,m;let h=await nM(u,a,s),g=await(0,ua.readEnvironment)(d.client),y=await(0,ua.readEnvironment)(f.client),b=[];g.organizationId===y.organizationId&&b.push((0,hp.refusal)("PROMOTION_SAME_ENVIRONMENT")),g.tenantId!==y.tenantId&&b.push((0,hp.refusal)("PROMOTION_TENANT_MISMATCH"));let E=!0,w={importKind:"undetermined",observations:[],coverage:[],checks:[],steps:[]};try{c.countComponents(h.componentCount);let O=new zL.OrgReader(d.client,c,a),v=await(0,vA.judgeSource)(h,O),N=await(0,hp.buildRecipe)(h,o,l,a,v),S=await(0,vA.correspondSource)(N.checks,h,O,a),R=await(0,vA.observeTarget)(h,o,new zL.OrgReader(f.client,c,a),a,l.connectionReferences,e.listConnections?()=>e.listConnections(f.client,c):void 0);b.push(...N.findings,...S,...R.findings),w={importKind:R.importKind,observations:R.observations,coverage:N.coverage,checks:N.checks,steps:N.steps}}catch(O){if(!(O instanceof HL.PromotionError)||O.code!=="PROMOTION_READ_BUDGET_EXCEEDED")throw O;E=!1,b.push({problem:O.problem,unknown:!0})}let _=eM(b,E),I={schemaVersion:1,planId:((p=e.newId)!==null&&p!==void 0?p:nie.newId)(),source:g,target:y,package:tM(h),intent:o,limits:s,importKind:w.importKind,observations:w.observations,coverage:w.coverage,checks:w.checks,steps:w.steps,outcome:_,problems:ZL(b),reads:{getAttempts:c.getAttempts,layerLookups:c.layerLookups,layerPages:c.layerPages,components:c.components,elapsedMs:c.elapsedMs,complete:E}},T=await XL(a,I);return(m=e.issuedPlans)===null||m===void 0||m.add(T),{...I,planDigest:T}})}Mt.planPromotion=rie});var sM=C(Qg=>{"use strict";Object.defineProperty(Qg,"__esModule",{value:!0});Qg.promote=void 0;var iie=Ke(),gp=Y(),oM=ft(),oie=pe(),rM=ae(),CA=zE(),yp=Kg(),ts=bA(),oe=Ya(),ns=AA(),aie=new Set(["codec","journal","resumeAttemptId","retryKnownUnappliedStepIds","pollTimeoutMs","onReceipt"]),sie=6e5,iM=[250,500,1e3,2e3,5e3],Eo=e=>(0,oe.promotionError)("PROMOTION_PLAN_INVALID","preflight",{reason:e}),ul=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),rs=e=>JSON.parse(JSON.stringify(e));function uie(e){var t,n;if(!ul(e))throw(0,oe.promotionError)("PROMOTION_JOURNAL_REQUIRED","preflight");let r=e.journal;if(!r||typeof r.begin!="function"||typeof r.read!="function"||typeof r.replace!="function"||typeof r.release!="function")throw(0,oe.promotionError)("PROMOTION_JOURNAL_REQUIRED","preflight");let i=(0,yp.requireCodec)(e.codec);for(let l of Object.keys(e))if(!aie.has(l))throw(0,oe.promotionError)("INVALID_ARGUMENT","preflight",{reason:"an unsupported apply option"});let o=e.resumeAttemptId;if(o!==void 0&&!(0,oe.canonicalGuid)(o))throw(0,oe.promotionError)("INVALID_ARGUMENT","preflight",{reason:"resumeAttemptId must be an attempt id"});let a=(t=e.retryKnownUnappliedStepIds)!==null&&t!==void 0?t:[],s=Array.isArray(a)?[...a]:[];if(!Array.isArray(a)||s.some(l=>typeof l!="string"))throw(0,oe.promotionError)("INVALID_ARGUMENT","preflight",{reason:"retryKnownUnappliedStepIds must be step ids"});let u=(n=e.pollTimeoutMs)!==null&&n!==void 0?n:sie;if(typeof u!="number"||!Number.isSafeInteger(u)||u<=0)throw(0,oe.promotionError)("INVALID_ARGUMENT","preflight",{reason:"pollTimeoutMs must be a positive safe integer"});if(e.onReceipt!==void 0&&typeof e.onReceipt!="function")throw(0,oe.promotionError)("INVALID_ARGUMENT","preflight",{reason:"onReceipt must be a function"});return{codec:i,journal:r,...o!==void 0?{resumeAttemptId:(0,oe.canonicalGuid)(o)}:{},retry:s,pollTimeoutMs:u,...e.onReceipt?{onReceipt:e.onReceipt}:{}}}function lie(e,t){let n;try{n=ul(e)?rs(e):e}catch{throw Eo("a plan that is not JSON data")}if(!ul(n)||n.schemaVersion!==1)throw Eo("an unsupported plan schema");let r=o=>ul(o)&&["organizationId","tenantId","instanceUrl","actorId"].every(a=>typeof o[a]=="string"),i=n.package;if(typeof n.planId!="string"||typeof n.planDigest!="string"||!/^[0-9a-f]{64}$/.test(n.planDigest)||!r(n.source)||!r(n.target)||!ul(i)||typeof i.sha256!="string"||!ul(n.intent)||!["install","update","undetermined"].includes(n.importKind)||!["ready","refused","unknown"].includes(n.outcome)||!["observations","coverage","checks","steps","problems"].every(o=>Array.isArray(n[o]))||!ul(n.reads))throw Eo("a malformed plan");try{let o=(0,yp.readPlanInput)({...n.intent,packageBase64:"x",codec:t});if((0,oe.canonicalJson)(o.intent)!==(0,oe.canonicalJson)(n.intent))throw Eo("a non-canonical intent");if((0,oe.canonicalJson)((0,yp.readLimits)(n.limits))!==(0,oe.canonicalJson)(n.limits))throw Eo("non-canonical limits")}catch(o){throw o instanceof gp.PromotionError&&o.code==="PROMOTION_PLAN_INVALID"?o:Eo("an invalid intent")}return n}function aM(e,t){return{schemaVersion:1,attemptId:t,planId:e.planId,planDigest:e.planDigest,packageSha256:e.package.sha256,targetOrganizationId:e.target.organizationId,targetTenantId:e.target.tenantId,phase:"preflight",stage:{state:"notStarted"},import:{state:"notSubmitted"},steps:e.steps.map(n=>({stepId:n.id,state:"notStarted",expectedBefore:[]})),verification:[],effects:"noneVerified",cleanup:{state:"notStarted"}}}function Lc(e,t,n){return{status:"failed",receipt:aM(e,n),problems:t}}var Yg=class{constructor(t,n,r){this.journal=t,this.record=n,this.onReceipt=r,this.stopped=!1,this.problems=[],this.receipt=rs(n.receipt)}get released(){return this.record.reservation==="released"}async save(t){let n=t(rs(this.receipt));if(this.receipt=n,this.stopped)return!1;let r={...this.record,revision:this.record.revision+1,receipt:rs(n)},i=!1;try{i=await this.journal.replace(n.attemptId,this.record.revision,r)===!0}catch{i=!1}if(!i)return this.stop("the journal did not accept the attempt state"),!1;if(this.record=r,this.onReceipt)try{await this.onReceipt(rs(n))}catch{return this.stop("the host receipt notification failed"),!1}return!0}stop(t){this.stopped=!0,this.problems.push((0,oe.promotionProblem)("PROMOTION_JOURNAL_FAILED",this.receipt.phase,{reason:t}))}async release(){if(this.stopped||this.released)return;let t=!1;try{t=await this.journal.release(this.receipt.targetOrganizationId,this.receipt.attemptId,this.record.revision)===!0}catch{t=!1}t?this.record={...this.record,revision:this.record.revision+1,reservation:"released"}:this.problems.push((0,oe.promotionProblem)("PROMOTION_JOURNAL_FAILED",this.receipt.phase,{blocking:!1,reason:"the reservation could not be released"}))}};function cie(e){return e.import.state==="succeeded"?e.effects==="completeVerified"?"applied":"partial":e.effects==="partialKnown"?"partial":e.effects==="unknown"||["submitting","running","unknown"].includes(e.import.state)?"unknown":"failed"}var SA=class{constructor(t,n,r,i,o,a,s,u){this.context=t,this.attempt=n,this.plan=r,this.model=i,this.client=o,this.budget=a,this.options=s,this.gates=u,this.problems=[],this.trace=[]}problem(t,n,r={}){this.problems.push((0,oe.promotionProblem)(t,n,r))}result(t){return{status:t,receipt:rs(this.attempt.receipt),problems:[...this.problems,...this.attempt.problems]}}lister(t){let n=this.context.listConnections;return n?()=>n(t,this.budget):void 0}async observe(){let{client:t,guard:n}=this.client.readOnly();try{let r=await(0,ns.latched)([n],()=>(0,ts.observeTarget)(this.model,this.plan.intent,new CA.OrgReader(t,this.budget,this.options.codec),this.options.codec,this.gates.connectionReferences,this.lister(t)));return r.observations.some(i=>i.image.state==="unreadable")||r.findings.some(i=>i.unknown)?void 0:r.observations}catch(r){if(r instanceof gp.PromotionError)return;throw r}}parameters(){let t=[];for(let n of this.model.variables){let r=this.plan.intent.values.find(i=>i.schemaName.toLowerCase()===n.schemaName.toLowerCase());r&&r.value!==""&&t.push({"@odata.type":"Microsoft.Dynamics.CRM.environmentvariablevalue",schemaname:n.schemaName,value:r.value})}for(let n of this.model.references){let r=this.plan.intent.connections.find(i=>i.logicalName.toLowerCase()===n.logicalName.toLowerCase());r&&r.connectionId!==""&&t.push({"@odata.type":"Microsoft.Dynamics.CRM.connectionreference",connectionreferencelogicalname:n.logicalName,connectionid:r.connectionId,connectorid:n.connectorId})}return t}stageDiscrepancy(t){let n=this.model,r=t.details;if(!r)return"the staged solution details are missing";let i=(0,oe.parseVersion)(r.version);if(r.solutionName.toLowerCase()!==n.solutionUniqueName.toLowerCase()||r.publisherName.toLowerCase()!==n.publisherUniqueName.toLowerCase()||r.managed!==n.managed||!i||(0,oe.compareVersions)(i,(0,oe.parseVersion)(n.version))!==0)return"another solution, publisher, mode or version was staged";if(r.patch||r.pendingUpgrade)return"a patch or a pending upgrade was staged";if(t.missing>0)return this.problem("PROMOTION_DEPENDENCY_MISSING","stage"),"staging reports missing dependencies";if(t.validationErrors>0)return"staging reports validation errors";let o=c=>c.map(d=>d.toLowerCase()).sort();if((0,oe.canonicalJson)(o(n.apps.map(c=>c.uniqueName)))!==(0,oe.canonicalJson)(t.apps)||(0,oe.canonicalJson)(o(n.webResources.map(c=>c.name)))!==(0,oe.canonicalJson)(t.webResources))return"the staged apps or web resources differ from the package";let a=[...n.variables].sort((c,d)=>(0,oe.byCodeUnit)(c.schemaName.toLowerCase(),d.schemaName.toLowerCase())).map(c=>{var d;return{schemaName:c.schemaName.toLowerCase(),type:String(c.type),isRequired:c.isRequired?"true":"false",defaultValue:(d=c.defaultValue)!==null&&d!==void 0?d:""}}),s=t.variables.map(c=>({...c,isRequired:c.isRequired===null?null:c.isRequired.toLowerCase()}));if((0,oe.canonicalJson)(a)!==(0,oe.canonicalJson)(s))return"the staged variables differ from the package";let u=[...n.references].sort((c,d)=>(0,oe.byCodeUnit)(c.logicalName.toLowerCase(),d.logicalName.toLowerCase())).map(c=>({logicalName:c.logicalName.toLowerCase(),connectorId:c.connectorId.toLowerCase()})),l=t.references.map(c=>({logicalName:c.logicalName,connectorId:c.connectorId===null?null:c.connectorId.toLowerCase()}));if((0,oe.canonicalJson)(u)!==(0,oe.canonicalJson)(l))return"the staged connection references differ from the package"}async fresh(t){if(!await this.attempt.save(s=>({...s,phase:"stage",stage:{state:"submitting"}})))return this.result("failed");let n,r={};this.trace.push({action:"StageSolution"});try{let s=await this.client.post("/StageSolution",{CustomizationFile:t});n=s.status===200?(0,ts.readStageAnswer)(s.body):ts.UNREADABLE_STAGE,r=s.status===200?{}:{httpStatus:s.status}}catch(s){n=ts.UNREADABLE_STAGE,r=(0,oe.safeDiagnostics)(s)}if(n.status==="unreadable")return await this.attempt.save(s=>({...s,stage:{state:"unknown",...n.uploadId?{uploadId:n.uploadId}:{}},effects:"unknown"})),this.problem("PROMOTION_STAGE_UNKNOWN","stage",r),this.result("unknown");if(n.status==="Failed")return await this.attempt.save(s=>({...s,stage:{state:"failed",...n.uploadId?{uploadId:n.uploadId}:{}}})),this.problem("PROMOTION_STAGE_FAILED","stage"),n.missing>0&&this.problem("PROMOTION_DEPENDENCY_MISSING","stage"),await this.cleanup(),await this.finish("failed"),this.result("failed");let i=n.uploadId;if(!await this.attempt.save(s=>({...s,stage:{state:"passed",uploadId:i}})))return await this.attempt.save(s=>({...s,cleanup:{state:"deferred",remainingUploadId:i}})),this.result("failed");let o=this.stageDiscrepancy(n);if(o)return this.problem("PROMOTION_STAGE_FAILED","stage",{reason:o}),await this.cleanup(),await this.finish("failed"),this.result("failed");let a=await this.observe();return!a||!(0,ts.sameObservations)(a,this.plan.observations)?(this.problem(a?"PROMOTION_PLAN_STALE":"PROMOTION_VERIFICATION_UNAVAILABLE","stage"),await this.cleanup(),await this.finish("failed"),this.result("failed")):this.importOnce(i)}async importOnce(t){var n,r;let i=((n=this.context.newId)!==null&&n!==void 0?n:oM.newId)();if(!await this.attempt.save(d=>({...d,phase:"import",import:{state:"submitting",importJobId:i}})))return await this.attempt.save(d=>({...d,cleanup:{state:"deferred",remainingUploadId:t}})),this.result("failed");let o=this.parameters(),a={OverwriteUnmanagedCustomizations:this.plan.intent.overwriteUnmanagedCustomizations,PublishWorkflows:this.plan.intent.publishWorkflows,ImportJobId:i,SolutionParameters:{StageSolutionUploadId:t},...o.length>0?{ComponentParameters:o}:{}};this.trace.push({action:"ImportSolutionAsync",publishWorkflows:a.PublishWorkflows});let s=0,u,l={};try{let d=await this.client.post("/ImportSolutionAsync",a);s=d.status,u=(0,oe.canonicalGuid)((r=d.body)===null||r===void 0?void 0:r.AsyncOperationId)}catch(d){l=(0,oe.safeDiagnostics)(d)}if(s>=200&&s<300&&u){let d=u;await this.attempt.save(p=>({...p,import:{state:"running",importJobId:i,asyncOperationId:d}}));let f=await this.activationEvidence();return await this.attempt.save(p=>({...p,verification:f})),this.attempt.stopped?this.stopped():this.settle(d)}let c=await this.activationEvidence();return await this.attempt.save(d=>({...d,import:{state:"unknown",importJobId:i,...u?{asyncOperationId:u}:{}},verification:c,effects:"unknown",cleanup:{state:"deferred",remainingUploadId:t}})),this.problem("PROMOTION_IMPORT_UNKNOWN","import",{...l,...s?{httpStatus:s}:{}}),this.result("unknown")}async activationEvidence(){let t=[];for(let n of this.plan.checks.filter(r=>r.aspect==="activation"))t.push(await this.activationResult(n));return t}async poll(t){var n,r;let i=(n=this.context.now)!==null&&n!==void 0?n:Date.now,o=(r=this.context.sleep)!==null&&r!==void 0?r:oie.sleep,a=i()+this.options.pollTimeoutMs,s;for(let u=0;;u+=1){try{let c=await this.client.get(`/asyncoperations(${t})${(0,rM.odataQuery)([["$select","statecode,statuscode"]])}`),d=c.body;if(c.status===200&&typeof d?.statecode=="number"&&typeof d?.statuscode=="number"&&(s={stateCode:d.statecode,statusCode:d.statuscode},d.statecode===3))return{state:d.statuscode===30?"succeeded":d.statuscode===31||d.statuscode===32?"failed":"unknown",...s}}catch(c){if(c instanceof gp.PromotionError&&c.code==="PROMOTION_READ_BUDGET_EXCEEDED")break}let l=a-i();if(l<=0)break;await o(Math.min(iM[Math.min(u,iM.length-1)],l))}return s?{state:"running",...s}:{state:"unknown"}}async settle(t){let n=await this.poll(t),r={...n.stateCode!==void 0?{stateCode:n.stateCode}:{},...n.statusCode!==void 0?{statusCode:n.statusCode}:{}};return n.state==="succeeded"?(await this.attempt.save(i=>({...i,phase:"verify",import:{...i.import,state:"succeeded",...r}})),this.attempt.stopped?this.stopped():this.verifyAndFinish()):n.state==="failed"?(await this.attempt.save(i=>({...i,import:{...i.import,state:"failed",...r}})),this.problem("PROMOTION_IMPORT_FAILED","import"),this.attempt.stopped?this.stopped():this.afterFailedImport()):(await this.attempt.save(i=>({...i,import:{...i.import,state:n.state==="running"?"running":"unknown",...r},effects:"unknown",cleanup:i.stage.uploadId?{state:"deferred",remainingUploadId:i.stage.uploadId}:i.cleanup})),this.problem("PROMOTION_IMPORT_UNKNOWN","import",{reason:"the import did not reach a terminal state in time"}),this.result("unknown"))}async activationResult(t){let n=this.trace.filter(a=>a.action==="ImportSolutionAsync");if(n.length!==1)return{checkId:t.id,state:"unreadable",evidence:"notAvailable",problem:(0,oe.promotionProblem)("PROMOTION_VERIFICATION_FAILED","verify",{reason:"no dispatch trace of the import"})};let r={publishWorkflows:n[0].publishWorkflows===!0,activationRequests:this.trace.filter(a=>a.action!=="ImportSolutionAsync"&&a.action!=="StageSolution"&&a.action!=="DeleteUpload").length},i=!r.publishWorkflows&&r.activationRequests===0,o;try{o=await(0,oe.digestOf)(this.options.codec,r)}catch{return{checkId:t.id,state:"unreadable",evidence:"notAvailable",problem:(0,oe.promotionProblem)("PROMOTION_VERIFICATION_FAILED","verify",{reason:"the dispatch evidence could not be digested"})}}return{checkId:t.id,state:i?"matched":"mismatched",evidence:"attemptTrace",observedDigest:o,...i?{}:{problem:(0,oe.promotionProblem)("PROMOTION_VERIFICATION_FAILED","verify",{reason:"an activation was requested"})}}}async verifyAndFinish(){var t;let{client:n,guard:r}=this.client.readOnly(),i=new Map(this.attempt.receipt.verification.map(s=>[s.checkId,s])),o=await(0,ns.latched)([r],()=>(0,ts.verifyChecks)(this.plan.checks,this.model,new CA.OrgReader(n,this.budget,this.options.codec),this.options.codec,s=>this.activationResult(s),i)),a=o.every(s=>s.state==="matched");for(let s of o.filter(u=>u.state!=="matched"))this.problems.push((t=s.problem)!==null&&t!==void 0?t:(0,oe.promotionProblem)("PROMOTION_VERIFICATION_UNAVAILABLE","verify",{reason:"a declared requirement is pending a manual step"}));return await this.attempt.save(s=>({...s,phase:"verify",verification:o,steps:s.steps.map(u=>({...u,state:"manualPending"})),effects:a?"completeVerified":"partialKnown"})),this.attempt.stopped?this.stopped():(await this.cleanup(),a&&await this.finish("applied"),this.attempt.stopped?this.stopped():this.result(a?"applied":"partial"))}async afterFailedImport(){let t=await this.observe(),n=i=>i.filter(o=>o.purpose==="affected"),r=t?(0,ts.sameObservations)(n(t),n(this.plan.observations))?"failed":"partial":"unknown";return await this.attempt.save(i=>({...i,effects:r==="failed"?"noneVerified":r==="partial"?"partialKnown":"unknown"})),this.attempt.stopped?this.stopped():r==="unknown"?(await this.attempt.save(i=>({...i,cleanup:i.stage.uploadId?{state:"deferred",remainingUploadId:i.stage.uploadId}:i.cleanup})),this.result("unknown")):(await this.cleanup(),await this.finish(r),this.attempt.stopped?this.stopped():this.result(r))}async stopped(){let t=this.attempt.receipt,n=t.import.state==="succeeded"||t.effects==="partialKnown"?"partial":"unknown";return await this.attempt.save(r=>({...r,effects:n==="partial"?"partialKnown":"unknown",cleanup:r.stage.uploadId&&r.cleanup.state!=="complete"?{state:"deferred",remainingUploadId:r.stage.uploadId}:r.cleanup})),this.result(n)}async finish(t){t!=="partial"&&await this.attempt.save(n=>({...n,phase:"complete"})),await this.attempt.release()}async cleanup(){let t=this.attempt.receipt.stage.uploadId;if(!t)return;let n=async u=>{await this.attempt.save(l=>({...l,cleanup:{state:"deferred",remainingUploadId:t}})),this.problem("PROMOTION_CLEANUP_FAILED","cleanup",{blocking:!1,reason:u})};if(this.attempt.stopped){await n("the journal stopped this attempt");return}let r=`/stagesolutionuploads${(0,rM.odataQuery)([["$select","stagesolutionuploadid"],["$filter",`stagesolutionuploadid eq ${t}`]])}`,i=async()=>{var u;try{let l=await this.client.get(r),c=(u=l.body)===null||u===void 0?void 0:u.value;return l.status===200&&Array.isArray(c)&&(0,iie.boundedPageComplete)(l.body,c.length)?c:void 0}catch{return}},o=await i();if(o&&o.length===0){await this.attempt.save(u=>({...u,cleanup:{state:"complete"}}));return}if(!this.gates.stageCleanup){await n("conditional deletion of the staged upload is not certified");return}let a=o?.length===1?o[0]["@odata.etag"]:void 0;if(typeof a!="string"){await n("the staged upload has no readable row token");return}if(!await this.attempt.save(u=>({...u,phase:"cleanup"})))return;this.trace.push({action:"DeleteUpload"});try{await this.client.delete(`/stagesolutionuploads(${t})`,{headers:{"If-Match":a}})}catch{}let s=await i();if(s&&s.length===0){await this.attempt.save(u=>({...u,cleanup:{state:"complete"}}));return}await this.attempt.save(u=>({...u,cleanup:{state:"failed",remainingUploadId:t}})),this.problem("PROMOTION_CLEANUP_FAILED","cleanup",{blocking:!1})}async resume(){let t=this.attempt.receipt;return t.import.state==="succeeded"?this.verifyAndFinish():t.import.state==="failed"?this.afterFailedImport():(t.import.state==="running"||t.import.state==="unknown")&&t.import.asyncOperationId?this.settle(t.import.asyncOperationId):t.import.state==="notSubmitted"?t.stage.state!=="passed"&&t.stage.state!=="failed"?(this.problem("PROMOTION_STAGE_UNKNOWN","stage",{reason:"the staging outcome was never read"}),this.result("unknown")):(this.problem("PROMOTION_STAGE_FAILED","stage",{reason:"the attempt stopped before its import"}),await this.cleanup(),await this.finish("failed"),this.result("failed")):(this.problem("PROMOTION_IMPORT_UNKNOWN","import"),this.result("unknown"))}async guarded(t){try{return await t()}catch(n){let r=this.attempt.receipt.phase;this.problems.push(n instanceof gp.PromotionError?(0,oe.promotionProblem)(n.code,r,{reason:"the attempt stopped on an internal failure"}):(0,oe.promotionProblem)("PROMOTION_VERIFICATION_UNAVAILABLE",r,{reason:"the attempt stopped on an unexpected failure"}));let i=this.attempt.receipt.import.state==="succeeded"?"partial":"unknown";try{await this.attempt.save(o=>({...o,effects:i==="partial"?"partialKnown":"unknown",cleanup:o.stage.uploadId&&o.cleanup.state!=="complete"?{state:"deferred",remainingUploadId:o.stage.uploadId}:o.cleanup}))}catch{}return this.result(i)}}};async function die(e,t,n,r){var i,o,a,s,u,l;let c=uie(r),{codec:d}=c,f=lie(t,d);if(await(0,ns.planDigestOf)(d,f)!==f.planDigest)throw Eo("the digest does not match the plan");let p=typeof n=="string"?(0,ns.decodePackage)(n):void 0;if(!p||await(0,oe.sha256Of)(d,p)!==f.package.sha256)throw Eo("the package bytes differ from the planned package");let m=n,h=(i=e.gates)!==null&&i!==void 0?i:yp.CERTIFIED_GATES,g=new oe.ReadBudget(f.limits,(o=e.now)!==null&&o!==void 0?o:Date.now,!1),y=e.client.withoutSolution().withTransport(U=>g.wrap(U)),b=await(0,oe.readEnvironment)(y.readOnly().client);if((0,oe.canonicalJson)(b)!==(0,oe.canonicalJson)(f.target))throw(0,oe.promotionError)("PROMOTION_ENVIRONMENT_MISMATCH","preflight");let E=await(0,ns.modelOf)(m,d,f.limits);if((0,oe.canonicalJson)((0,ns.packageIdentity)(E))!==(0,oe.canonicalJson)(f.package))throw Eo("the package identity differs");let w=(a=c.resumeAttemptId)!==null&&a!==void 0?a:((s=e.newId)!==null&&s!==void 0?s:oM.newId)(),_=U=>e.listConnections?()=>e.listConnections(U,g):void 0,I=U=>new SA(e,U,f,E,y,g,c,h);if(c.resumeAttemptId){let U;try{U=await c.journal.read(w)}catch{throw(0,oe.promotionError)("PROMOTION_JOURNAL_FAILED","preflight")}let M=U?.receipt;if(!U||!M||typeof U.revision!="number"||M.attemptId!==w||((u=U.plan)===null||u===void 0?void 0:u.planId)!==f.planId||((l=U.plan)===null||l===void 0?void 0:l.planDigest)!==f.planDigest||M.planDigest!==f.planDigest||M.packageSha256!==f.package.sha256||M.targetOrganizationId!==f.target.organizationId)throw(0,oe.promotionError)("PROMOTION_RECEIPT_UNVERIFIED","preflight");for(let X of c.retry)if(!M.steps.some(ye=>ye.stepId===X&&ye.state==="failedNotApplied"))throw(0,oe.promotionError)("INVALID_ARGUMENT","preflight",{reason:"a retried step is not known to be unapplied"});if(U.reservation==="released")return{status:cie(M),receipt:rs(M),problems:[]};let q=I(new Yg(c.journal,U,c.onReceipt));return q.guarded(()=>q.resume())}if(c.retry.length>0)throw(0,oe.promotionError)("INVALID_ARGUMENT","preflight",{reason:"only a continuation may retry steps"});if(!e.issuedPlans||!e.issuedPlans.has(f.planDigest))throw Eo("the plan was not issued by this SDK");if(f.outcome!=="ready")return Lc(f,f.problems.map(U=>(0,oe.promotionProblem)(U.code,U.phase,{blocking:U.blocking,subject:U.subject,stepId:U.stepId})),w);let T=await(0,yp.buildRecipe)(E,f.intent,h,d,{refusedRoles:new Set,findings:[]});if((0,oe.canonicalJson)([T.coverage,T.checks,T.steps])!==(0,oe.canonicalJson)([f.coverage,f.checks,f.steps]))throw Eo("the recipe differs from the package and intent");let O=y.readOnly(),v;try{v=await(0,ns.latched)([O.guard],()=>(0,ts.observeTarget)(E,f.intent,new CA.OrgReader(O.client,g,d),d,h.connectionReferences,_(O.client)))}catch(U){if(U instanceof gp.PromotionError&&U.code==="PROMOTION_READ_BUDGET_EXCEEDED")return Lc(f,[U.problem],w);throw U}if(!(0,ts.sameObservations)(v.observations,f.observations)||v.importKind!==f.importKind)return Lc(f,[(0,oe.promotionProblem)("PROMOTION_PLAN_STALE","preflight")],w);let N=[...T.findings,...v.findings],S=[...f.source.organizationId===f.target.organizationId?[(0,oe.promotionProblem)("PROMOTION_SAME_ENVIRONMENT","preflight")]:[],...f.source.tenantId!==f.target.tenantId?[(0,oe.promotionProblem)("PROMOTION_TENANT_MISMATCH","preflight")]:[]];if((0,ns.outcomeOf)(N,!0)!=="ready"||S.length>0)return Lc(f,[...(0,ns.sortProblems)(N),...S],w);let R={revision:0,reservation:"held",plan:rs(f),receipt:aM(f,w)},x;try{x=await c.journal.begin(f.target.organizationId,rs(R))}catch{return Lc(f,[(0,oe.promotionProblem)("PROMOTION_JOURNAL_FAILED","preflight")],w)}if(!x||x.acquired!==!0)return Lc(f,[(0,oe.promotionProblem)("PROMOTION_ATTEMPT_IN_PROGRESS","preflight")],w);let G=I(new Yg(c.journal,R,c.onReceipt));return G.guarded(()=>G.fresh(m))}Qg.promote=die});var lM={};Fi(lM,{CCFControlConstants:()=>uM,CCFPropertyConstants:()=>_A,CustomControlDataType:()=>j,CustomControlNames:()=>is,DefaultControlNameKeys:()=>NA,ICCModeEnum:()=>eu,JSONParametersConstants:()=>IA,LookUpType:()=>Xg,ManifestXMLConstants:()=>vr,NumberType:()=>Zg,Usage:()=>ll});var uM,_A,IA,vr,j,NA,is,eu,ll,Xg,Zg,cl=B(()=>{"use strict";uM={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"},_A={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"},IA={GroupDefinition:"GroupDefinition"},vr={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"})(j||(j={}));(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"})(NA||(NA={}));(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"})(is||(is={}));(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"})(eu||(eu={}));(function(e){e[e.Bound=0]="Bound",e[e.Input=1]="Input",e[e.Output=2]="Output"})(ll||(ll={}));Xg=[j.LookupCustomer,j.LookupOwner,j.LookupPartyList,j.LookupRegarding,j.LookupSimple],Zg=[j.WholeNone,j.WholeDuration,j.WholeLanguage,j.WholeTimeZone,j.FP,j.Decimal]});var Mc,qr,bp=B(()=>{"use strict";Mc=class{keys;values;constructor(){this.keys=[],this.values=[]}add(t,n){return this.containsKey(t)?!1:(this.keys.push(t),this.values.push(n),!0)}upsert(t,n){this.update(t,n)||this.add(t,n)}sortedUpsert(t,n){if(!this.update(t,n)){let r=0;for(;r<this.keys.length&&this.keys[r]<t;)r++;this.keys.splice(r,0,t),this.values.splice(r,0,n)}}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 n=this.keys.indexOf(t);return n!==-1?this.values[n]:!1}getKeys(){return this.keys.slice()}getValues(){return this.values.slice()}remove(t){let n=this.keys.indexOf(t);return n!==-1?(this.keys.splice(n,1),this.values.splice(n,1),!0):!1}update(t,n){let r=this.keys.indexOf(t);return r!==-1?(this.values[r]=n,!0):!1}},qr=class{data={};add(t,n){return this.containsKey(t)?!1:(this.data[t]=n,!0)}upsert(t,n){this.data[t]=n}clear(){this.data={}}containsKey(t){return this.data.hasOwnProperty(t)}containsValue(t){for(let n in this.data)if(this.data[n]===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 n in this.data)t.push(this.data[n]);return t}remove(t){return this.containsKey(t)?delete this.data[t]:!1}update(t,n){return this.containsKey(t)?(this.data[t]=n,!0):!1}getInternalObject(){return this.data}}});var cM={};Fi(cM,{AttributeDataSourceType:()=>vp,AttributeDataSourceTypeMask:()=>e0,AttributePrecisionSource:()=>wp,EntityAttributeDataSourceType:()=>dl,EntityAttributeDateTimeBehavior:()=>DA,EntityAttributeImeMode:()=>OA,EntityAttributePrecisionSource:()=>PA,EntityAttributeRequiredLevel:()=>tu,EntityAttributeType:()=>V,EntityAttributeTypeFormat:()=>ne,EntityMetadataLookUpBase:()=>os,EntityResxKeyLookUp:()=>t0,SourceTypeMask:()=>TA});var os,V,ne,tu,dl,TA,vp,e0,OA,DA,PA,wp,t0,xc=B(()=>{"use strict";bp();os=class{name;constructor(t){this.name=t}toString(){return this.name}getName(){return this.name}getDisplayNameResourceKey(){return t0.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"})(V||(V={}));(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"})(ne||(ne={}));tu=class extends os{constructor(t){super(t)}static get None(){return"None"}static get SystemRequired(){return"SystemRequired"}static get ApplicationRequired(){return"ApplicationRequired"}static get Recommended(){return"Recommended"}},dl=class e extends os{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?vp.Persistent:parseInt(vp[this.name])}},TA=class e extends os{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(e0[this.name])}};(function(e){e[e.Persistent=0]="Persistent",e[e.Calculated=1]="Calculated",e[e.Rollup=2]="Rollup"})(vp||(vp={}));(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"})(e0||(e0={}));OA=class e extends os{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"}},DA=class e extends os{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"}},PA=class e extends os{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?wp.Currency:parseInt(wp[this.name])}};(function(e){e[e.Attribute=0]="Attribute",e[e.Organization=1]="Organization",e[e.Currency=2]="Currency"})(wp||(wp={}));t0=class e{static resourceKeyMap=e.initResourceKeyMap();static initResourceKeyMap(){let t=new Mc;return t.add(V.TwoOptions,"SystemCustomization.type.bit.label"),t.add(V.Customer,"SystemCustomization.type.customer.label"),t.add(V.CustomerType,"SystemCustomization.type.customer.label"),t.add(V.DateTime,"SystemCustomization.type.datetime.label"),t.add(V.DecimalNumber,"SystemCustomization.type.decimal.label"),t.add(V.FloatingPointNumber,"SystemCustomization.type.float.label"),t.add(V.WholeNumber,"SystemCustomization.type.int.label"),t.add(V.LookupType,"SystemCustomization.type.lookup.label"),t.add(V.Lookup,"SystemCustomization.type.lookup.label"),t.add(V.MultipleLineofText,"SystemCustomization.type.ntext.label"),t.add(V.Currency,"SystemCustomization.type.money.label"),t.add(V.Owner,"SystemCustomization.type.owner.label"),t.add(V.OwnerType,"SystemCustomization.type.owner.label"),t.add(V.PartyList,"SystemCustomization.type.partylist.label"),t.add(V.PartyListType,"SystemCustomization.type.partylist.label"),t.add(V.OptionSet,"SystemCustomization.type.picklist.label"),t.add(V.State,"SystemCustomization.type.state.label"),t.add(V.Status,"SystemCustomization.type.status.label"),t.add(V.SingleLineofText,"SystemCustomization.type.nvarchar.label"),t.add(V.UniqueIdentifier,"SystemCustomization.type.uniqueidentifier.label"),t.add(V.UniqueIdentifierType,"SystemCustomization.type.uniqueidentifiertype.label"),t.add(V.CalendarRulesType,"SystemCustomization.type.calendarrules.label"),t.add(V.VirtualType,"SystemCustomization.type.virtual.label"),t.add(V.BigInt,"SystemCustomization.type.bigint.label"),t.add(V.ManagedPropertyType,"SystemCustomization.type.managedproperty.label"),t.add(V.EntityNameType,"SystemCustomization.type.entityname.label"),t.add(V.Image,"SystemCustomization.type.image.label"),t.add(V.MultiSelectOptionSet,"SystemCustomization.type.multiselectpicklist.label"),t.add(V.PrimaryNameAttributeType,"SystemCustomization.type.primaryname.label"),t.add(V.LookupType,"SystemCustomization.type.lookuptype.label"),t.add(V.Subject,"SystemCustomization.type.subject.label"),t.add(ne.Email,"SystemCustomization.String.Format.email"),t.add(ne.Text,"SystemCustomization.String.Format.text"),t.add(ne.TextArea,"SystemCustomization.String.Format.textarea"),t.add(ne.Url,"SystemCustomization.String.Format.url"),t.add(ne.TickerSymbol,"SystemCustomization.String.Format.tickersymbol"),t.add(ne.PhoneticGuide,"SystemCustomization.String.Format.phoneticguide"),t.add(ne.VersionNumber,"SystemCustomization.String.Format.versionnumber"),t.add(ne.Phone,"SystemCustomization.String.Format.phone"),t.add(ne.None,"SystemCustomization.Integer.Format."),t.add(ne.Duration,"SystemCustomization.Integer.Format.duration"),t.add(ne.TimeZone,"SystemCustomization.Integer.Format.timezone"),t.add(ne.Language,"SystemCustomization.Integer.Format.language"),t.add(ne.Locale,"SystemCustomization.Integer.Format.language"),t.add(ne.DateOnly,"SystemCustomization.DateTime.Format.date"),t.add(ne.DateAndTime,"SystemCustomization.DateTime.Format.datetime"),t.add(ne.Regarding,"SystemCustomization.Lookup.Format.regarding"),t.add(dl.Persistent,"SystemCustomization.String.Source.persistent"),t.add(dl.Calculated,"SystemCustomization.String.Source.calculated"),t.add(dl.Rollup,"SystemCustomization.String.Source.rollup"),t.add(dl.None,"SystemCustomization.String.Source.none"),t}static getDisplayNameResourceKey(t){return e.resourceKeyMap.getValue(t)}}});var kA=C(vn=>{"use strict";Object.defineProperty(vn,"__esModule",{value:!0});vn.parsePcfManifest=vn.parseControlElement=vn.parseManifestRoot=vn.firstLevel=vn.attr=vn.elementChildren=vn.manifestTypesForColumn=vn.DEFAULT_TYPE_GROUPS=void 0;var fie=Ms(),ie=(cl(),_i(lM)),Je=(xc(),_i(cM));vn.DEFAULT_TYPE_GROUPS={numbers:[ie.CustomControlDataType.WholeNone,ie.CustomControlDataType.FP,ie.CustomControlDataType.Decimal,ie.CustomControlDataType.Currency],text:[ie.CustomControlDataType.SingleLineText,ie.CustomControlDataType.SingleLineTextArea,ie.CustomControlDataType.Multiple],lookup:[ie.CustomControlDataType.LookupSimple,ie.CustomControlDataType.LookupCustomer,ie.CustomControlDataType.LookupOwner,ie.CustomControlDataType.LookupPartyList,ie.CustomControlDataType.LookupRegarding],dates:[ie.CustomControlDataType.DateAndTimeDateOnly,ie.CustomControlDataType.DateAndTimeDateAndTime],allFields:[ie.CustomControlDataType.TwoOptions,ie.CustomControlDataType.DateAndTimeDateOnly,ie.CustomControlDataType.DateAndTimeDateAndTime,ie.CustomControlDataType.FP,ie.CustomControlDataType.Decimal,ie.CustomControlDataType.WholeNone,ie.CustomControlDataType.WholeDuration,ie.CustomControlDataType.WholeTimeZone,ie.CustomControlDataType.WholeLanguage,ie.CustomControlDataType.LookupSimple,ie.CustomControlDataType.LookupCustomer,ie.CustomControlDataType.LookupOwner,ie.CustomControlDataType.LookupPartyList,ie.CustomControlDataType.LookupRegarding,ie.CustomControlDataType.Multiple,ie.CustomControlDataType.OptionSet,ie.CustomControlDataType.SingleLineText,ie.CustomControlDataType.SingleLineTextArea,ie.CustomControlDataType.SingleLineEmail,ie.CustomControlDataType.SingleLineURL,ie.CustomControlDataType.SingleLineTickerSymbol,ie.CustomControlDataType.SingleLinePhone]};var pie="Phone";function mie(e,t,n){switch(e){case Je.EntityAttributeType.TwoOptions:return[ie.CustomControlDataType.TwoOptions,ie.CustomControlDataType.Boolean];case Je.EntityAttributeType.Customer:case Je.EntityAttributeType.CustomerType:return[ie.CustomControlDataType.LookupCustomer];case Je.EntityAttributeType.DateTime:return t===Je.EntityAttributeTypeFormat.DateAndTime?[ie.CustomControlDataType.DateAndTimeDateAndTime]:[ie.CustomControlDataType.DateAndTimeDateOnly];case Je.EntityAttributeType.DecimalNumber:return[ie.CustomControlDataType.Decimal];case Je.EntityAttributeType.FloatingPointNumber:return[ie.CustomControlDataType.FP];case Je.EntityAttributeType.File:return[ie.CustomControlDataType.File];case Je.EntityAttributeType.Image:return[ie.CustomControlDataType.Image];case Je.EntityAttributeType.WholeNumber:return t===Je.EntityAttributeTypeFormat.Duration?[ie.CustomControlDataType.WholeDuration]:t===Je.EntityAttributeTypeFormat.Language?[ie.CustomControlDataType.WholeLanguage]:t===Je.EntityAttributeTypeFormat.TimeZone?[ie.CustomControlDataType.WholeTimeZone]:[ie.CustomControlDataType.WholeNone];case Je.EntityAttributeType.LookupType:case Je.EntityAttributeType.Lookup:return t===Je.EntityAttributeTypeFormat.Regarding?[ie.CustomControlDataType.LookupRegarding]:[ie.CustomControlDataType.LookupSimple];case Je.EntityAttributeType.MultipleLineofText:return[ie.CustomControlDataType.Multiple];case Je.EntityAttributeType.Currency:return[ie.CustomControlDataType.Currency];case Je.EntityAttributeType.Owner:case Je.EntityAttributeType.OwnerType:return[ie.CustomControlDataType.LookupOwner];case Je.EntityAttributeType.PartyList:case Je.EntityAttributeType.PartyListType:return[ie.CustomControlDataType.LookupPartyList];case Je.EntityAttributeType.Status:case Je.EntityAttributeType.OptionSet:return[ie.CustomControlDataType.OptionSet];case Je.EntityAttributeType.SingleLineofText:switch(t){case Je.EntityAttributeTypeFormat.Email:return[ie.CustomControlDataType.SingleLineEmail];case Je.EntityAttributeTypeFormat.Phone:return[ie.CustomControlDataType.SingleLinePhone];case Je.EntityAttributeTypeFormat.Text:return n===pie?[ie.CustomControlDataType.SingleLinePhone]:[ie.CustomControlDataType.SingleLineText];case Je.EntityAttributeTypeFormat.TextArea:return[ie.CustomControlDataType.SingleLineTextArea];case Je.EntityAttributeTypeFormat.TickerSymbol:return[ie.CustomControlDataType.SingleLineTickerSymbol];case Je.EntityAttributeTypeFormat.Url:return[ie.CustomControlDataType.SingleLineURL];default:return[ie.CustomControlDataType.SingleLineText]}case Je.EntityAttributeType.MultiSelectOptionSet:return[ie.CustomControlDataType.MultiSelectOptionSet];default:return null}}vn.manifestTypesForColumn=mie;function RA(e){let t=[],n=e.childNodes;for(let r=0;r<n.length;r+=1)n[r].nodeType===1&&t.push(n[r]);return t}vn.elementChildren=RA;function Ao(e,t){return e.hasAttribute(t)?e.getAttribute(t):null}vn.attr=Ao;function la(e,...t){return RA(e).filter(n=>t.includes(n.tagName))}vn.firstLevel=la;function hie(e){let t=new Map;for(let n of la(e,"type-group"))t.set(String(Ao(n,"name")),la(n,"type").map(r=>String(r.textContent)));for(let[n,r]of t)t.set(n,r.sort());return t}function gie(e){let t=e.getElementsByTagName("AvailableOn")[0];if(!t)return{web:!0,phone:!0,tablet:!0};let n=new Set(RA(t).map(r=>r.tagName));return{web:n.has("web"),phone:n.has("phone"),tablet:n.has("tablet")}}var yie={input:"input",bound:"bound",output:"output"};function bie(e,t,n){let r=Ao(e,"usage"),i=r!==null&&yie[r]||"input",o=Ao(e,"default-value"),a=la(e,"value").map(p=>{let m={name:Ao(p,"name"),value:String(p.textContent),isDefault:Ao(p,"default")==="true"};return m.isDefault&&(o=m.value),m}),s=Ao(e,"of-type-group"),u=s!==null?t.get(s):void 0,l=s!==null&&Object.prototype.hasOwnProperty.call(vn.DEFAULT_TYPE_GROUPS,s)?vn.DEFAULT_TYPE_GROUPS[s]:void 0,c=u?[...u]:l?[...l]:[],d=Ao(e,"of-type"),f=d!==null?d:c.length>0?c[0]:null;return{name:Ao(e,"name"),usage:i,ofType:d,typeGroupName:s,ofTypeGroup:c,defaultType:f||void 0,required:Ao(e,"required")==="true",hidden:Ao(e,"hidden")==="true",defaultValue:o,enumValues:a,isPrimary:n&&i==="bound"}}function dM(e){var t;let n=[],r=a=>s=>n.push(`${a}: ${s}`),i=new fie.DOMParser({errorHandler:{warning:r("warning"),error:r("error"),fatalError:r("fatalError")}}).parseFromString(e,"text/xml"),o=(t=i?.documentElement)!==null&&t!==void 0?t:null;if(!o||n.length>0)throw new Error(`the control manifest does not parse cleanly${n.length>0?` (${n[0]})`:""}`);return o}vn.parseManifestRoot=dM;function fM(e){let t=la(dM(e),"control")[0];if(!t)throw new Error("the control manifest has no <control> element");return t}vn.parseControlElement=fM;function vie(e){let t=fM(e),n=hie(t),r=la(t,"data-set"),i=la(t,"property"),o=la(t,"groups"),a=[],s=!1;for(let l of i){let c=bie(l,n,r.length===0&&!s);s=s||c.isPrimary,a.push(c)}let u=r.length>0||(a.length>0?a[0].usage==="bound":o.some(l=>la(l,"group").some(c=>la(c,"data-set","property").length>0)));return{properties:a,hasDataset:r.length>0,hasGroups:o.length>0,isBound:u,availableOn:gie(t)}}vn.parsePcfManifest=vie});var mM=C(Uc=>{"use strict";Object.defineProperty(Uc,"__esModule",{value:!0});Uc.readPcfColumn=Uc.readControlManifest=void 0;var Fc=ae(),wie=kA();function $A(e,t,n){var r;let i=(r=n?.error)===null||r===void 0?void 0:r.message;return new Error(`${e}: HTTP ${t}${typeof i=="string"?` ${i}`:""}`)}async function Eie(e,t){var n;let r="/customcontrols"+(0,Fc.odataQuery)([["$select","name,manifest"],["$filter",`name eq '${(0,Fc.odataLiteral)(t)}'`]]);try{let i=await e.get(r);if(i.status<200||i.status>=300)return{kind:"unavailable",error:$A(`reading control "${t}"`,i.status,i.body)};let o=(n=i.body)===null||n===void 0?void 0:n.value;if(!Array.isArray(o)||o.some(u=>u===null||typeof u!="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,wie.parsePcfManifest)(s)}}catch(i){return{kind:"unavailable",error:i instanceof Error?i:new Error(String(i))}}}Uc.readControlManifest=Eie;var Aie=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 pM(e){let t=e?.Value;return typeof t=="string"?t:void 0}async function Cie(e,t,n,r){var i;let o=`/EntityDefinitions(LogicalName='${(0,Fc.odataPathLiteral)(t)}')/Attributes(LogicalName='${(0,Fc.odataPathLiteral)(n)}')`,a=r?.requireCreateEligibility===!0;try{let s=await e.get(o+(0,Fc.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:$A(`reading column "${n}"`,s.status,s.body)};let u=(i=s.body)!==null&&i!==void 0?i:{},l=pM(u.AttributeTypeName);if(!l)return{kind:"unavailable",error:new Error(`column "${n}" has no AttributeTypeName`)};if(a&&typeof u.IsValidForCreate!="boolean")return{kind:"unavailable",error:new Error(`column "${n}" has no IsValidForCreate`)};let c={logicalName:typeof u.LogicalName=="string"?u.LogicalName:n,attributeTypeName:l,isValidForForm:u.IsValidForForm===!0,isPrimaryId:u.IsPrimaryId===!0,...a?{isValidForCreate:u.IsValidForCreate}:{}},d=Aie.get(l);if(d){let f=await e.get(`${o}/Microsoft.Dynamics.CRM.${d.cast}`+(0,Fc.odataQuery)([["$select",d.select]]));if(f.status<200||f.status>=300)return{kind:"unavailable",error:$A(`reading the format of column "${n}"`,f.status,f.body)};let p=f.body;if(p===null||typeof p!="object"||p.Format!==null&&typeof p.Format!="string")return{kind:"unavailable",error:new Error(`reading the format of column "${n}": the answer is unreadable \u2014 expected its Format (a string or null)`)};typeof p.Format=="string"&&(c.format=p.Format);let m=pM(p.FormatName);m&&(c.formatName=m)}return{kind:"found",value:c}}catch(s){return{kind:"unavailable",error:s instanceof Error?s:new Error(String(s))}}}Uc.readPcfColumn=Cie});var fl=C(n0=>{"use strict";Object.defineProperty(n0,"__esModule",{value:!0});n0.DEFAULT_LCID=void 0;n0.DEFAULT_LCID=1033});var r0=C(qc=>{"use strict";Object.defineProperty(qc,"__esModule",{value:!0});qc.fnv128Hex=qc.fnv32=void 0;function hM(e){let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return t>>>0}qc.fnv32=hM;function Sie(e,t){let n="";for(let r=0;r<4;r+=1)n+=hM(`${r}:${e}:${t}`).toString(16).padStart(8,"0");return n}qc.fnv128Hex=Sie});var LA=C(Bc=>{"use strict";Object.defineProperty(Bc,"__esModule",{value:!0});Bc.deterministicId=Bc.fnv32=void 0;var Nie=r0(),_ie=r0();Object.defineProperty(Bc,"fnv32",{enumerable:!0,get:function(){return _ie.fnv32}});function Iie(e,t){let n=(0,Nie.fnv128Hex)(e,t);return`${n.slice(0,8)}-${n.slice(8,12)}-${n.slice(12,16)}-${n.slice(16,20)}-${n.slice(20,32)}`}Bc.deterministicId=Iie});var o0=C(Me=>{"use strict";Object.defineProperty(Me,"__esModule",{value:!0});Me.profileTokenFor=Me.parseProfileToken=Me.composeProfileToken=Me.readPermissionRows=Me.canonicalGuid=Me.toFieldPermission=Me.ALLOWED=Me.NOT_ALLOWED=Me.PERMISSION_SELECT=Me.FIELD_SECURITY_PROFILE_PLATFORM_MANAGED_CODE=Me.FIELD_SECURITY_PROFILE_PUSH_NOT_ATOMIC_CODE=Me.FIELD_SECURITY_COLUMN_NOT_SECURED_CODE=Me.FIELD_PERMISSION_UNRECOGNIZED_CODE=Me.SYSTEM_ADMINISTRATOR_FIELD_SECURITY_PROFILE_ID=void 0;var i0=Y(),Tie=LA(),MA=pe(),yM=ae();Me.SYSTEM_ADMINISTRATOR_FIELD_SECURITY_PROFILE_ID="572329c1-a042-4e22-be47-367c6374ea45";Me.FIELD_PERMISSION_UNRECOGNIZED_CODE="FIELD_PERMISSION_UNRECOGNIZED";Me.FIELD_SECURITY_COLUMN_NOT_SECURED_CODE="FIELD_SECURITY_COLUMN_NOT_SECURED";Me.FIELD_SECURITY_PROFILE_PUSH_NOT_ATOMIC_CODE="FIELD_SECURITY_PROFILE_PUSH_NOT_ATOMIC";Me.FIELD_SECURITY_PROFILE_PLATFORM_MANAGED_CODE="FIELD_SECURITY_PROFILE_PLATFORM_MANAGED";Me.PERMISSION_SELECT="fieldpermissionid,entityname,attributelogicalname,canread,cancreate,canupdate,canreadunmasked";Me.NOT_ALLOWED=0;Me.ALLOWED=4;var Oie=new Map([[0,"none"],[1,"oneRecord"],[3,"allRecords"]]);function gM(e,t,n,r,i){var o;return new i0.SdkError(Me.FIELD_PERMISSION_UNRECOGNIZED_CODE,`Field security profile '${e.profileId}': the permission for ${t}.${n} has ${r} = ${(o=JSON.stringify(i))!==null&&o!==void 0?o:"undefined"}, which this SDK cannot represent (accepted: ${r==="canreadunmasked"?"0, 1, 3":"0, 4"}). Refusing rather than misreport the access.`)}function bM(e,t){for(let r of["canread","cancreate","canupdate"])if(e[r]!==Me.NOT_ALLOWED&&e[r]!==Me.ALLOWED)throw gM(t,e.table,e.column,r,e[r]);let n=Oie.get(e.canreadunmasked);if(n===void 0)throw gM(t,e.table,e.column,"canreadunmasked",e.canreadunmasked);return{table:e.table,column:e.column,read:e.canread===Me.ALLOWED,create:e.cancreate===Me.ALLOWED,update:e.canupdate===Me.ALLOWED,...n!=="none"?{readUnmasked:n}:{},id:e.id}}Me.toFieldPermission=bM;var Die=/^[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 Pie(e){if(typeof e=="string")try{return(0,yM.normalizeGuid)(e,"id")}catch{return}}Me.canonicalGuid=Pie;function Rie(e,t,n){let r=[],i=new Set,o=new Set;for(let a of e){let s=a??{},u=s.fieldpermissionid,l=s["@odata.etag"],c=s.entityname,d=s.attributelogicalname;if(typeof u!="string"||!Die.test(u)||!(0,MA.isVersionToken)(l))throw new i0.ConnectionError(n,200,`the permissions of field security profile '${t.profileId}' could not be read: a row has no usable id or version`);if(typeof c!="string"||c===""||typeof d!="string"||d==="")throw new i0.ConnectionError(n,200,`the permissions of field security profile '${t.profileId}' could not be read: a row names no table or column`);let f=(0,yM.normalizeGuid)(u,"fieldpermissionid"),p=`${c}\0${d}`;if(i.has(f)||o.has(p))throw new i0.ConnectionError(n,200,`the permissions of field security profile '${t.profileId}' were read inconsistently: ${i.has(f)?`the row '${f}'`:`the column ${c}.${d}`} appears twice`);i.add(f),o.add(p);let m={id:f,token:l,table:c,column:d,canread:s.canread,cancreate:s.cancreate,canupdate:s.canupdate,canreadunmasked:s.canreadunmasked};bM(m,t),r.push(m)}return r}Me.readPermissionRows=Rie;var kie="fieldSecurityProfile.permissions";function $ie(e){return Object.keys(e).map(t=>[t.toLowerCase(),e[t]]).sort(([t],[n])=>t<n?-1:t>n?1:0).map(([t,n])=>`${t}=${n}`).join(`+`)}function vM(e,t){return`${e} fp${Object.keys(t).length}:${(0,Tie.deterministicId)(kie,$ie(t))}`}Me.composeProfileToken=vM;function wM(e){if(typeof e!="string")return;let t=e.split(" ");if(t.length!==2||!(0,MA.isVersionToken)(t[0]))return;let n=/^fp(0|[1-9][0-9]*):([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/.exec(t[1]);if(n)return{profileToken:t[0],count:Number(n[1]),digest:n[2]}}Me.parseProfileToken=wM;function Lie(e,t){let n=wM(e);if(!n||!t)return;let r=Object.entries(t);return r.length!==n.count||r.some(([,o])=>!(0,MA.isVersionToken)(o))?void 0:vM(n.profileToken,t)===e?n.profileToken:void 0}Me.profileTokenFor=Lie});var s0=C(Qi=>{"use strict";Object.defineProperty(Qi,"__esModule",{value:!0});Qi.readColumnPermissionHolders=Qi.findFieldSecurityProfile=Qi.resolveFieldSecurityProfiles=Qi.fieldSecurityProfileApi=Qi.readFieldPermissions=void 0;var EM=Zo(),Sp=Ke(),Tn=Y(),wr=pe(),Br=ae(),Er=o0(),pl="fieldsecurityprofiles",Cp="fieldpermissions",Ep="lk_fieldpermission_fieldsecurityprofileid",Ap={Prefer:"return=representation"},Mie=/^[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 Np(e){return(0,wr.isVersionToken)(e)&&!e.includes(" ")}function FA(e){return new Tn.SdkError(Er.FIELD_SECURITY_PROFILE_PLATFORM_MANAGED_CODE,`Refusing to ${e} the System Administrator field security profile: it is platform-managed configuration (the platform adds a full-access permission to it for every column it secures). It can be fetched, not written. Nothing was sent.`)}function UA(e){var t;let n=(t=e?.error)===null||t===void 0?void 0:t.code;return typeof n=="string"?n.toLowerCase():void 0}function xie(e){var t;let n=(t=e?.error)===null||t===void 0?void 0:t.message;return typeof n=="string"?n:""}function CM(e,t){var n,r;let i=(r=/for attribute (\S+) with id/i.exec(xie((n=e?.cause)!==null&&n!==void 0?n:e)))===null||r===void 0?void 0:r[1],o=t.filter(s=>s.column===i),a=(o.length===1?o:t).map(s=>`${s.table}.${s.column}`).join(", ");return(0,Tn.attachCause)(new Tn.SdkError(Er.FIELD_SECURITY_COLUMN_NOT_SECURED_CODE,`A field permission names a column that is not secured (${a}); the platform refused the write and nothing was written. Secure the column first \u2014 updateColumn(table, column, { isSecured: true }) \u2014 then push again.`),e)}async function a0(e,t){let n=`/${Cp}${(0,Br.odataQuery)([["$select",Er.PERMISSION_SELECT],["$filter",`_fieldsecurityprofileid_value eq ${t}`],["$orderby","fieldpermissionid"]])}`,r=await(0,Sp.collectPages)(e,n,`the permissions of field security profile '${t}'`);return(0,Er.readPermissionRows)(r,{profileId:t},e.apiUrl(n))}Qi.readFieldPermissions=a0;function xA(e){return Object.fromEntries(e.map(t=>[t.id,t.token]))}function AM(e,t){let n=Object.keys(e);return n.length===Object.keys(t).length&&n.every(r=>Object.prototype.hasOwnProperty.call(t,r)&&t[r]===e[r])}var Fie="Saved, but the profile's permissions on the server could not be proven equal to what was pushed (a schema change \u2014 unsecuring a column, or deleting a column or table \u2014 removes a permission without moving the profile\u2019s version). No version is held for it now: re-fetch it (fetchArtifact) before the next push.";function SM(e){let t=n=>{var r;return(r=(0,Er.canonicalGuid)(n))!==null&&r!==void 0?r:n.toLowerCase()};return{profile:e.profile,creates:e.creates.map(n=>({...n,id:t(n.id)})),updates:e.updates.map(n=>({...n,id:t(n.id)})),deletes:e.deletes.map(n=>({...n,id:t(n.id)}))}}async function Uie(e,t,n){var r,i;let o=(0,Br.normalizeGuid)(t,"id");if(o===Er.SYSTEM_ADMINISTRATOR_FIELD_SECURITY_PROFILE_ID)throw FA("delete");let a=(0,Er.parseProfileToken)(n?.token),s=(r=n?.snapshot)===null||r===void 0?void 0:r.permissions;if(!a||!Array.isArray(s)||s.length!==a.count)throw new Tn.SdkError(wr.DELETE_NO_ETAG_CODE,`Refusing to delete fieldSecurityProfile '${o}': no usable concurrency token is held for it, so the delete could not be made conditional and could remove what another writer changed. Fetch it first (fetchArtifact).`);let u=`/${pl}(${o})`,l=await e.delete(u,{headers:{"If-Match":a.profileToken}});if(l.status===412)throw new Tn.VersionConflictError("fieldSecurityProfile",o,(i=n?.token)!==null&&i!==void 0?i:null,null,"Another writer changed the profile or one of its permissions since it was fetched; nothing was deleted.");if(UA(l.body)==="0x8004f01f")throw new Tn.ArtifactInUseError("fieldSecurityProfile",o,`Refusing to delete fieldSecurityProfile '${o}': another component depends on it; nothing was deleted.`);(0,wr.ensureSuccess)(l,e.apiUrl(u))}async function qie(e,t,n){var r,i;let o=(0,Br.normalizeGuid)(n??"","fieldsecurityprofileid");if(o===Er.SYSTEM_ADMINISTRATOR_FIELD_SECURITY_PROFILE_ID)throw FA("create");let a=SM(t),s={fieldsecurityprofileid:o,name:a.profile.name,...a.profile.description!==void 0&&a.profile.description!==null?{description:a.profile.description}:{},[Ep]:a.creates.map(m=>({fieldpermissionid:m.id,entityname:m.table,attributelogicalname:m.column,canread:m.canread,cancreate:m.cancreate,canupdate:m.canupdate}))},u=`/${pl}${(0,Br.odataQuery)([["$select","name,description"],["$expand",`${Ep}($select=fieldpermissionid,entityname,attributelogicalname,canread,cancreate,canupdate,canreadunmasked)`]])}`,l;try{l=(0,wr.ensureSuccess)(await e.post(u,s,{headers:Ap}),e.apiUrl(u))}catch(m){throw m instanceof Tn.ConnectionError&&UA(m.cause)==="0x8004f508"?CM(m,a.creates):m}let c=(r=l.body)!==null&&r!==void 0?r:{},d=c[Ep],f={},p=Np((0,wr.readEtag)(l))&&Array.isArray(d)&&d.length===a.creates.length;if(p=p&&c[`${Ep}@odata.nextLink`]===void 0,p){let m=new Map(a.creates.map(h=>[h.id,h]));for(let h of d){if(!h||typeof h!="object"||Array.isArray(h)){p=!1;break}let g=h,y=(i=(0,Er.canonicalGuid)(g.fieldpermissionid))!==null&&i!==void 0?i:"",b=m.get(y),E=g["@odata.etag"];if(!b||Object.prototype.hasOwnProperty.call(f,y)||!Np(E)||g.entityname!==b.table||g.attributelogicalname!==b.column||g.canread!==b.canread||g.cancreate!==b.cancreate||g.canupdate!==b.canupdate){p=!1;break}f[y]=E}}return p?{id:o,etag:(0,Er.composeProfileToken)((0,wr.readEtag)(l),f),memberEtags:f}:{id:o,etag:null,warnings:["Saved; the create's answer did not account for every permission, so no version is held for the profile \u2014 re-fetch it (fetchArtifact) before the next push."]}}function Bie(e,t,n){var r,i;if(!(e instanceof Tn.ConnectionError))return e;let o=UA(e.cause),a=(i=(r=/\/fieldpermissions\(([^)]+)\)/.exec(e.url))===null||r===void 0?void 0:r[1])===null||i===void 0?void 0:i.toLowerCase();if(e.statusCode===404&&o==="0x80040217"&&a){let u=[...t.updates,...t.deletes].find(l=>l.id.toLowerCase()===a);if(u)return(0,Tn.attachCause)(new Tn.SdkError(wr.VERSION_CONFLICT_CODE,`The permission for ${u.table}.${u.column} no longer exists on the server \u2014 a schema change (unsecuring its column, or deleting the column or table) removes it without moving the profile's version. Nothing was written; re-fetch.`),e)}if(o==="0x8004f508")return CM(e,t.creates);let s=/\/fieldpermissions$/i.test(e.url.split("?")[0]);return e.statusCode===400&&o==="0x80040203"&&s?(0,Tn.attachCause)(new Tn.SdkError(wr.VERSION_CONFLICT_CODE,`Another writer added a permission for a column this push creates in profile '${n}'. Nothing was written; re-fetch.`),e):e}async function Vie(e,t,n,r,i){let o=(0,Br.normalizeGuid)(t,"id");if(o===Er.SYSTEM_ADMINISTRATOR_FIELD_SECURITY_PROFILE_ID)throw FA("push");let a=SM(n),s=(0,Er.profileTokenFor)(r,i);if(!s||!i)throw new Tn.SdkError(wr.UPDATE_NO_ETAG_CODE,`Refusing to push fieldSecurityProfile '${o}': no usable concurrency token is held for it (none, or one that does not describe the held permission versions), so the write could not be made conditional. Re-fetch the fieldSecurityProfile and re-apply the change.`);let u=a.creates.length+a.updates.length+a.deletes.length>0;if(u&&!e.supportsAtomicBatch)throw new Tn.SdkError(Er.FIELD_SECURITY_PROFILE_PUSH_NOT_ATOMIC_CODE,`Refusing to push fieldSecurityProfile '${o}': changing its permissions is ONE atomic change set, which needs an HttpClient that implements postRaw. Nothing was sent. (A create, or a change to the name or description only, needs no change set.)`);let l=await a0(e,o);if(!AM(xA(l),i))throw new Tn.SdkError(wr.VERSION_CONFLICT_CODE,"The profile's permissions changed since it was fetched \u2014 another writer, or a schema change that removes a permission without moving the profile's version. Nothing was written; re-fetch.");let c={...i},d,f=`/${pl}(${o})`,p=`${f}${(0,Br.odataQuery)([["$select","fieldsecurityprofileid"]])}`;if(u){let y=(0,Br.odataQuery)([["$select","fieldpermissionid"]]),b=[{method:"PATCH",path:f,body:a.profile,etag:s},...a.deletes.map(T=>{var O;return{method:"DELETE",path:`/${Cp}(${T.id})`,etag:(O=i[T.id])!==null&&O!==void 0?O:void 0}}),...a.updates.map(T=>{var O;return{method:"PATCH",path:`/${Cp}(${T.id})${y}`,body:T.set,etag:(O=i[T.id])!==null&&O!==void 0?O:void 0,headers:Ap}}),...a.creates.map(T=>({method:"POST",path:`/${Cp}${y}`,body:{fieldpermissionid:T.id,entityname:T.table,attributelogicalname:T.column,canread:T.canread,cancreate:T.cancreate,canupdate:T.canupdate,"[email protected]":`/${pl}(${o})`},headers:Ap})),{method:"PATCH",path:p,body:{},headers:Ap}],E;try{E=await(0,EM.sendChangeSet)(e,b,`field security profile '${o}'`)}catch(T){throw Bie(T,a,o)}let w=E.map(T=>(0,wr.readEtag)((0,EM.partResponse)(T)));for(let T of a.deletes)delete c[T.id];let _=1+a.deletes.length;a.updates.forEach((T,O)=>{c[T.id]=w[_+O]});let I=_+a.updates.length;a.creates.forEach((T,O)=>{c[T.id]=w[I+O]}),d=w[w.length-1]}else{let y=(0,wr.ensureSuccess)(await e.patch(p,a.profile,{headers:{...Ap,"If-Match":s}}),e.apiUrl(p));d=(0,wr.readEtag)(y)}let m=Np(d)&&Object.values(c).every(y=>Np(y)),h=!1;if(m)try{h=AM(xA(await a0(e,o)),c)}catch{h=!1}if(!h)return{id:o,etag:null,warnings:[Fie]};let g=c;return{id:o,etag:(0,Er.composeProfileToken)(d,g),memberEtags:g}}Qi.fieldSecurityProfileApi={async get(e,t){var n;let r=(0,Br.normalizeGuid)(t,"id"),i=`/${pl}(${r})${(0,Br.odataQuery)([["$select","name,description"]])}`,o=(0,wr.ensureSuccess)(await e.get(i),e.apiUrl(i)),a=(0,wr.readEtag)(o),s=await a0(e,r),u=(n=o.body)!==null&&n!==void 0?n:{},l={fieldsecurityprofileid:r,name:typeof u.name=="string"?u.name:"",description:typeof u.description=="string"?u.description:null,[Ep]:s.map(d=>({fieldpermissionid:d.id,entityname:d.table,attributelogicalname:d.column,canread:d.canread,cancreate:d.cancreate,canupdate:d.canupdate,canreadunmasked:d.canreadunmasked}))},c=xA(s);return{raw:l,etag:Np(a)?(0,Er.composeProfileToken)(a,c):null,memberEtags:c}},async list(e){let t=`/${pl}${(0,Br.odataQuery)([["$select","fieldsecurityprofileid,name"]])}`;return(await(0,Sp.collectPages)(e,t,"listArtifacts('fieldSecurityProfile')")).map(r=>{var i,o;return{type:"fieldSecurityProfile",id:String((i=r.fieldsecurityprofileid)!==null&&i!==void 0?i:""),name:String((o=r.name)!==null&&o!==void 0?o:""),isDirty:!1}})},create(e,t,n){return qie(e,t,n)},update(e,t,n,r,i){return Vie(e,t,n,r,i)},delete(e,t,n){return Uie(e,t,n)}};async function NM(e,t,n){let r=`/${pl}${(0,Br.odataQuery)([["$select","fieldsecurityprofileid,name"],["$filter",`name eq '${(0,Br.odataLiteral)(t)}'`],...n!==void 0?[["$top",String(n)]]:[]])}`,i=e.apiUrl(r),o;if(n===void 0)o=await(0,Sp.collectPages)(e,r,"resolveArtifact('fieldSecurityProfile')");else{let a=(0,wr.ensureSuccess)(await e.get(r),i).body;if(o=a?.value,Array.isArray(o)&&!(0,Sp.boundedPageComplete)(a,o.length,n))throw new Tn.ConnectionError(i,200,"the list of field security profiles is incomplete (the answer says more rows exist), so it proves neither absence nor a single match")}if(!Array.isArray(o))throw new Tn.ConnectionError(i,200,"the response could not be read as a list of field security profiles");return o.map(a=>({id:String(a.fieldsecurityprofileid),name:String(a.name)}))}Qi.resolveFieldSecurityProfiles=NM;async function Gie(e,t){let n=await NM(e,t,2);if(n.length>1)throw new Tn.AmbiguousArtifactError("fieldSecurityProfile",t,n.length);return n.length===1?n[0].id:null}Qi.findFieldSecurityProfile=Gie;async function jie(e,t,n){let r=`/${Cp}${(0,Br.odataQuery)([["$select","fieldpermissionid,_fieldsecurityprofileid_value"],["$filter",`entityname eq '${(0,Br.odataLiteral)(t)}' and attributelogicalname eq '${(0,Br.odataLiteral)(n)}'`],["$orderby","fieldpermissionid"]])}`,i=await(0,Sp.collectPages)(e,r,`the field permissions on ${t}.${n}`),o=new Set;for(let a of i){let s=a?._fieldsecurityprofileid_value;if(typeof a?.fieldpermissionid!="string"||typeof s!="string"||!Mie.test(s))throw new Tn.ConnectionError(e.apiUrl(r),200,`the field permissions on ${t}.${n} could not be classified (a row has no readable profile), so whether unsecuring it would delete another profile\u2019s permission is unknown`);let u=s.toLowerCase();u!==Er.SYSTEM_ADMINISTRATOR_FIELD_SECURITY_PROFILE_ID&&o.add(u)}return[...o]}Qi.readColumnPermissionHolders=jie});var u0=C(Ce=>{"use strict";Object.defineProperty(Ce,"__esModule",{value:!0});Ce.updateTable=Ce.deleteAlternateKey=Ce.createAlternateKey=Ce.deleteGlobalOptionSet=Ce.createGlobalOptionSet=Ce.deleteRelationship=Ce.deleteColumn=Ce.updateColumn=Ce.deleteTable=Ce.createRelationship=Ce.insertStatusValue=Ce.createCustomerColumn=Ce.createColumns=Ce.setColumnVisualization=Ce.getColumnVisualization=Ce.createColumn=Ce.createTable=Ce.resolveUpsertTarget=Ce.resolveEntitySetName=Ce.pluralFallback=void 0;var nt=pe(),he=ae(),ca=fl(),de=Y(),Wie=Zo(),zie=s0(),Hie={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 ln(e,t){return{"@odata.type":"Microsoft.Dynamics.CRM.Label",LocalizedLabels:Kie(e,t)}}var _M=65535;function Kie(e,t){let n=(o,a)=>({"@odata.type":"Microsoft.Dynamics.CRM.LocalizedLabel",Label:o,LanguageCode:a});if(typeof e=="string")return[n(e,t)];let r=Object.entries(e);if(!r.length)throw new de.InvalidArgumentError("a localized label must contain at least one language");let i=new Set;return r.map(([o,a])=>{if(!/^[1-9]\d*$/.test(o))throw new de.InvalidArgumentError(`localized label key '${o}' is not an LCID (expected a canonical positive integer, e.g. 1033)`);let s=Number(o);if(s>_M)throw new de.InvalidArgumentError(`localized label LCID ${s} is out of range (1-${_M})`);if(i.has(s))throw new de.InvalidArgumentError(`localized label LCID ${s} is specified more than once`);if(i.add(s),typeof a!="string")throw new de.InvalidArgumentError(`localized label for LCID ${s} must be a string`);return n(a,s)})}function PM(e){return typeof e=="string"?`${e}s`:Object.fromEntries(Object.entries(e).map(([t,n])=>{if(typeof n!="string")throw new de.InvalidArgumentError(`localized label for LCID ${t} must be a string`);return[t,`${n}s`]}))}Ce.pluralFallback=PM;function _p(e){return{Value:e,CanBeChanged:!0,ManagedPropertyLogicalName:"canmodifyrequirementlevelsettings"}}var IM=["None","ApplicationRequired","Recommended"];function GA(e){let t=e.indexOf("_");return t>0?e.slice(0,t):e}function TM(e,t,n){let r=e[t];r&&typeof r=="object"?r.Value=n:e[t]={Value:n}}function Ip(e){let t=(0,nt.readCreatedId)(e,"MetadataId");if(!t)throw new de.InvalidArgumentError("Dataverse did not return a MetadataId for the created metadata component");return t}var BA=["UserLocal","DateOnly","TimeZoneIndependent"];function RM(e,t){if(!BA.includes(e))throw new de.InvalidArgumentError(`${t}: dateTimeBehavior '${String(e)}' is not one of ${BA.join(", ")}.`);return e}function Jie(e,t,n,r){var i;let o=`'${n}' on '${r}'`,a=e.DateTimeBehavior,s="unreadable";if(a===null?s="missing":a&&typeof a=="object"&&BA.includes(a.Value)&&(s=a.Value),s==="unreadable")throw new de.InvalidArgumentError(`updateColumn: the current DateTimeBehavior of ${o} could not be read, so the SDK will not change it.`);if(s!==t){let u=(i=e.CanChangeDateTimeBehavior)===null||i===void 0?void 0:i.Value;if(u!==!0)throw new de.InvalidArgumentError(typeof u=="boolean"?`updateColumn: CanChangeDateTimeBehavior is false on ${o}; Learn requires it to be true for any change of behaviour, a repair included.`:`updateColumn: CanChangeDateTimeBehavior of ${o} could not be read, so the SDK will not change its behaviour (Learn requires it to be true).`);if(s!=="missing"&&s!=="UserLocal")throw new de.InvalidArgumentError(`updateColumn: ${o} is ${s}, which cannot be changed \u2014 Learn documents DateOnly and TimeZoneIndependent as permanent; only UserLocal may become DateOnly or TimeZoneIndependent.`)}e.DateTimeBehavior={Value:t},t==="DateOnly"&&e.Format!=="DateOnly"&&(e.Format="DateOnly")}var Yie="0x80048550";async function jA(e,t,n){var r,i;let o=n instanceof de.ConnectionError?(i=(r=n.cause)===null||r===void 0?void 0:r.error)===null||i===void 0?void 0:i.code:void 0;if(!(n instanceof de.ConnectionError)||n.statusCode!==400||typeof o!="string"||o.toLowerCase()!==Yie)throw n;let a;try{a=await Qie(e,t)}catch{a=void 0}throw a&&a.length>0?(0,de.attachCause)(new de.DateTimeBehaviorMissingError(t,a),n):n}async function Qie(e,t){var n;let r=`/EntityDefinitions(LogicalName='${(0,he.odataPathLiteral)(t)}')/Attributes/Microsoft.Dynamics.CRM.DateTimeAttributeMetadata`+(0,he.odataQuery)([["$select","LogicalName,DateTimeBehavior"]]),i=await e.get(r);if(i.status<200||i.status>=300)return;let o=(n=i.body)===null||n===void 0?void 0:n.value;if(!Array.isArray(o))return;let a=[];for(let s of o){if(!s||typeof s!="object"||!Object.prototype.hasOwnProperty.call(s,"DateTimeBehavior"))return;let{LogicalName:u,DateTimeBehavior:l}=s;if(typeof u!="string"||u==="")return;l===null&&a.push(u)}return a}function Xie(e,t,n){var r,i,o,a,s,u,l,c,d,f,p,m,h,g,y,b,E,w,_,I,T,O,v,N;if(t.defaultValue!==void 0&&e!=="boolean")throw new de.InvalidArgumentError(`createColumn: 'defaultValue' applies to boolean columns, but '${t.schemaName}' is of type '${e}'.`);if(t.integerFormat!==void 0&&e!=="integer")throw new de.InvalidArgumentError(`createColumn: 'integerFormat' applies to integer columns, but '${t.schemaName}' is of type '${e}'.`);if(t.dateTimeBehavior!==void 0&&e!=="dateTime")throw new de.InvalidArgumentError(`createColumn: 'dateTimeBehavior' applies to dateTime 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:(r=t.maxLength)!==null&&r!==void 0?r: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:(u=t.maxValue)!==null&&u!==void 0?u:2147483647};case"bigint":return{"@odata.type":"Microsoft.Dynamics.CRM.BigIntAttributeMetadata",AttributeType:"BigInt",AttributeTypeName:{Value:"BigIntType"}};case"double":return{"@odata.type":"Microsoft.Dynamics.CRM.DoubleAttributeMetadata",AttributeType:"Double",AttributeTypeName:{Value:"DoubleType"},Precision:(l=t.precision)!==null&&l!==void 0?l:2,MinValue:(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:(y=t.maxValue)!==null&&y!==void 0?y:1e9};case"boolean":return{"@odata.type":"Microsoft.Dynamics.CRM.BooleanAttributeMetadata",AttributeType:"Boolean",AttributeTypeName:{Value:"BooleanType"},DefaultValue:(b=t.defaultValue)!==null&&b!==void 0?b:!1,OptionSet:{"@odata.type":"Microsoft.Dynamics.CRM.BooleanOptionSetMetadata",TrueOption:{Value:1,Label:ln((E=t.trueLabel)!==null&&E!==void 0?E:"Yes",n)},FalseOption:{Value:0,Label:ln((w=t.falseLabel)!==null&&w!==void 0?w:"No",n)}}};case"dateTime":{let S=t.dateTimeBehavior===void 0?"UserLocal":RM(t.dateTimeBehavior,"createColumn");if(S==="DateOnly"&&t.dateFormat==="DateAndTime")throw new de.InvalidArgumentError(`createColumn: dateTimeBehavior 'DateOnly' needs dateFormat 'DateOnly', but '${t.schemaName}' asks for 'DateAndTime' \u2014 Dataverse refuses that pair.`);return{"@odata.type":"Microsoft.Dynamics.CRM.DateTimeAttributeMetadata",AttributeType:"DateTime",AttributeTypeName:{Value:"DateTimeType"},Format:(_=t.dateFormat)!==null&&_!==void 0?_:S==="DateOnly"?"DateOnly":"DateAndTime",DateTimeBehavior:{Value:S}}}case"choice":return OM(t,n,!1);case"multiChoice":return OM(t,n,!0);case"file":return{"@odata.type":"Microsoft.Dynamics.CRM.FileAttributeMetadata",AttributeType:"Virtual",AttributeTypeName:{Value:"FileType"},MaxSizeInKB:(I=t.maxSizeKb)!==null&&I!==void 0?I:10240};case"image":return{"@odata.type":"Microsoft.Dynamics.CRM.ImageAttributeMetadata",AttributeType:"Virtual",AttributeTypeName:{Value:"ImageType"},IsPrimaryImage:(T=t.isPrimaryImage)!==null&&T!==void 0?T:!1,MaxSizeInKB:(O=t.maxSizeKb)!==null&&O!==void 0?O:10240};case"autonumber":if(!(!((v=t.autoNumberFormat)===null||v===void 0)&&v.trim()))throw new de.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:(N=t.maxLength)!==null&&N!==void 0?N:100,AutoNumberFormat:t.autoNumberFormat};default:throw new de.InvalidArgumentError(`unsupported column type '${String(e)}'`)}}function OM(e,t,n){let i={"@odata.type":n?"Microsoft.Dynamics.CRM.MultiSelectPicklistAttributeMetadata":"Microsoft.Dynamics.CRM.PicklistAttributeMetadata",AttributeType:n?"Virtual":"Picklist",AttributeTypeName:{Value:n?"MultiSelectPicklistType":"PicklistType"}};if(e.globalChoiceMetadataId)return i["[email protected]"]=`/GlobalOptionSetDefinitions(${(0,he.normalizeGuid)(e.globalChoiceMetadataId,"globalChoiceMetadataId")})`,i;if(!e.options||e.options.length===0)throw new de.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:ln(o.label,t)}))},i}var Vc=new WeakMap;async function Zie(e,t){var n,r;let i=(n=Vc.get(e))===null||n===void 0?void 0:n.get(t);if(i)return i;let o=`/EntityDefinitions(LogicalName='${(0,he.odataPathLiteral)(t)}')${(0,he.odataQuery)([["$select","EntitySetName"]])}`,s=(r=(0,nt.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||r===void 0?void 0:r.EntitySetName;if(!s)throw new de.InvalidArgumentError(`could not resolve EntitySetName for '${t}'`);(0,he.assertODataName)(s,`server-derived EntitySetName for '${t}'`);let u=Vc.get(e);return u||(u=new Map,Vc.set(e,u)),u.set(t,s),s}Ce.resolveEntitySetName=Zie;var qA=new WeakMap;async function eoe(e,t){var n,r,i;let o=(n=Vc.get(e))===null||n===void 0?void 0:n.get(t),a=(r=qA.get(e))===null||r===void 0?void 0:r.get(t);if(o&&a)return{entitySetName:o,primaryIdAttribute:a};let s=`/EntityDefinitions(LogicalName='${(0,he.odataPathLiteral)(t)}')${(0,he.odataQuery)([["$select","EntitySetName,PrimaryIdAttribute"]])}`,l=(0,nt.ensureSuccess)(await e.get(s),e.apiUrl(s)).body,c=l?.EntitySetName;if(typeof c!="string"||!c)throw new de.InvalidArgumentError(`could not resolve EntitySetName for '${t}'`);(0,he.assertODataName)(c,`server-derived EntitySetName for '${t}'`);let d=Vc.get(e);d||(d=new Map,Vc.set(e,d)),d.has(t)||d.set(t,c);let f=l?.PrimaryIdAttribute;if(typeof f!="string"||!f)throw new de.InvalidArgumentError(`could not resolve PrimaryIdAttribute for '${t}'`);(0,he.assertODataName)(f,`server-derived PrimaryIdAttribute for '${t}'`);let p=qA.get(e);return p||(p=new Map,qA.set(e,p)),p.set(t,f),{entitySetName:(i=d.get(t))!==null&&i!==void 0?i:c,primaryIdAttribute:f}}Ce.resolveUpsertTarget=eoe;async function toe(e,t){var n,r,i,o,a,s,u,l,c,d,f,p,m,h,g;let y=t.primaryColumnRequired;if(y!==void 0&&!IM.includes(y))throw new de.InvalidArgumentError(`createTable: 'primaryColumnRequired' must be one of ${IM.join(", ")}; got '${String(y)}'.`);let b=y!==void 0&&y!=="None";if(b&&!t.primaryColumnAutoNumberFormat&&!e.supportsPut)throw new de.InvalidArgumentError(`createTable: 'primaryColumnRequired: ${y}' 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 E=(n=t.languageCode)!==null&&n!==void 0?n:ca.DEFAULT_LCID,w=GA(t.schemaName),_=(r=t.primaryColumnSchemaName)!==null&&r!==void 0?r:`${w}_Name`,I={"@odata.type":"Microsoft.Dynamics.CRM.StringAttributeMetadata",AttributeType:"String",AttributeTypeName:{Value:"StringType"},SchemaName:_,RequiredLevel:_p(y??"None"),MaxLength:(i=t.primaryColumnMaxLength)!==null&&i!==void 0?i:100,FormatName:{Value:"Text"},DisplayName:ln((o=t.primaryColumnDisplayName)!==null&&o!==void 0?o:"Name",E),IsPrimaryName:!0};t.primaryColumnAutoNumberFormat&&(I.AutoNumberFormat=t.primaryColumnAutoNumberFormat),t.columns&&(MM(t.columns,"createTable"),ioe(t.columns));let T={"@odata.type":"Microsoft.Dynamics.CRM.EntityMetadata",SchemaName:t.schemaName,DisplayName:ln(t.displayName,E),DisplayCollectionName:ln((a=t.pluralName)!==null&&a!==void 0?a:PM(t.displayName),E),OwnershipType:(s=t.ownership)!==null&&s!==void 0?s:"UserOwned",IsActivity:!1,HasActivities:(u=t.hasActivities)!==null&&u!==void 0?u:!1,HasNotes:(l=t.hasNotes)!==null&&l!==void 0?l:!1,Attributes:[I,...((c=t.columns)!==null&&c!==void 0?c:[]).map(X=>WA(X,E))]};t.description&&(T.Description=ln(t.description,E)),t.searchEnabled===!0&&(T.SyncToExternalSearchIndex=!0,T.ChangeTrackingEnabled=!0);let O="/EntityDefinitions",v=(0,nt.ensureSuccess)(await e.post(O,T),e.apiUrl(O)),N=Ip(v),S=`/EntityDefinitions(${N})`+(0,he.odataQuery)([["$select","LogicalName,EntitySetName,PrimaryIdAttribute,PrimaryNameAttribute"]]),R=Math.max(1,Math.trunc((d=t.readBackAttempts)!==null&&d!==void 0?d:6)),x=Math.max(0,(f=t.readBackDelayMs)!==null&&f!==void 0?f:1e3),G=b?` Its primary column's requirement level '${y}' was NOT applied or checked: once the table is readable, set it with updateColumn('${t.schemaName.toLowerCase()}', '${_.toLowerCase()}', { required: '${y}' }).`:"",U;try{U=await kM(e,S,R,x)}catch(X){throw b?(0,de.attachCause)(new de.SdkError("PRIMARY_COLUMN_REQUIRED_NOT_APPLIED",`Table '${t.schemaName}' WAS CREATED (MetadataId ${N}), but reading it back failed (${X instanceof Error?X.message:String(X)}).${G} Do NOT re-run the create \u2014 it will collide on the schema name.`),X):X}if(!U)throw new de.SdkError("TABLE_METADATA_NOT_VISIBLE",`Table '${t.schemaName}' WAS CREATED (MetadataId ${N}) but its metadata was still not readable after ${R} attempt(s). Do NOT re-run the create \u2014 it will collide on the schema name. Re-read /EntityDefinitions(${N}) once the environment catches up, or raise 'readBackAttempts'.${G}`);let M=U.body,q={logicalName:(p=M.LogicalName)!==null&&p!==void 0?p:t.schemaName.toLowerCase(),metadataId:N,entitySetName:(m=M.EntitySetName)!==null&&m!==void 0?m:"",primaryIdAttribute:(h=M.PrimaryIdAttribute)!==null&&h!==void 0?h:`${t.schemaName.toLowerCase()}id`,primaryNameAttribute:(g=M.PrimaryNameAttribute)!==null&&g!==void 0?g:_.toLowerCase()};return b&&(q.primaryColumnRequired=await noe(e,t.schemaName,q,y,R,x)),q}Ce.createTable=toe;async function kM(e,t,n,r){for(let i=1;i<=n;i+=1){let o=await e.get(t);if(o.status>=200&&o.status<300)return o;o.status!==404&&(0,nt.ensureSuccess)(o,e.apiUrl(t)),i<n&&r>0&&await new Promise(a=>setTimeout(a,r))}}async function noe(e,t,n,r,i,o){let a=`/EntityDefinitions(LogicalName='${(0,he.odataPathLiteral)(n.logicalName)}')/Attributes(LogicalName='${(0,he.odataPathLiteral)(n.primaryNameAttribute)}')`+(0,he.odataQuery)([["$select","RequiredLevel"]]),s=async()=>{var d,f;let p=await kM(e,a,i,o),m=(f=(d=p?.body)===null||d===void 0?void 0:d.RequiredLevel)===null||f===void 0?void 0:f.Value;return typeof m=="string"?m:void 0},u="read",l,c=d=>{let f=`its primary column '${n.primaryNameAttribute}'`,p=u==="read"?`${f} could not be read back`:u==="update"?`${f} read '${l??"(unreadable)"}' and the update to '${r}' failed, so it may or may not carry it`:l===void 0?`${f} was updated to '${r}' but could not be read back`:`${f} is still '${l}' after the update to '${r}'`;return new de.SdkError("PRIMARY_COLUMN_REQUIRED_NOT_APPLIED",`Table '${t}' WAS CREATED (MetadataId ${n.metadataId}), but ${p}${d?` (${d})`:""}. Do NOT re-run the create \u2014 it will collide on the schema name. Check the level, and set it with updateColumn('${n.logicalName}', '${n.primaryNameAttribute}', { required: '${r}' }).`)};try{l=await s(),l!==r&&(u="update",await qM(e,n.logicalName,n.primaryNameAttribute,{required:r}),u="verify",l=await s())}catch(d){throw u==="verify"&&(l=void 0),(0,de.attachCause)(c(d instanceof Error?d.message:String(d)),d)}if(l!==r)throw c(l===void 0?"the answer had no RequiredLevel":void 0);return r}function WA(e,t){var n,r;let i=(n=e.languageCode)!==null&&n!==void 0?n:t,o={...Xie(e.type,e,i),SchemaName:e.schemaName,RequiredLevel:_p((r=e.required)!==null&&r!==void 0?r:"None"),DisplayName:ln(e.displayName,i)};return e.description&&(o.Description=ln(e.description,i)),e.sourceType&&e.sourceType!=="Simple"&&(o.SourceType=e.sourceType==="Rollup"?2:1,e.formulaDefinition&&(o.FormulaDefinition=e.formulaDefinition)),$M(o,e),e.isSecured===!0&&(o.IsSecured=!0),o}function $M(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 roe(e,t,n){var r;let i=WA(n,(r=n.languageCode)!==null&&r!==void 0?r:ca.DEFAULT_LCID),o=`/EntityDefinitions(LogicalName='${(0,he.odataPathLiteral)(t)}')/Attributes`,a;try{a=(0,nt.ensureSuccess)(await e.post(o,i),e.apiUrl(o))}catch(u){return jA(e,t,u)}let s={logicalName:n.schemaName.toLowerCase(),metadataId:Ip(a)};if(n.visualization&&n.visualization!=="None")try{await UM(e,t,s.logicalName,s.metadataId,n.visualization)}catch(u){let l=new de.SdkError("COLUMN_VISUALIZATION_BIND_FAILED",`Column '${s.logicalName}' on '${t}' was created, but binding its '${n.visualization}' grid visualization failed; the column exists WITHOUT a visualization. Retry with setColumnVisualization('${t}', '${s.logicalName}', '${n.visualization}'). Cause: ${u instanceof Error?u.message:String(u)}`);throw(0,de.attachCause)(l,u),l}return s}Ce.createColumn=roe;var Gc="/controlconfigurations",LM="CustomRenderersConfiguration",VA={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 MM(e,t){let n=e.find(r=>r.visualization&&r.visualization!=="None");if(n)throw new de.InvalidArgumentError(`${t}: setting 'visualization' on an inline column ('${n.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 ioe(e){let t=e.find(n=>n.isSecured===!0);if(t)throw new de.InvalidArgumentError(`createTable: 'isSecured' on an inline column ('${t.schemaName}') is not supported \u2014 the platform refuses a table create that secures an inline column. Create the table, then call updateColumn(table, column, { isSecured: true }); or add the column with createColumn / createColumns.`)}function xM(e){return JSON.stringify({type:VA[e]})}function ooe(e){if(!e)return"None";let t;try{t=JSON.parse(e)}catch{return"None"}let n=t?.type,r=Object.keys(VA).find(i=>VA[i]===n);return r??"None"}async function FM(e,t,n){var r,i;let o=`entitylogicalname eq '${(0,he.odataLiteral)(t)}' and Attribute/logicalname eq '${(0,he.odataLiteral)(n)}'`,a=`${Gc}${(0,he.odataQuery)([["$select","name,uniquename,metadatajson"],["$expand","Attribute($select=name,logicalname)"],["$filter",o]])}`,u=(i=(r=(0,nt.ensureSuccess)(await e.get(a),e.apiUrl(a)).body)===null||r===void 0?void 0:r.value)!==null&&i!==void 0?i:[],l=n.toLowerCase();return u.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())===l})}async function aoe(e,t,n){var r;let i=`/EntityDefinitions(LogicalName='${(0,he.odataPathLiteral)(t)}')/Attributes(LogicalName='${(0,he.odataPathLiteral)(n)}')${(0,he.odataQuery)([["$select","MetadataId"]])}`,a=(r=(0,nt.ensureSuccess)(await e.get(i),e.apiUrl(i)).body)===null||r===void 0?void 0:r.MetadataId;if(!a)throw new de.InvalidArgumentError(`cannot resolve column '${n}' on '${t}' to set its visualization`);return(0,he.normalizeGuid)(a,"MetadataId")}async function UM(e,t,n,r,i){let o={name:LM,uniquename:`msdyn_${t}_${n}_customrenderers`,metadatajson:xM(i),"[email protected]":`/attributes(${(0,he.normalizeGuid)(r,"MetadataId")})`,entitylogicalname:t};(0,nt.ensureSuccess)(await e.post(Gc,o),e.apiUrl(Gc))}async function soe(e,t,n){var r;let i=await FM(e,t,n);return ooe((r=i[0])===null||r===void 0?void 0:r.metadatajson)}Ce.getColumnVisualization=soe;async function uoe(e,t,n,r){let o=(await FM(e,t,n)).map(l=>l.controlconfigurationid).filter(l=>!!l);if(r==="None"){for(let l of o){let c=`${Gc}(${(0,he.normalizeGuid)(l,"controlconfigurationid")})`;(0,nt.ensureSuccess)(await e.delete(c),e.apiUrl(c))}return}let[a,...s]=o,u=await aoe(e,t,n);if(a){let l=`${Gc}(${(0,he.normalizeGuid)(a,"controlconfigurationid")})`,c={name:LM,metadatajson:xM(r),"[email protected]":`/attributes(${u})`,entitylogicalname:t};(0,nt.ensureSuccess)(await e.patch(l,c),e.apiUrl(l))}else await UM(e,t,n,u,r);for(let l of s){let c=`${Gc}(${(0,he.normalizeGuid)(l,"controlconfigurationid")})`;(0,nt.ensureSuccess)(await e.delete(c),e.apiUrl(c))}}Ce.setColumnVisualization=uoe;async function loe(e,t,n){if(n.length===0)return;if(MM(n,"createColumns"),!e.supportsAtomicBatch)throw new de.InvalidArgumentError(`createColumns writes ${n.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 r=`/EntityDefinitions(LogicalName='${(0,he.odataPathLiteral)(t)}')/Attributes`;try{await(0,Wie.postChangeSet)(e,n.map(i=>{var o;return{method:"POST",path:r,body:WA(i,(o=i.languageCode)!==null&&o!==void 0?o:ca.DEFAULT_LCID)}}),`${n.length} column(s) on '${t}'`)}catch(i){await jA(e,t,i)}}Ce.createColumns=loe;async function coe(e,t,n){var r,i,o,a;let s=(r=n.languageCode)!==null&&r!==void 0?r:ca.DEFAULT_LCID,u=GA(n.schemaName),l=(i=n.accountRelationshipName)!==null&&i!==void 0?i:`${u}_${t}_account`,c=(o=n.contactRelationshipName)!==null&&o!==void 0?o:`${u}_${t}_contact`,d={Lookup:{"@odata.type":"Microsoft.Dynamics.CRM.ComplexLookupAttributeMetadata",SchemaName:n.schemaName,DisplayName:ln(n.displayName,s),RequiredLevel:_p((a=n.required)!==null&&a!==void 0?a:"None"),Targets:["account","contact"]},OneToManyRelationships:[{"@odata.type":"Microsoft.Dynamics.CRM.ComplexOneToManyRelationshipMetadata",SchemaName:l,ReferencedEntity:"account",ReferencingEntity:t},{"@odata.type":"Microsoft.Dynamics.CRM.ComplexOneToManyRelationshipMetadata",SchemaName:c,ReferencedEntity:"contact",ReferencingEntity:t}]};return(0,nt.ensureSuccess)(await e.post("/CreateCustomerRelationships",d),e.apiUrl("/CreateCustomerRelationships")),{logicalName:n.schemaName.toLowerCase(),metadataId:""}}Ce.createCustomerColumn=coe;async function doe(e,t,n){var r,i,o,a,s;let u=(r=n.languageCode)!==null&&r!==void 0?r:ca.DEFAULT_LCID,l={EntityLogicalName:t,AttributeLogicalName:"statuscode",Label:ln(n.label,u),StateCode:(i=n.stateCode)!==null&&i!==void 0?i:0};typeof n.value=="number"&&(l.Value=n.value),n.color&&(l.Color=n.color);let c=(0,nt.ensureSuccess)(await e.post("/InsertStatusValue",l),e.apiUrl("/InsertStatusValue"));return Number((s=(a=(o=c.body)===null||o===void 0?void 0:o.NewOptionValue)!==null&&a!==void 0?a:n.value)!==null&&s!==void 0?s:0)}Ce.insertStatusValue=doe;async function foe(e,t){var n,r,i,o,a;let s=(n=t.languageCode)!==null&&n!==void 0?n:ca.DEFAULT_LCID,u,l;if(t.type==="OneToMany"){if(!t.referencedEntity||!t.referencingEntity)throw new de.InvalidArgumentError("OneToMany relationship requires referencedEntity and referencingEntity");let f=(r=t.lookupSchemaName)!==null&&r!==void 0?r:`${GA(t.schemaName)}_${t.referencedEntity}Id`;l=f.toLowerCase(),u={"@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:_p((i=t.lookupRequired)!==null&&i!==void 0?i:"None"),DisplayName:ln((o=t.lookupDisplayName)!==null&&o!==void 0?o:t.referencedEntity,s)}}}else{if(!t.entity1||!t.entity2)throw new de.InvalidArgumentError("ManyToMany relationship requires entity1 and entity2");u={"@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;try{d=(0,nt.ensureSuccess)(await e.post(c,u),e.apiUrl(c))}catch(f){if(t.type==="OneToMany"&&t.referencingEntity)return jA(e,t.referencingEntity,f);throw f}return{schemaName:t.schemaName,metadataId:Ip(d),lookupLogicalName:l}}Ce.createRelationship=foe;async function poe(e,t){let n=`/EntityDefinitions(LogicalName='${(0,he.odataPathLiteral)(t)}')`;(0,nt.ensureSuccess)(await e.delete(n),e.apiUrl(n))}Ce.deleteTable=poe;function moe(e){return Object.entries(e).every(([t,n])=>t==="isSecured"||t==="languageCode"||n===void 0)}async function qM(e,t,n,r){var i,o;let a=(i=r.languageCode)!==null&&i!==void 0?i:ca.DEFAULT_LCID,s=`/EntityDefinitions(LogicalName='${(0,he.odataPathLiteral)(t)}')/Attributes`,u=r.dateTimeBehavior===void 0?void 0:RM(r.dateTimeBehavior,"updateColumn"),l=`${s}(LogicalName='${(0,he.odataPathLiteral)(n)}')${(0,he.odataQuery)([["$select","MetadataId,AttributeType"]])}`,d=(0,nt.ensureSuccess)(await e.get(l),e.apiUrl(l)).body,f=Hie[(o=d.AttributeType)!==null&&o!==void 0?o:""];if(!d.MetadataId||!f){let y=d.MetadataId?d.AttributeType?`type '${d.AttributeType}' not supported`:"the attribute read returned no AttributeType":"the attribute read returned no MetadataId";throw new de.InvalidArgumentError(`cannot update column '${n}' on '${t}' (${y})`)}let p=(0,he.normalizeGuid)(d.MetadataId,"MetadataId");if(u!==void 0&&d.AttributeType!=="DateTime")throw new de.InvalidArgumentError(`updateColumn: 'dateTimeBehavior' applies to DateTime columns, but '${n}' on '${t}' is of type '${d.AttributeType}'.`);let m=`${s}(${p})/${f}`,h=(0,nt.ensureSuccess)(await e.get(m),e.apiUrl(m)).body;for(let y of Object.keys(h))y.startsWith("@odata.")&&delete h[y];if(h["@odata.type"]=f,r.displayName!==void 0&&(h.DisplayName=ln(r.displayName,a)),r.description!==void 0&&(h.Description=ln(r.description,a)),r.required!==void 0&&(h.RequiredLevel=_p(r.required)),r.maxLength!==void 0&&(h.MaxLength=r.maxLength),r.autoNumberFormat!==void 0&&(h.AutoNumberFormat=r.autoNumberFormat),r.defaultValue!==void 0&&d.AttributeType!=="Boolean")throw new de.InvalidArgumentError(`updateColumn: 'defaultValue' applies to Boolean columns, but '${n}' on '${t}' is of type '${d.AttributeType}'.`);if(r.integerFormat!==void 0&&d.AttributeType!=="Integer")throw new de.InvalidArgumentError(`updateColumn: 'integerFormat' applies to Integer columns, but '${n}' on '${t}' is of type '${d.AttributeType}'.`);if(r.defaultValue!==void 0&&(h.DefaultValue=r.defaultValue),r.integerFormat!==void 0&&(h.Format=r.integerFormat),$M(h,r),u!==void 0&&Jie(h,u,n,t),r.isSecured===!0)h.IsSecured=!0;else if(r.isSecured===!1){if(h.IsSecured!==!0&&moe(r))return;h.IsSecured=!1}let g=`${s}(${p})`;if(r.isSecured===!1){let y=await(0,zie.readColumnPermissionHolders)(e,t,n);if(y.length>0)throw new de.ArtifactInUseError("column",`${t}.${n}`,`Refusing to unsecure ${t}.${n}: ${y.length} field security profile(s) hold a permission on it, and unsecuring a column deletes every permission on it in every profile. Nothing was changed. Remove those permissions from their profiles first.`,y.map(b=>({table:"fieldsecurityprofile",id:b})))}(0,nt.ensureSuccess)(await e.put(g,h,{headers:{"MSCRM.MergeLabels":"true"}}),e.apiUrl(g))}Ce.updateColumn=qM;async function hoe(e,t,n){var r;let i=`/EntityDefinitions(LogicalName='${(0,he.odataPathLiteral)(t)}')/Attributes`,o=`${i}(LogicalName='${(0,he.odataPathLiteral)(n)}')${(0,he.odataQuery)([["$select","MetadataId"]])}`,s=(r=(0,nt.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||r===void 0?void 0:r.MetadataId;if(!s)throw new de.InvalidArgumentError(`column '${n}' not found on '${t}'`);let u=`${i}(${(0,he.normalizeGuid)(s,"MetadataId")})`;(0,nt.ensureSuccess)(await e.delete(u),e.apiUrl(u))}Ce.deleteColumn=hoe;async function goe(e,t){var n,r,i;let o=`/RelationshipDefinitions${(0,he.odataQuery)([["$filter",`SchemaName eq '${(0,he.odataLiteral)(t)}'`],["$select","MetadataId"]])}`,s=(i=(r=(n=(0,nt.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||n===void 0?void 0:n.value)===null||r===void 0?void 0:r[0])===null||i===void 0?void 0:i.MetadataId;if(!s)throw new de.InvalidArgumentError(`relationship '${t}' not found`);let u=`/RelationshipDefinitions(${(0,he.normalizeGuid)(s,"MetadataId")})`;(0,nt.ensureSuccess)(await e.delete(u),e.apiUrl(u))}Ce.deleteRelationship=goe;async function DM(e,t){var n;let r=`/GlobalOptionSetDefinitions(Name='${(0,he.odataPathLiteral)(t)}')${(0,he.odataQuery)([["$select","MetadataId"]])}`,i=await e.get(r);if(i.status===404)return;let a=(n=(0,nt.ensureSuccess)(i,e.apiUrl(r)).body)===null||n===void 0?void 0:n.MetadataId;return a?(0,he.normalizeGuid)(a,"MetadataId"):void 0}async function yoe(e,t){var n;let r=t.name.toLowerCase(),i=await DM(e,r);if(i)return{name:r,metadataId:i};let o=(n=t.languageCode)!==null&&n!==void 0?n:ca.DEFAULT_LCID,a={"@odata.type":"Microsoft.Dynamics.CRM.OptionSetMetadata",Name:r,DisplayName:ln(t.displayName,o),IsGlobal:!0,OptionSetType:"Picklist",Options:t.options.map(u=>({Value:u.value,Label:ln(u.label,o)}))};t.description&&(a.Description=ln(t.description,o));let s="/GlobalOptionSetDefinitions";try{let u=(0,nt.ensureSuccess)(await e.post(s,a),e.apiUrl(s));return{name:r,metadataId:Ip(u)}}catch(u){let l;try{l=await DM(e,r)}catch{l=void 0}if(l)return{name:r,metadataId:l};throw u}}Ce.createGlobalOptionSet=yoe;async function boe(e,t){let n=`/GlobalOptionSetDefinitions(Name='${(0,he.odataPathLiteral)(t.toLowerCase())}')`;(0,nt.ensureSuccess)(await e.delete(n),e.apiUrl(n))}Ce.deleteGlobalOptionSet=boe;async function voe(e,t,n){var r;let i=(r=n.languageCode)!==null&&r!==void 0?r:ca.DEFAULT_LCID,o={"@odata.type":"Microsoft.Dynamics.CRM.EntityKeyMetadata",SchemaName:n.schemaName,DisplayName:ln(n.displayName,i),KeyAttributes:n.keyAttributes},a=`/EntityDefinitions(LogicalName='${(0,he.odataPathLiteral)(t)}')/Keys`,s=(0,nt.ensureSuccess)(await e.post(a,o),e.apiUrl(a));return{logicalName:n.schemaName.toLowerCase(),metadataId:Ip(s)}}Ce.createAlternateKey=voe;async function woe(e,t,n){var r;let i=`/EntityDefinitions(LogicalName='${(0,he.odataPathLiteral)(t)}')/Keys`,o=`${i}(LogicalName='${(0,he.odataPathLiteral)(n.toLowerCase())}')${(0,he.odataQuery)([["$select","MetadataId"]])}`,s=(r=(0,nt.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||r===void 0?void 0:r.MetadataId;if(!s)throw new de.InvalidArgumentError(`alternate key '${n}' not found on '${t}'`);let u=`${i}(${(0,he.normalizeGuid)(s,"MetadataId")})`;(0,nt.ensureSuccess)(await e.delete(u),e.apiUrl(u))}Ce.deleteAlternateKey=woe;function Eoe(e,t,n){var r;let i=t.ChangeTrackingEnabled===!0;if(n.changeTrackingEnabled===!1&&i)throw new de.InvalidArgumentError(`updateTable('${e}'): change tracking is on and cannot be turned off \u2014 the platform keeps it on (it would accept the write and change nothing). Nothing was written.`);if(n.searchEnabled!==!0)return;if(n.changeTrackingEnabled===!1)throw new de.InvalidArgumentError(`updateTable('${e}'): searchEnabled: true contradicts changeTrackingEnabled: false \u2014 Dataverse search needs change tracking. Nothing was written.`);if(!i&&n.changeTrackingEnabled!==!0)throw new de.InvalidArgumentError(`updateTable('${e}'): searchEnabled: true turns on change tracking, which can never be turned off again. Pass changeTrackingEnabled: true in the same call to confirm. Nothing was written.`);if(((r=t.CanEnableSyncToExternalSearchIndex)===null||r===void 0?void 0:r.Value)===!1)throw new de.TableSearchNotAllowedError(e)}async function Aoe(e,t,n){var r;let i=(r=n.languageCode)!==null&&r!==void 0?r:ca.DEFAULT_LCID,o=`/EntityDefinitions(LogicalName='${(0,he.odataPathLiteral)(t)}')`,s=(0,nt.ensureSuccess)(await e.get(o),e.apiUrl(o)).body,u=s.MetadataId;if(!u)throw new de.InvalidArgumentError(`table '${t}' not found`);let l=(0,he.normalizeGuid)(u,"MetadataId");Eoe(t,s,n);for(let d of Object.keys(s))d.startsWith("@odata.")&&delete s[d];s["@odata.type"]="Microsoft.Dynamics.CRM.EntityMetadata",n.displayName!==void 0&&(s.DisplayName=ln(n.displayName,i)),n.pluralName!==void 0&&(s.DisplayCollectionName=ln(n.pluralName,i)),n.description!==void 0&&(s.Description=ln(n.description,i)),n.auditEnabled!==void 0&&TM(s,"IsAuditEnabled",n.auditEnabled),n.duplicateDetectionEnabled!==void 0&&TM(s,"IsDuplicateDetectionEnabled",n.duplicateDetectionEnabled),n.changeTrackingEnabled!==void 0&&(s.ChangeTrackingEnabled=n.changeTrackingEnabled),n.searchEnabled===!0?(s.SyncToExternalSearchIndex=!0,s.ChangeTrackingEnabled=!0):n.searchEnabled===!1&&(s.SyncToExternalSearchIndex=!1),n.quickCreateEnabled!==void 0&&(s.IsQuickCreateEnabled=n.quickCreateEnabled),n.iconVectorName!==void 0&&(s.IconVectorName=n.iconVectorName),n.iconSmallName!==void 0&&(s.IconSmallName=n.iconSmallName),n.iconMediumName!==void 0&&(s.IconMediumName=n.iconMediumName),n.iconLargeName!==void 0&&(s.IconLargeName=n.iconLargeName);let c=`/EntityDefinitions(${l})`;(0,nt.ensureSuccess)(await e.put(c,s,{headers:{"MSCRM.MergeLabels":"true"}}),e.apiUrl(c))}Ce.updateTable=Aoe});var VM=C(jc=>{"use strict";Object.defineProperty(jc,"__esModule",{value:!0});jc.getSearchSettings=jc.configuredIndexFieldCount=void 0;var c0=Ke(),Coe=pe(),zA=ae(),HA=Y(),Soe="isexternalsearchindexenabled,quickfindrecordlimitenabled,usequickfindviewforgridsearch",Noe="LogicalName,SyncToExternalSearchIndex,ChangeTrackingEnabled,CanEnableSyncToExternalSearchIndex",_oe="Attributes($select=LogicalName,AttributeType,IsSearchable,IsFilterable,IsRetrievable,IsPrimaryId,IsPrimaryName)",Ioe=new Set(["ownerid","owningbusinessunit","businessunitid","versionnumber","statecode","statuscode","entityimage_url","createdon","modifiedon"]),Toe=new Set(["Lookup","Customer","Owner"]),Ooe=new Set(["Boolean","Picklist","State","Status"]);function BM(e){let t=0;for(let n of e){if(!(n.IsSearchable||n.IsFilterable||n.IsRetrievable)||n.IsPrimaryId||n.IsPrimaryName||Ioe.has(String(n.LogicalName)))continue;let r=String(n.AttributeType);t+=Toe.has(r)?3:Ooe.has(r)?2:1}return t}jc.configuredIndexFieldCount=BM;function Doe(e){var t,n;let r=e?.response;if(typeof r!="string")return"unknown";let i;try{i=(n=(t=JSON.parse(r))===null||t===void 0?void 0:t.value)===null||n===void 0?void 0:n.status}catch{return"unknown"}switch(String(i).toLowerCase()){case"notprovisioned":case"0":return"notProvisioned";case"provisioninginprogress":case"1":return"provisioningInProgress";case"provisioned":case"2":return"provisioned";default:return"unknown"}}async function Poe(e){let t;try{t=await e.get("/searchstatus")}catch{return"unknown"}return t.status>=200&&t.status<300?Doe(t.body):"unknown"}var l0=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Roe=["isexternalsearchindexenabled","quickfindrecordlimitenabled","usequickfindviewforgridsearch"],koe=["IsSearchable","IsFilterable","IsRetrievable","IsPrimaryId","IsPrimaryName"];function as(e,t,n){return new HA.ConnectionError(e,t,`getSearchSettings: ${n}; an unreadable answer is never reported as a search configuration.`)}function $oe(e,t){var n;let r=(n=e.body)===null||n===void 0?void 0:n.value;if(!Array.isArray(r))throw as(t,e.status,`the organization answer has no rows (${(0,c0.describeMalformedValue)(r)})`);let i=r[0];if(r.length!==1||!l0(i))throw as(t,e.status,`the organization answer holds ${r.length} row(s), not one organization`);let o=Roe.find(a=>typeof i[a]!="boolean");if(o)throw as(t,e.status,`the organization's '${o}' is not a boolean`);return i}function Loe(e,t){if(!l0(e)||typeof e.LogicalName!="string"||e.LogicalName==="")throw as(t,200,"a table row without its LogicalName");let n=e.LogicalName,r=["SyncToExternalSearchIndex","ChangeTrackingEnabled"].find(s=>typeof e[s]!="boolean");if(r)throw as(t,200,`table '${n}': '${r}' is not a boolean`);let i=e.CanEnableSyncToExternalSearchIndex;if(!l0(i)||typeof i.Value!="boolean")throw as(t,200,`table '${n}': 'CanEnableSyncToExternalSearchIndex' has no boolean Value`);let o=e["[email protected]"];if((0,c0.moreRecordsClaim)(e,"Attributes")!=="none"||o!=null)throw as(t,200,`table '${n}': its attributes were answered incompletely`);let a=e.Attributes;if(!Array.isArray(a))throw as(t,200,`table '${n}': its attributes are ${(0,c0.describeMalformedValue)(a)}`);for(let s of a)if(!l0(s)||typeof s.LogicalName!="string"||typeof s.AttributeType!="string"||koe.some(u=>typeof s[u]!="boolean"))throw as(t,200,`table '${n}': an attribute without its name, type or search flags`);return e}function Moe(e){var t,n,r;let i=(t=e.Attributes)!==null&&t!==void 0?t:[],o=e.SyncToExternalSearchIndex===!0,a=e.ChangeTrackingEnabled===!0;return{entityLogicalName:String((n=e.LogicalName)!==null&&n!==void 0?n:""),syncToSearchIndex:o,changeTrackingEnabled:a,searchEnabled:o&&a,canEnableSearch:((r=e.CanEnableSyncToExternalSearchIndex)===null||r===void 0?void 0:r.Value)===!0,configuredSearchableColumns:i.filter(s=>s.IsSearchable===!0&&typeof s.LogicalName=="string").map(s=>String(s.LogicalName)).sort(),configuredIndexFieldCount:BM(i)}}async function xoe(e,t={}){let n=t.tables;if(n!==void 0){if(!Array.isArray(n))throw new HA.InvalidArgumentError("getSearchSettings: tables must be an array of table logical names.");n.forEach((l,c)=>{if(typeof l!="string"||l.trim()==="")throw new HA.InvalidArgumentError(`getSearchSettings: tables[${c}] must be a non-empty table logical name, got ${JSON.stringify(l)}.`)})}let r=n===void 0?void 0:[...new Set(n.map(l=>l.toLowerCase()))],i=`/organizations${(0,zA.odataQuery)([["$select",Soe]])}`,o=e.apiUrl(i),a=$oe((0,Coe.ensureSuccess)(await e.get(i),o),o),s=await Poe(e),u=[];if(r===void 0||r.length>0){let l=r===void 0?"SyncToExternalSearchIndex eq true":r.map(p=>`LogicalName eq '${(0,zA.odataLiteral)(p)}'`).join(" or "),c=`/EntityDefinitions${(0,zA.odataQuery)([["$select",Noe],["$expand",_oe],["$filter",l]])}`,d=e.apiUrl(c),f=(await(0,c0.collectPages)(e,c,"getSearchSettings")).map(p=>Moe(Loe(p,d)));u=r===void 0?f:r.map(p=>f.find(m=>m.entityLogicalName.toLowerCase()===p)).filter(p=>p!==void 0)}return{environment:{dataverseSearchEnabled:a.isexternalsearchindexenabled,indexStatus:s,quickFindRecordLimitEnabled:a.quickfindrecordlimitenabled,gridSearchUsesQuickFindView:a.usequickfindviewforgridsearch},tables:u}}jc.getSearchSettings=xoe});var KM=C(On=>{"use strict";Object.defineProperty(On,"__esModule",{value:!0});On.recoverFormCreate=On.solutionMembershipProblem=On.formWriteMismatches=On.validateExistingForm=On.formExistsAtId=On.isFormRecordAt=On.MAIN_FORM_TYPE=void 0;var Wc=ae(),GM=Ke(),jM=il();On.MAIN_FORM_TYPE=2;function d0(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function f0(e){return e instanceof Error?e.message:String(e)}function KA(e,t){if(typeof e!="string"||typeof t!="string")return!1;try{return(0,Wc.normalizeGuid)(e,"a GUID")===(0,Wc.normalizeGuid)(t,"a GUID")}catch{return!1}}function JA(e,t){return d0(e)&&KA(e.formid,t)}On.isFormRecordAt=JA;async function Foe(e,t){try{return JA((await e()).raw,t)}catch{return!1}}On.formExistsAtId=Foe;function WM(e,t){let n=e.raw;if(!d0(n))return{problem:"it is not a record"};if(!JA(n,t))return{problem:"its formid is not the id this create sent"};if(n.type!==On.MAIN_FORM_TYPE)return{problem:`its type is not ${On.MAIN_FORM_TYPE} (a Main form)`};if(typeof n.objecttypecode!="string")return{problem:"its objecttypecode is not a string"};if(typeof n.name!="string")return{problem:"its name is not a string"};if(typeof n.formxml!="string"||n.formxml.length===0)return{problem:"its formxml is not a non-empty string"};if(typeof n.formpresentation!="number")return{problem:"its formpresentation is not a number"};if(typeof n.formactivationstate!="number")return{problem:"its formactivationstate is not a number"};for(let o of["uniquename","description"]){let a=n[o];if(a!=null&&typeof a!="string")return{problem:`its ${o} is neither a string nor null`}}let r=n["@odata.etag"];if(r!==void 0&&typeof r!="string")return{problem:"its @odata.etag is not a string"};if(r!==void 0&&e.etag!==null&&e.etag!==r)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:n,etag:i}}On.validateExistingForm=WM;function zM(e,t){let n=[];for(let i of["formxml","name","objecttypecode","type"])e[i]!==t[i]&&n.push(i);let r=t.description;if(r!==void 0){let i=e.description;typeof r=="string"&&(r===""?i==null||i==="":i===r)||n.push("description")}return n}On.formWriteMismatches=zM;async function HM(e,t){let n=e.solutionName;if(n)try{let r=await(0,GM.collectPages)(e,`/solutions${(0,Wc.odataQuery)([["$select","solutionid,uniquename"],["$filter",`uniquename eq '${(0,Wc.odataLiteral)(n)}'`]])}`,"createRecovery solution lookup");if(r.length!==1)return`the configured solution '${n}' resolves to ${r.length} solutions, not exactly one`;let[i]=r,o;return d0(i)&&typeof i.uniquename=="string"&&typeof i.solutionid=="string"&&i.uniquename.toLowerCase()===n.toLowerCase()&&(o=(0,Wc.normalizeGuid)(i.solutionid,"solutionid")),o===void 0?`the configured solution '${n}' did not resolve to a valid solution of that name`:(await(0,GM.collectPages)(e,`/solutioncomponents${(0,Wc.odataQuery)([["$select","objectid,componenttype,_solutionid_value"],["$filter",`_solutionid_value eq ${o} and componenttype eq ${jM.SolutionComponentType.SystemForm} and objectid eq ${t}`]])}`,"createRecovery solution membership")).some(u=>d0(u)&&u.componenttype===jM.SolutionComponentType.SystemForm&&KA(u.objectid,t)&&KA(u._solutionid_value,o))?void 0:`the form is not a component of the configured solution '${n}'`}catch(r){return`membership in the configured solution '${n}' could not be established (${f0(r)})`}}On.solutionMembershipProblem=HM;async function Uoe(e){try{return await qoe(e)}catch(t){return{refused:`the recovery could not be completed (${f0(t)})`}}}On.recoverFormCreate=Uoe;async function qoe(e){let{client:t,read:n,sent:r,authoredFormType:i,project:o}=e;if(i!=="Main"||r.type!==On.MAIN_FORM_TYPE)return{refused:`only a Main form is adopted (this one is authored as ${String(i)})`};let a=r.formid;if(typeof a!="string")return{refused:"the create sent no formid to look for"};let s;try{s=await n()}catch(f){return{refused:`the existing row could not be read (${f0(f)})`}}let u=WM(s,a);if("problem"in u)return{refused:`the existing row cannot be trusted: ${u.problem}`};let l=zM(u.record,r);if(l.length>0)return{refused:`the existing row is not what this create wrote (it differs in ${l.join(", ")})`};let c;try{c=o(u.record)}catch(f){return{refused:`the existing row could not be read into a form (${f0(f)})`}}let d=await HM(t,a);return d!==void 0?{refused:d}:{adopted:{artifact:c,etag:u.etag}}}});var p0=C(Xt=>{"use strict";Object.defineProperty(Xt,"__esModule",{value:!0});Xt.disassociateRecords=Xt.associateRecords=Xt.createRecordsBulk=Xt.upsertRecord=Xt.queryAllRecords=Xt.queryRecords=Xt.getRecord=Xt.deleteRecord=Xt.updateRecord=Xt.createRecord=void 0;var QA=Ke(),pi=pe(),ar=ae(),$i=Y(),Co=u0();function Tp(e){let t=e,n=!1,r={};for(let i of Object.keys(t)){let o=t[i];Array.isArray(o)&&o.every(a=>typeof a=="number")?(r[i]=o.join(","),n=!0):r[i]=o}return n?r:e}async function Boe(e,t,n){let i=`/${await(0,Co.resolveEntitySetName)(e,t)}`,o=(0,pi.ensureSuccess)(await e.post(i,Tp(n)),e.apiUrl(i)),a=(0,pi.readCreatedId)(o,`${t}id`);if(!a)throw new $i.InvalidArgumentError(`Dataverse did not return an id for the created '${t}' row`);return{id:a,entityType:t}}Xt.createRecord=Boe;async function Voe(e,t,n,r){let i=(0,ar.normalizeGuid)(n,"id"),a=`/${await(0,Co.resolveEntitySetName)(e,t)}(${i})`;(0,pi.ensureSuccess)(await e.patch(a,Tp(r)),e.apiUrl(a))}Xt.updateRecord=Voe;async function Goe(e,t,n){let r=(0,ar.normalizeGuid)(n,"id"),o=`/${await(0,Co.resolveEntitySetName)(e,t)}(${r})`;(0,pi.ensureSuccess)(await e.delete(o),e.apiUrl(o))}Xt.deleteRecord=Goe;async function joe(e,t,n,r){let i=(0,ar.normalizeGuid)(n,"id"),o=await(0,Co.resolveEntitySetName)(e,t),a=(0,ar.odataQuery)([["$select",r&&r.length>0?r.join(","):void 0]]),s=`/${o}(${i})${a}`,u=(0,pi.ensureSuccess)(await e.get(s),e.apiUrl(s)),l=u.body;if(l===null||typeof l!="object"||Array.isArray(l))throw new $i.ConnectionError(e.apiUrl(s),u.status,`getRecord: read returned a malformed row \u2014 expected an OData entity object but got ${Array.isArray(l)?"an array":(0,QA.describeMalformedValue)(l)}; refusing to read it as a row.`);return l}Xt.getRecord=joe;function Woe(e){return e?.fetchXml?(0,ar.odataQuery)([["fetchXml",e.fetchXml]]):(0,ar.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 YM(e,t,n){var r;if(n?.paginate){if(n.top!==void 0)throw new $i.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(n.fetchXml)throw new $i.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,Co.resolveEntitySetName)(e,t)}${Woe(n)}`;if(n?.paginate)return(0,QA.collectPages)(e,o,"queryRecords");let a=(0,pi.ensureSuccess)(await e.get(o),e.apiUrl(o)),s=(r=a.body)===null||r===void 0?void 0:r.value;if(!Array.isArray(s))throw new $i.ConnectionError(e.apiUrl(o),a.status,`queryRecords: read returned a malformed page \u2014 expected an OData 'value' array but got ${(0,QA.describeMalformedValue)(s)}; refusing to read it as rows.`);return s}Xt.queryRecords=YM;async function zoe(e,t,n){return YM(e,t,{...n,paginate:!0})}Xt.queryAllRecords=zoe;function Hoe(e){if("id"in e)return`(${(0,ar.normalizeGuid)(e.id,"id")})`;let t=typeof e.value=="string"?`'${(0,ar.odataPathLiteral)(e.value)}'`:e.value;return`(${(0,ar.assertODataName)(e.key,"alternate key name")}=${t})`}function JM(e){if(e===201)return!0;if(e===200)return!1}function Koe(e){if(e===void 0)return!1;let t=e!==null&&typeof e=="object"?Object.getPrototypeOf(e):void 0;if(t!==Object.prototype&&t!==null)throw new $i.InvalidArgumentError("upsertRecord: `options` must be a plain object, e.g. { reportCreated: true }");let n=e.reportCreated;if(n!==void 0&&typeof n!="boolean")throw new $i.InvalidArgumentError(`upsertRecord: \`reportCreated\` must be true or false, not ${n===null?"null":typeof n}`);return n===!0}async function Joe(e,t,n,r,i){let o=Koe(i),a=Hoe(n);if(!o){let g=`/${await(0,Co.resolveEntitySetName)(e,t)}${a}`,y=(0,pi.ensureSuccess)(await e.patch(g,Tp(r)),e.apiUrl(g)),b=(0,pi.readCreatedId)(y,`${t}id`);return{id:b??("id"in n?(0,ar.normalizeGuid)(n.id,"id"):""),created:JM(y.status)}}let s=await(0,Co.resolveUpsertTarget)(e,t),u=(0,pi.echoWrite)(s.primaryIdAttribute),l=`/${s.entitySetName}${a}${u.query}`,c=e.apiUrl(l),d=Tp(r),f;try{f=await e.patch(l,d,u.options)}catch(h){throw YA(t,n,h instanceof $i.ConnectionError?h:new $i.ConnectionError(c,0,String(h),h))}if(f.status<200||f.status>=300)throw YA(t,n,new $i.ConnectionError(c,f.status,(0,pi.extractErrorMessage)(f.body),f.body));let p;try{p=(0,pi.readCreatedId)(f,s.primaryIdAttribute)}catch(h){throw YA(t,n,new $i.ConnectionError(c,f.status,`the answer's primary id could not be read: ${h instanceof Error?h.message:String(h)}`,h))}return{id:p??("id"in n?(0,ar.normalizeGuid)(n.id,"id"):""),created:JM(f.status)}}Xt.upsertRecord=Joe;function YA(e,t,n){var r,i;let o=(i=(r=n.cause)===null||r===void 0?void 0:r.error)===null||i===void 0?void 0:i.code,a=typeof o=="string"&&o?o:void 0,s="id"in t?`id ${t.id}`:`${t.key} = ${String(t.value)}`,u=a?`${n.message} [${a}]`:n.message,c=n.statusCode>=200&&n.statusCode<300?`was acknowledged, but its answer could not be read \u2014 ${u}. The row was most likely written; whether it was inserted or updated, and its id, are unknown. `:`failed after it was sent \u2014 ${u}. The row MAY have been written: Dataverse was asked to read it back, and this failure does not say whether the write happened first. `;return new $i.UpsertOutcomeUnknownError(e,t,n.statusCode,a,`Upsert of '${e}' (${s}) with reportCreated ${c}Nothing was re-sent. Read the row by its key before deciding to re-run; re-running the same upsert writes the same values again.`,n)}async function Yoe(e,t,n){var r,i;if(n.length===0)return[];let o=await(0,Co.resolveEntitySetName)(e,t),a=n.map(c=>({"@odata.type":`Microsoft.Dynamics.CRM.${t}`,...Tp(c)})),s=`/${o}/Microsoft.Dynamics.CRM.CreateMultiple`,l=(i=(r=(0,pi.ensureSuccess)(await e.post(s,{Targets:a}),e.apiUrl(s)).body)===null||r===void 0?void 0:r.Ids)!==null&&i!==void 0?i:[];if(l.length!==n.length)throw new $i.InvalidArgumentError(`CreateMultiple on '${t}' returned ${l.length} id(s) for ${n.length} row(s)`);return l}Xt.createRecordsBulk=Yoe;async function Qoe(e,t,n,r){let i=(0,ar.normalizeGuid)(n,"id"),o=(0,ar.normalizeGuid)(r.targetId,"targetId"),a=await(0,Co.resolveEntitySetName)(e,t),s=await(0,Co.resolveEntitySetName)(e,r.targetEntity),u=(0,ar.assertODataName)(r.relationshipName,"relationshipName"),l=`/${a}(${i})/${u}/$ref`,c={"@odata.id":e.apiUrl(`/${s}(${o})`)};(0,pi.ensureSuccess)(await e.post(l,c),e.apiUrl(l))}Xt.associateRecords=Qoe;async function Xoe(e,t,n,r,i){let o=(0,ar.normalizeGuid)(n,"id"),a=(0,ar.normalizeGuid)(i,"targetId"),s=await(0,Co.resolveEntitySetName)(e,t),u=(0,ar.assertODataName)(r,"relationshipName"),l=`/${s}(${o})/${u}(${a})/$ref`;(0,pi.ensureSuccess)(await e.delete(l),e.apiUrl(l))}Xt.disassociateRecords=Xoe});var h0=C(m0=>{"use strict";Object.defineProperty(m0,"__esModule",{value:!0});m0.HEADER_NAV_BOOLEAN_RULE=void 0;m0.HEADER_NAV_BOOLEAN_RULE="headerAndNavigationRefresh-must-be-boolean"});var XA=C(So=>{"use strict";Object.defineProperty(So,"__esModule",{value:!0});So.classifyValueAnswer=So.parseVariableToken=So.composeVariableToken=So.UNSETTLED_TOKEN=void 0;var nu=pe();So.UNSETTLED_TOKEN="?";var Zoe=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function eae(e,t){return(0,nu.isVersionToken)(e)?t===void 0?e:`${e} ${t.rowId}=${t.token}`:null}So.composeVariableToken=eae;function tae(e,t){if(typeof e!="string")return{kind:"none"};let n=e.split(" ");if(n.length<1||n.length>2||n.some(s=>s==="")||!(0,nu.isVersionToken)(n[0]))return{kind:"none"};let r=n[0];if(n.length===1)return t===null?{kind:"versioned",definition:r}:{kind:"none"};let i=n[1].indexOf("="),o=i===-1?"":n[1].slice(0,i),a=i===-1?"":n[1].slice(i+1);return Zoe.test(o)?a===So.UNSETTLED_TOKEN?{kind:"unsettled",definition:r,rowId:o}:!(0,nu.isVersionToken)(a)||t===null||o!==t.toLowerCase()?{kind:"none"}:{kind:"versioned",definition:r,value:{rowId:o,token:a}}:{kind:"none"}}So.parseVariableToken=tae;function nae(e,t){if(!("response"in t))return"unknown";let{response:n}=t,r=n.status;return r>=200&&r<300?e==="DELETE"?"deleted":(0,nu.isVersionToken)((0,nu.readEtag)(n))?"written":"unversioned":r===0||nu.AMBIGUOUS_WRITE_STATUSES.has(r)?"unknown":r===500&&((0,nu.isSqlDeadlockVictim)(n)||(0,nu.isTransactionNotStarted)(n))?"refused":r>=500||r<400?"unknown":"refused"}So.classifyValueAnswer=nae});var g0=C(Xi=>{"use strict";Object.defineProperty(Xi,"__esModule",{value:!0});Xi.isTransportFailure=Xi.variableTransportFailure=Xi.variableRefusal=Xi.isValueConflict=Xi.platformErrorCode=void 0;var Op=Y(),rae=XA(),iae=pe(),oae=new Set(["0x80040217","0x80040216","0x80072013"]),aae=new Set(["0x80040216"]),sae={"0x80072040":"the caller cannot reach the Key Vault the reference names (or the reference is wrong)","0x80072049":"the value is not an Azure Key Vault secret reference","0x80044331":"a value is longer than the platform allows","0x80040265":"the platform refused the row (for a Secret: an empty reference is not accepted)","0x8004f01f":"another component (a flow, an app) depends on it"};function eC(e){var t;let n=(t=e?.error)===null||t===void 0?void 0:t.code;return typeof n=="string"&&/^0x[0-9a-f]{1,8}$/i.test(n)?n.toLowerCase():void 0}Xi.platformErrorCode=eC;function ZA(e){let t=e.schemaName?` '${e.schemaName}'`:"",n=e.rowId?`, value row ${e.rowId}`:"";return`${e.operation} of environment variable${t} (${e.id}${n})`}function QM(e){if(e.status===412)return!0;let t=eC(e.body);return t!==void 0&&oae.has(t)&&(e.status===400||e.status===404&&t==="0x80040217")}Xi.isValueConflict=QM;function uae(e,t,n,r){let i=eC(n.body),o=r==="value"?QM(n):n.status===412||i!==void 0&&aae.has(i),a=i===void 0?void 0:sae[i],s=(0,rae.classifyValueAnswer)("PATCH",{response:n})==="unknown",u=`HTTP ${n.status}${i?` ${i}`:""}`+(a?` \u2014 ${a}`:""),l=(s?`${ZA(e)} got an answer that does not say whether it was applied (${u}): the outcome is unknown`:`${ZA(e)} was refused: ${u}`)+" (the platform message is withheld: it can quote the value).";return o?new Op.SdkError(iae.VERSION_CONFLICT_CODE,`${l} Re-fetch and re-apply the change.`):new Op.ConnectionError(t,n.status,l,{status:n.status,...i?{code:i}:{}})}Xi.variableRefusal=uae;function lae(e,t,n){let r=n instanceof Op.ConnectionError?n.cause:n,i=r instanceof Error?r.name:"Error",o=r?.code,a=typeof o=="string"&&/^[A-Z0-9_]{1,40}$/i.test(o)?o:void 0;return new Op.ConnectionError(t,0,`${ZA(e)} got no answer (${i}${a?` ${a}`:""}): whether it was applied is unknown.`,{status:0,name:i,...a?{code:a}:{}})}Xi.variableTransportFailure=lae;function cae(e){return e instanceof Op.ConnectionError&&e.statusCode===0}Xi.isTransportFailure=cae});var Jc=C(_t=>{"use strict";Object.defineProperty(_t,"__esModule",{value:!0});_t.foldVariableValueComponents=_t.findEnvironmentVariable=_t.resolveEnvironmentVariables=_t.environmentVariableApi=_t.readDeleteDependents=_t.ENVIRONMENT_VARIABLE_VALUE_COMPONENT=_t.ENVIRONMENT_VARIABLE_DEFINITION_COMPONENT=_t.ENVIRONMENT_VARIABLE_TYPE_CODES=void 0;var y0=Ke(),tC=Zo(),No=g0(),ru=XA(),mi=Y(),sr=pe(),dae=ft(),Ar=ae();_t.ENVIRONMENT_VARIABLE_TYPE_CODES={string:1e8,number:100000001,boolean:100000002,json:100000003,dataSource:100000004,secret:100000005};_t.ENVIRONMENT_VARIABLE_DEFINITION_COMPONENT=380;_t.ENVIRONMENT_VARIABLE_VALUE_COMPONENT=381;var oC="environmentvariabledefinition_environmentvariablevalue",nC="envdefinition_envdefinition",fae="environmentvariabledefinitionid,schemaname,displayname,description,type,defaultvalue,isrequired,valueschema,apiid,parameterkey,_parentdefinitionid_value,secretstore,hint,learnmoreurl,inputcontrolconfig",pae="environmentvariablevalueid,value";function mae(e){let t=e.split("/"),n=[[1,"subscriptions"],[3,"resourcegroups"],[5,"providers"],[6,"microsoft.keyvault"],[7,"vaults"],[9,"secrets"]];return(t.length===11||t.length===12)&&t[0]===""&&n.every(([r,i])=>t[r].toLowerCase()===i)&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(t[2])&&[4,8,10,11].every(r=>r>=t.length||t[r]!=="")}var b0="environmentvariabledefinitions",zc="environmentvariablevalues";function Hc(e){return`/${b0}(${e})`}function Kc(e,t){return new mi.ConnectionError(e,200,`the response could not be read as ${t}`)}function hae(e){let t=e[oC];return Array.isArray(t)&&t.every(n=>n!==null&&typeof n=="object")?t:void 0}function gae(e,t){if(e.type!==_t.ENVIRONMENT_VARIABLE_TYPE_CODES.secret)return;let n=`'${String(e.schemaname)}' (${String(e.environmentvariabledefinitionid)})`,r=o=>{throw new mi.SdkError("ENVIRONMENT_VARIABLE_SECRET_UNRECOGNIZED",`Refusing to fetch the Secret environment variable ${n}: ${o}. The SDK never reads a secret: a Secret it manages holds an Azure Key Vault secret reference. Manage this variable in the maker portal.`)};e.secretstore!==void 0&&e.secretstore!==null&&e.secretstore!==0&&r("its secret is stored by Dataverse, not referenced in Azure Key Vault");let i=o=>o==null||typeof o=="string"&&mae(o);i(e.defaultvalue)||r("its default value is not an Azure Key Vault secret reference"),t.some(o=>!i(o.value))&&r("its current value is not an Azure Key Vault secret reference")}function yae(e){let t=e["@odata.etag"];return typeof t=="string"?t:void 0}function t2(e,t){throw new mi.SdkError(sr.UPDATE_NO_ETAG_CODE,`Refusing to push environmentVariable '${e}': ${t?"the concurrency token held for it is not a version of this variable":"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 environmentVariable and re-apply the change.`)}function n2(e,t){return new mi.SdkError("ENVIRONMENT_VARIABLE_VALUE_UNSETTLED",`Refusing to ${t} environmentVariable '${e}': the outcome of its last value write is unknown (or the server returned no version for it), so no request can be conditioned on it. Re-fetch it \u2014 fetchArtifact('environmentVariable', id, { overwrite: true }) when you have local edits \u2014 and re-apply the change.`)}async function rC(e,t){let n;try{n={response:await t()}}catch(r){if(!(0,No.isTransportFailure)(r))throw r;n={transport:r}}return{answer:n,outcome:(0,ru.classifyValueAnswer)(e,n)}}function iC(e,t,n){return"response"in n?(0,No.variableRefusal)(e,t,n.response,"value"):(0,No.variableTransportFailure)(e,t,n.transport)}async function XM(e,t,n){let r;try{r=await n()}catch(i){throw(0,No.isTransportFailure)(i)?(0,No.variableTransportFailure)(e,t,i):i}if(r.status<200||r.status>=300)throw(0,No.variableRefusal)(e,t,r,"definition");return r}async function ZM(e,t,n,r,i){let o=n.value;if(o.op==="none")return{part:r};let a=e.withoutSolution(),s=(0,Ar.normalizeGuid)(o.id,"currentValue.id"),u={operation:`${o.op} value`,id:t,rowId:s,schemaName:n.schemaName},l,c;if(o.op==="create"){let d=(0,sr.echoWrite)("environmentvariablevalueid"),f=`/${zc}${d.query}`;l=a.apiUrl(f),c=await rC("POST",()=>a.post(f,{environmentvariablevalueid:s,value:o.value,"[email protected]":Hc(t)},d.options))}else if(r||t2(t,null),o.op==="update"){let d=(0,sr.echoWrite)("environmentvariablevalueid",{"If-Match":r.token}),f=`/${zc}(${s})${d.query}`;l=a.apiUrl(f),c=await rC("PATCH",()=>a.patch(f,{value:o.value},d.options))}else{let d=`/${zc}(${s})`;l=a.apiUrl(d),c=await rC("DELETE",()=>a.delete(d,{headers:{"If-Match":r.token}}))}switch(c.outcome){case"deleted":return{part:void 0};case"written":return{part:{rowId:s,token:(0,sr.readEtag)(c.answer.response)}};case"unversioned":return{part:{rowId:s,token:ru.UNSETTLED_TOKEN},warning:`Saved; the server returned no version for the value of environment variable '${n.schemaName}', so the next push is refused until it is re-fetched (fetchArtifact).`};case"refused":{let d=iC(u,l,c.answer);if(!i)throw d;return{part:r,warning:`The definition of environment variable '${n.schemaName}' was saved; the value was NOT: ${d.message} The value change is kept locally \u2014 push again (a conflict needs a re-fetch).`,intentPending:!0}}default:{if(!i)throw iC(u,l,c.answer);return{part:{rowId:s,token:ru.UNSETTLED_TOKEN},warning:`The definition of environment variable '${n.schemaName}' was saved; whether the value was is UNKNOWN (${iC(u,l,c.answer).message}). The next push and delete are refused until it is re-fetched: fetchArtifact('environmentVariable', id, { overwrite: true }).`,intentPending:!0}}}}function e2(e,t,n){return{id:e,etag:(0,ru.composeVariableToken)(t,n.part),...n.warning?{warnings:[n.warning]}:{},...n.intentPending?{intentPending:!0}:{}}}async function r2(e,t,n){var r;if(n!==void 0)try{let i=`/RetrieveDependenciesForDelete(ObjectId=@p1,ComponentType=@p2)?@p1=${(0,Ar.normalizeGuid)(t,"id")}&@p2=${n}`,a=(r=(0,sr.ensureSuccess)(await e.get(i),e.apiUrl(i)).body)===null||r===void 0?void 0:r.value;return Array.isArray(a)?a.map(s=>{var u;let l=Number(s.dependentcomponenttype);return{table:l===29?"workflow":l===380?"environmentvariabledefinition":"solutioncomponent",id:String((u=s.dependentcomponentobjectid)!==null&&u!==void 0?u:"").toLowerCase(),...Number.isInteger(l)?{componentType:l}:{}}}):void 0}catch{return}}_t.readDeleteDependents=r2;async function bae(e,t,n){var r,i,o,a,s;let u=(0,Ar.normalizeGuid)(t,"id"),l=n?.snapshot,c=!((r=l?.currentValue)===null||r===void 0)&&r.id?(0,Ar.normalizeGuid)(l.currentValue.id,"currentValue.id"):null,d=(0,ru.parseVariableToken)((i=n?.token)!==null&&i!==void 0?i:null,c);if(d.kind==="unsettled")throw n2(u,"delete");if(d.kind==="none"||!l)throw new mi.SdkError(sr.DELETE_NO_ETAG_CODE,`Refusing to delete environmentVariable '${u}': no usable concurrency token is held for it, so the delete could not be made conditional and could remove what another writer changed. Fetch it first (fetchArtifact).`);if(!e.supportsAtomicBatch)throw new mi.SdkError("ENVIRONMENT_VARIABLE_DELETE_NOT_ATOMIC",`Refusing to delete environmentVariable '${u}': the injected HttpClient does not implement postRaw(), and the definition and its value can only be deleted together, guarded, in one change set. Nothing was sent.`);if(l.type==="secret"&&d.value===void 0)throw new mi.SdkError("ENVIRONMENT_VARIABLE_DELETE_UNGUARDED",`Refusing to delete the Secret environment variable '${u}': it holds no value, and for a Secret the SDK cannot build the guard that proves no value was created since it was read (the platform refuses an empty Secret value row), so the delete could remove a value it never saw. This is a limit of the SDK, not of the variable: delete it in the maker portal. Nothing was sent.`);let f=`${Hc(u)}${(0,Ar.odataQuery)([["$select","environmentvariabledefinitionid"],["$expand",`${oC}($select=environmentvariablevalueid),${nC}($select=environmentvariabledefinitionid,schemaname)`]])}`,p=e.apiUrl(f),m=await e.get(f);if(m.status===404)throw new mi.VersionConflictError("environmentVariable",u,(o=n?.token)!==null&&o!==void 0?o:null,null,"The variable no longer exists on the server (another writer deleted it).");(0,sr.ensureSuccess)(m,p);let h=(a=m.body)===null||a===void 0?void 0:a[nC];if(!Array.isArray(h))throw Kc(p,"the variable's child definitions, so whether the delete would cascade is unknown");if(h.length===0&&(0,y0.pageEnd)(m.body,nC).kind!=="end")throw Kc(p,"the variable's child definitions \u2014 the answer carries none but does not say it is the end \u2014 so whether the delete would cascade is unknown");if(h.length>0){let S=h.map(R=>{var x;return{table:"environmentvariabledefinition",id:String((x=R.environmentvariabledefinitionid)!==null&&x!==void 0?x:"").toLowerCase(),componentType:_t.ENVIRONMENT_VARIABLE_DEFINITION_COMPONENT}});throw new mi.ArtifactInUseError("environmentVariable",u,`Refusing to delete environmentVariable '${u}': ${S.length} data-source variable(s) depend on it, and the platform would delete them \u2014 with their values \u2014 together with it, without saying so. Delete or re-parent them first. Nothing was deleted.`,S)}let g=e.withoutSolution(),y={method:"DELETE",path:Hc(u),etag:d.definition},b=d.value?[{method:"DELETE",path:`/${zc}(${d.value.rowId})`,etag:d.value.token},y]:[{method:"POST",path:`/${zc}`,body:{environmentvariablevalueid:(0,dae.newId)(),"[email protected]":Hc(u)}},y],{body:E,batchId:w,contentIds:_}=(0,tC.renderChangeSet)(g,b),I=g.apiUrl("/$batch"),T={operation:"delete",id:u,schemaName:l.schemaName},O;try{O=await g.postBatch(E,w)}catch(S){throw(0,No.isTransportFailure)(S)?(0,No.variableTransportFailure)(T,I,S):S}let v=(0,tC.parseChangeSetParts)(O.body,_),N=v?.find(S=>S.status<200||S.status>=300);if(N){let S=(0,tC.partResponse)(N),R=(0,No.platformErrorCode)(S.body);throw S.status===412||S.status===404&&R==="0x80040217"||S.status===400&&R==="0x80072013"?new mi.VersionConflictError("environmentVariable",u,(s=n?.token)!==null&&s!==void 0?s:null,null,"Another writer changed, created or deleted its definition or value since it was fetched; nothing was deleted."):R==="0x8004f01f"?new mi.ArtifactInUseError("environmentVariable",u,`Refusing to delete environmentVariable '${u}': another component (a flow, an app) depends on it; nothing was deleted. Remove the dependency first.`,await r2(e,u,_t.ENVIRONMENT_VARIABLE_DEFINITION_COMPONENT)):(0,No.variableRefusal)(T,I,S,"definition")}if(O.status<200||O.status>=300)throw(0,No.variableRefusal)(T,I,O,"definition");if(!v||v.length!==b.length)throw new mi.ConnectionError(I,O.status,`the delete of environmentVariable '${u}' cannot be confirmed: its change-set response ${v?`reported ${v.length} result(s) for ${b.length} operation(s)`:"could not be parsed"}, so whether it was deleted is unknown. Re-fetch it to see.`)}_t.environmentVariableApi={async get(e,t){let n=(0,Ar.normalizeGuid)(t,"id"),r=`${Hc(n)}${(0,Ar.odataQuery)([["$select",fae],["$expand",`${oC}($select=${pae})`]])}`,i=e.apiUrl(r),o=(0,sr.ensureSuccess)(await e.get(r),i),a=o.body,s=a?hae(a):void 0;if(!a||!s||s.length>1)throw Kc(i,"an environment variable with at most one value");if(!Object.values(_t.ENVIRONMENT_VARIABLE_TYPE_CODES).includes(a.type))throw new mi.SdkError("ENVIRONMENT_VARIABLE_TYPE_UNRECOGNIZED",`Environment variable '${n}' has a type the SDK does not know (${JSON.stringify(a.type)}).`);gae(a,s);let u=(0,sr.readEtag)(o),l=s[0],c;if(!l)c=(0,ru.composeVariableToken)(u);else{let d=yae(l);c=d===void 0?null:(0,ru.composeVariableToken)(u,{rowId:(0,Ar.normalizeGuid)(String(l.environmentvariablevalueid),"environmentvariablevalueid"),token:d})}return{raw:a,etag:c}},async list(e){let t=`/${b0}${(0,Ar.odataQuery)([["$select","environmentvariabledefinitionid,schemaname,displayname"]])}`;return(await(0,y0.collectPages)(e,t,"listArtifacts('environmentVariable')")).map(r=>{var i,o,a;return{type:"environmentVariable",id:String((i=r.environmentvariabledefinitionid)!==null&&i!==void 0?i:""),name:String((a=(o=r.displayname)!==null&&o!==void 0?o:r.schemaname)!==null&&a!==void 0?a:""),isDirty:!1}})},async create(e,t,n){let r=t,i=(0,sr.echoWrite)("environmentvariabledefinitionid"),o=`/${b0}${i.query}`,a=e.apiUrl(o),s={operation:"create definition",id:n??"(new)",schemaName:r.schemaName},u=await XM(s,a,()=>{var d;return e.post(o,(0,sr.withClientMintedId)((d=r.definition)!==null&&d!==void 0?d:{},"environmentvariabledefinitionid",n),i.options)}),l=(0,sr.resolveCreatedId)(u,"environmentvariabledefinitionid","environment variable",n),c=await ZM(e,l,r,void 0,!0);return e2(l,(0,sr.readEtag)(u),c)},async update(e,t,n,r){let i=n,o=(0,Ar.normalizeGuid)(t,"id"),a=(0,ru.parseVariableToken)(r,i.heldRowId);if(a.kind==="unsettled")throw n2(o,"push");a.kind==="none"&&t2(o,r);let s=a.definition,u=!1;if(i.definition){let c=(0,sr.echoWrite)("environmentvariabledefinitionid",{"If-Match":a.definition}),d=`${Hc(o)}${c.query}`,f=await XM({operation:"update definition",id:o,schemaName:i.schemaName},e.apiUrl(d),()=>e.patch(d,i.definition,c.options));s=(0,sr.readEtag)(f),u=!0}let l=await ZM(e,o,i,a.value,u);return e2(o,s,l)},delete(e,t,n){return bae(e,t,n)}};async function i2(e,t,n){let r=`/${b0}${(0,Ar.odataQuery)([["$select","environmentvariabledefinitionid,schemaname"],["$filter",`schemaname eq '${(0,Ar.odataLiteral)(t)}'`],...n!==void 0?[["$top",String(n)]]:[]])}`,i=e.apiUrl(r),o;if(n===void 0)o=await(0,y0.collectPages)(e,r,"resolveArtifact('environmentVariable')");else{let a=(0,sr.ensureSuccess)(await e.get(r),i).body;if(o=a?.value,Array.isArray(o)&&!(0,y0.boundedPageComplete)(a,o.length,n))throw Kc(i,"a complete list of environment variables (the answer says more rows exist)")}if(!Array.isArray(o))throw Kc(i,"a list of environment variables");return o.map(a=>({id:String(a.environmentvariabledefinitionid),name:String(a.schemaname)}))}_t.resolveEnvironmentVariables=i2;async function vae(e,t){let n=await i2(e,t,2);if(n.length>1)throw new mi.AmbiguousArtifactError("environmentVariable",t,n.length);return n.length===1?n[0].id:null}_t.findEnvironmentVariable=vae;async function wae(e,t){var n;let r=[],i=new Set,o=[];for(let u of t){if(u.componentType===_t.ENVIRONMENT_VARIABLE_DEFINITION_COMPONENT){try{i.add((0,Ar.normalizeGuid)(u.objectId,"objectid"))}catch(l){r.push({component:u,error:l})}continue}if(u.componentType!==_t.ENVIRONMENT_VARIABLE_VALUE_COMPONENT){o.push(u);continue}try{let l=`/${zc}(${(0,Ar.normalizeGuid)(u.objectId,"objectid")})${(0,Ar.odataQuery)([["$select","_environmentvariabledefinitionid_value"]])}`,d=(n=(0,sr.ensureSuccess)(await e.get(l),e.apiUrl(l)).body)===null||n===void 0?void 0:n._environmentvariabledefinitionid_value;if(typeof d!="string")throw Kc(e.apiUrl(l),"the value's definition");i.add((0,Ar.normalizeGuid)(d,"_environmentvariabledefinitionid_value"))}catch(l){r.push({component:u,error:l})}}let a=[...i].map(u=>({objectId:u,componentType:_t.ENVIRONMENT_VARIABLE_DEFINITION_COMPONENT})),s=u=>u.objectId.toLowerCase().replace(/^\{|\}$/g,"");return{components:[...o,...a].sort((u,l)=>u.componentType-l.componentType||(s(u)<s(l)?-1:s(u)>s(l)?1:0)),failed:r}}_t.foldVariableValueComponents=wae});var v0=C(wn=>{"use strict";Object.defineProperty(wn,"__esModule",{value:!0});wn.parseCustomApiToken=wn.composeCustomApiToken=wn.canonicalGuid=wn.EXPANSION_CAP=wn.optionName=wn.CUSTOM_API_TYPE_CODES=wn.CUSTOM_API_STEP_CODES=wn.CUSTOM_API_BINDING_CODES=void 0;var o2=pe();wn.CUSTOM_API_BINDING_CODES={global:0,entity:1,entityCollection:2};wn.CUSTOM_API_STEP_CODES={none:0,asyncOnly:1,syncAndAsync:2};wn.CUSTOM_API_TYPE_CODES={boolean:0,dateTime:1,decimal:2,entity:3,entityCollection:4,entityReference:5,float:6,integer:7,money:8,picklist:9,string:10,stringArray:11,guid:12};function Eae(e,t){return Object.keys(e).find(n=>e[n]===t)}wn.optionName=Eae;wn.EXPANSION_CAP=5e3;var Aae=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,Cae=e=>String(e??"").toLowerCase().replace(/^\{|\}$/g,"");wn.canonicalGuid=Cae;function Sae(e,t){let n=(r,i)=>i.map(([o,a])=>[(0,wn.canonicalGuid)(o),a]).sort(([o],[a])=>o<a?-1:o>a?1:0).map(([o,a])=>` ${r}${o}=${a}`);return[e,...n("p",t.requestParameters),...n("r",t.responseProperties)].join("")}wn.composeCustomApiToken=Sae;function Nae(e,t){if(typeof e!="string")return;let[n,...r]=e.split(" ");if(!(0,o2.isVersionToken)(n))return;let i={api:n,requestParameters:new Map,responseProperties:new Map};for(let a of r){let s=/^([pr])([0-9a-f-]{36})=(\S+)$/.exec(a);if(!s||!Aae.test(s[2])||!(0,o2.isVersionToken)(s[3]))return;let u=s[1]==="p"?i.requestParameters:i.responseProperties;if(u.has(s[2]))return;u.set(s[2],s[3])}let o=(a,s)=>{let u=new Set(s.map(wn.canonicalGuid));return u.size===s.length&&u.size===a.size&&[...u].every(l=>a.has(l))};return o(i.requestParameters,t.requestParameters)&&o(i.responseProperties,t.responseProperties)?i:void 0}wn.parseCustomApiToken=Nae});var C0=C(ut=>{"use strict";Object.defineProperty(ut,"__esModule",{value:!0});ut.foldCustomApiChildComponents=ut.findCustomApi=ut.resolveCustomApis=ut.customApiApi=ut.SYSTEM_ADMINISTRATOR_ROLE_TEMPLATE=ut.CUSTOM_API_OPTION_UNRECOGNIZED_CODE=ut.CUSTOM_API_DELETE_UNVERIFIABLE_CODE=ut.CUSTOM_API_LABELS_UNSUPPORTED_CODE=ut.CUSTOM_API_NOT_ATOMIC_CODE=void 0;var ss=Ke(),ml=Zo(),_ae=Jc(),p2=g0(),rt=v0(),m2=il(),Zt=Y(),en=pe(),Kn=ae();ut.CUSTOM_API_NOT_ATOMIC_CODE="CUSTOM_API_NOT_ATOMIC";ut.CUSTOM_API_LABELS_UNSUPPORTED_CODE="CUSTOM_API_LABELS_UNSUPPORTED";ut.CUSTOM_API_DELETE_UNVERIFIABLE_CODE="CUSTOM_API_DELETE_UNVERIFIABLE";ut.CUSTOM_API_OPTION_UNRECOGNIZED_CODE="CUSTOM_API_OPTION_UNRECOGNIZED";ut.SYSTEM_ADMINISTRATOR_ROLE_TEMPLATE="627090ff-40a3-4053-8790-584edc5be201";var Dp={headers:{"If-None-Match":"null"}},E0="customapis",Iae="customapiid,uniquename,name,displayname,description,bindingtype,boundentitylogicalname,isfunction,isprivate,allowedcustomprocessingsteptype,workflowsdkstepenabled,executeprivilegename,_plugintypeid_value",a2="uniquename,name,displayname,description,type,logicalentityname",da=[{kind:"requestParameter",nav:"CustomAPIRequestParameters",set:"customapirequestparameters",pk:"customapirequestparameterid",select:`customapirequestparameterid,${a2},isoptional`},{kind:"responseProperty",nav:"CustomAPIResponseProperties",set:"customapiresponseproperties",pk:"customapiresponsepropertyid",select:`customapiresponsepropertyid,${a2}`}],w0=e=>da.find(t=>t.kind===e),sC=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,hl=e=>`/${E0}(${e})`;function Yc(e,t){return new Zt.ConnectionError(e,200,`incomplete read: ${t} \u2014 never read as "no rows". Retry.`)}function aC(e){return da.map(t=>`${t.nav}($select=${e(t)})`).join(",")}async function h2(e,t,n,r,i){let o=t[n.nav],a=t[`${n.nav}@odata.nextLink`],s=(0,ss.moreRecordsClaim)(t,n.nav);if(!Array.isArray(o)||a!==void 0&&(typeof a!="string"||a==="")||s==="malformed")throw Yc(i,`the API's ${n.nav}`);let u=o;(o.length>=rt.EXPANSION_CAP||s==="more"||a!==void 0)&&(u=await(0,ss.collectPages)(e,`/${n.set}${(0,Kn.odataQuery)([["$select",n.select],["$filter",`_customapiid_value eq ${r}`]])}`,`fetchArtifact('customApi') ${n.nav}`,void 0,Dp));let l=new Set;for(let c of u){let d=c?.[n.pk],f=c?.["@odata.etag"];if(c===null||typeof c!="object"||typeof d!="string"||!sC.test((0,rt.canonicalGuid)(d))||!(0,en.isVersionToken)(f)||l.has((0,rt.canonicalGuid)(d)))throw Yc(i,`a row of the API's ${n.nav} without its id or version, or listed twice`);l.add((0,rt.canonicalGuid)(d))}return u}function Tae(e,t){let n=(r,i,o)=>{if((0,rt.optionName)(i,o)===void 0)throw new Zt.SdkError(ut.CUSTOM_API_OPTION_UNRECOGNIZED_CODE,`Custom API '${t}' has a ${r} the SDK does not know (${JSON.stringify(o)}); refusing to guess it.`)};n("bindingtype",rt.CUSTOM_API_BINDING_CODES,e.bindingtype),n("allowedcustomprocessingsteptype",rt.CUSTOM_API_STEP_CODES,e.allowedcustomprocessingsteptype);for(let r of da)for(let i of e[r.nav])n(`${r.nav} type`,rt.CUSTOM_API_TYPE_CODES,i.type)}function s2(e,t){if(!(0,en.isVersionToken)(e))return null;let n=r=>t[r.nav].map(i=>[(0,rt.canonicalGuid)(String(i[r.pk])),String(i["@odata.etag"])]);return(0,rt.composeCustomApiToken)(e,{requestParameters:n(da[0]),responseProperties:n(da[1])})}function Oae(e,t){throw new Zt.SdkError(en.UPDATE_NO_ETAG_CODE,`Refusing to push customApi '${e}': ${t?"the concurrency token held for it does not name exactly the rows last synced":"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 customApi and re-apply the change.`)}async function Dae(e,t,n){var r;let i="/RetrieveProvisionedLanguages()",o,a="its provisioned languages could not be read";try{let u=await e.get(i);u.status>=200&&u.status<300&&(o=(r=u.body)===null||r===void 0?void 0:r.RetrieveProvisionedLanguages)}catch{o=void 0}let s=Array.isArray(o)&&o.every(u=>typeof u=="number"&&Number.isInteger(u)&&u>0);if(!(s&&o.length===1))throw s&&(a=`it provisions ${o.length} languages`),new Zt.SdkError(ut.CUSTOM_API_LABELS_UNSUPPORTED_CODE,`Refusing to push customApi '${t}': it changes the localized label(s) ${n.join(", ")}, and ${a} \u2014 which language a write addresses there is not established, so the SDK does not write it. Edit labels in the maker portal; every other change can be pushed without them. Nothing was sent.`)}function Pae(e,t,n){let r={Prefer:"return=representation"},i=[],o=(a,s)=>(a==="requestParameter"?n.requestParameters:n.responseProperties).get(s);for(let a of t.deletes){let s=w0(a.kind);i.push({target:a.kind,id:a.id,op:{method:"DELETE",path:`/${s.set}(${a.id})`,etag:o(a.kind,a.id)}})}t.api&&i.push({target:"api",id:e,op:{method:"PATCH",path:`${hl(e)}?$select=customapiid`,body:t.api,etag:n.api,headers:r}});for(let a of t.posts){let s=w0(a.kind);i.push({target:a.kind,id:a.id,op:{method:"POST",path:`/${s.set}?$select=${s.pk}`,body:{...a.body,"[email protected]":hl(e)},headers:r}})}for(let a of t.patches){let s=w0(a.kind);i.push({target:a.kind,id:a.id,op:{method:"PATCH",path:`/${s.set}(${a.id})?$select=${s.pk}`,body:a.body,etag:o(a.kind,a.id),headers:r}})}return i}function u2(e,t,n){let r=(0,p2.platformErrorCode)(t.body);if(t.status===412||t.status===404&&r==="0x80040217"&&e.target!=="api"||t.status===400&&r==="0x80040216"||t.status===400&&r==="0x80072013"&&e.op.method==="POST")return new Zt.SdkError(en.VERSION_CONFLICT_CODE,`${e.op.method} of ${e.target} '${e.id}' was refused (${t.status}${r?` ${r}`:""}): another writer changed, added or deleted it since the fetch. Nothing was written.`);try{(0,en.ensureSuccess)(t,n)}catch(o){return o}return new Zt.ConnectionError(n,t.status,"unexpected refusal")}async function Rae(e,t){var n;if(t.length===1){let[c]=t,{op:d}=c,f={...(n=d.headers)!==null&&n!==void 0?n:{},...d.etag?{"If-Match":d.etag}:{}},p=d.method==="DELETE"?await e.delete(d.path,{headers:f}):d.method==="PATCH"?await e.patch(d.path,d.body,{headers:f}):await e.post(d.path,d.body,{headers:f});if(p.status<200||p.status>=300)throw u2(c,p,e.apiUrl(d.path));return[p]}let{body:r,batchId:i,contentIds:o}=(0,ml.renderChangeSet)(e,t.map(c=>c.op)),a=e.apiUrl("/$batch"),s=await e.postBatch(r,i),u=(0,ml.parseChangeSetParts)(s.body,o),l=u?.find(c=>c.status<200||c.status>=300);if(l){let c=t[o.indexOf(l.contentId)];throw u2(c,(0,ml.partResponse)(l),e.apiUrl(c.op.path))}if((0,en.ensureSuccess)(s,a),!u||u.length!==t.length)throw new Zt.ConnectionError(a,s.status,`the change set's answer ${u?`reported ${u.length} result(s) for ${t.length} operation(s)`:"could not be parsed"}, so whether it was applied is unknown. Nothing is re-sent; re-fetch to see.`);return o.map(c=>(0,ml.partResponse)(u.find(d=>d.contentId===c)))}function kae(e,t){var n;let r=e.target==="api"?"customapiid":w0(e.target).pk,i=(n=t.body)===null||n===void 0?void 0:n[r],o=(0,en.readEtag)(t);return typeof i=="string"&&(0,rt.canonicalGuid)(i)===(0,rt.canonicalGuid)(e.id)&&(0,en.isVersionToken)(o)?o:void 0}async function $ae(e,t,n){var r,i,o,a;let s=(0,Kn.normalizeGuid)(t,"id"),u=n?.snapshot,l=u?(0,rt.parseCustomApiToken)((r=n?.token)!==null&&r!==void 0?r:null,{requestParameters:((i=u.requestParameters)!==null&&i!==void 0?i:[]).map(b=>(0,rt.canonicalGuid)(String(b.id))),responseProperties:((o=u.responseProperties)!==null&&o!==void 0?o:[]).map(b=>(0,rt.canonicalGuid)(String(b.id)))}):void 0;if(!l)throw new Zt.SdkError(en.DELETE_NO_ETAG_CODE,`Refusing to delete customApi '${s}': no usable concurrency token is held for it, so the delete could not be made conditional and could remove what another writer changed. Fetch it first (fetchArtifact).`);if(l.requestParameters.size+l.responseProperties.size>0&&!e.supportsAtomicBatch)throw new Zt.SdkError(ut.CUSTOM_API_NOT_ATOMIC_CODE,`Refusing to delete customApi '${s}': the injected HttpClient does not implement postRaw(), and the API's parameters and properties can only be deleted with it, each guarded, in one change set. Nothing was sent.`);await Lae(e,s);let d=await Uae(e,s),f=[],p=await qae(e,s,l,d.apiReferences,f);if(await Bae(e,s,p,d.messageReferences,f),f.length>0)throw new Zt.ArtifactInUseError("customApi",s,`Refusing to delete customApi '${s}': ${f.length} row(s) of other tables reference it or its message (${[...new Set(f.map(b=>b.table))].join(", ")}), and the platform would delete, unlink or refuse with them. Nothing was deleted. Remove those references first.`,f);let m=[...[...l.requestParameters].map(([b,E])=>({method:"DELETE",path:`/customapirequestparameters(${b})`,etag:E})),...[...l.responseProperties].map(([b,E])=>({method:"DELETE",path:`/customapiresponseproperties(${b})`,etag:E})),{method:"DELETE",path:hl(s),etag:l.api}],h,g=e.apiUrl(hl(s));if(m.length===1){let b=await e.delete(hl(s),{headers:{"If-Match":l.api}});h=b.status<200||b.status>=300?b:void 0}else{let{body:b,batchId:E,contentIds:w}=(0,ml.renderChangeSet)(e,m);g=e.apiUrl("/$batch");let _=await e.postBatch(b,E),I=(0,ml.parseChangeSetParts)(_.body,w),T=I?.find(O=>O.status<200||O.status>=300);if(h=T?(0,ml.partResponse)(T):void 0,!h&&((0,en.ensureSuccess)(_,g),!I||I.length!==m.length))throw new Zt.ConnectionError(g,_.status,`the delete of customApi '${s}' cannot be confirmed: its change-set answer ${I?`reported ${I.length} result(s) for ${m.length} operation(s)`:"could not be parsed"}, so whether it was deleted is unknown. Re-fetch it to see.`)}if(!h)return;let y=(0,p2.platformErrorCode)(h.body);if(h.status===412||h.status===404&&y==="0x80040217")throw new Zt.VersionConflictError("customApi",s,(a=n?.token)!==null&&a!==void 0?a:null,null,"Another writer changed or deleted the API or one of its rows since it was fetched; nothing was deleted.");if(y==="0x8004f01f"||y==="0x80040227"){let b;try{b=await(0,_ae.readDeleteDependents)(e,s,(await(0,m2.resolveCustomApiComponentTypes)(e)).api)}catch{b=void 0}throw new Zt.ArtifactInUseError("customApi",s,`Refusing to delete customApi '${s}': the platform refused it (${y}) because another component depends on it or on its message; nothing was deleted. Remove the dependency first.`,b)}(0,en.ensureSuccess)(h,g)}function hi(e,t,n){let r=new Zt.SdkError(ut.CUSTOM_API_DELETE_UNVERIFIABLE_CODE,`Refusing to delete customApi '${e}': the SDK cannot establish that the delete is safe \u2014 ${t}. Nothing was deleted; delete it in the maker portal, or retry.`);return n===void 0?r:(0,Zt.attachCause)(r,n)}var l2=new WeakMap;async function Lae(e,t){var n,r;let i=l2.get(e);try{if(!i){let l=(n=(0,en.ensureSuccess)(await e.get("/WhoAmI()"),e.apiUrl("/WhoAmI()")).body)===null||n===void 0?void 0:n.UserId;if(typeof l!="string"||!sC.test((0,rt.canonicalGuid)(l)))throw hi(t,"the caller could not be identified (WhoAmI answered without a user id)");i=(0,rt.canonicalGuid)(l),l2.set(e,i)}let o=`/systemusers(${i})${(0,Kn.odataQuery)([["$select","systemuserid"],["$expand","systemuserroles_association($select=_roletemplateid_value)"]])}`,a=(r=(0,en.ensureSuccess)(await e.get(o,Dp),e.apiUrl(o)).body)===null||r===void 0?void 0:r.systemuserroles_association;if(!Array.isArray(a)||a.some(u=>u===null||typeof u!="object"||Array.isArray(u)))throw hi(t,"the caller's roles could not be read");if(!a.some(u=>{let l=u._roletemplateid_value;return typeof l=="string"&&(0,rt.canonicalGuid)(l)===ut.SYSTEM_ADMINISTRATOR_ROLE_TEMPLATE}))throw new Zt.SdkError(ut.CUSTOM_API_DELETE_UNVERIFIABLE_CODE,`Refusing to delete customApi '${t}': the SDK cannot establish that it sees every row the delete would affect (the API's parameters and properties, rows of other tables that reference it, registrations on its message). It can only when the caller directly holds the System Administrator role, and this caller does not. This is a limit of the SDK, not a statement that you may not delete it: delete it in the maker portal. Nothing was deleted.`)}catch(o){throw o instanceof Zt.SdkError&&o.code===ut.CUSTOM_API_DELETE_UNVERIFIABLE_CODE?o:hi(t,"the caller's identity or roles could not be read",o)}}var Mae=new Set(["syncerror","asyncoperation","mailboxtrackingfolder","userentityinstancedata","processsession","bulkdeletefailure","principalobjectattributeaccess"]),xae=new Set(["customapirequestparameter","customapiresponseproperty"]),Fae=new Set(["sdkmessagefilter","sdkmessagepair","customapi"]);function c2(e,t,n){let r=e;if(!r||typeof r!="object"||!Array.isArray(r.value))throw hi(t,`${n} could not be read`);if(Object.prototype.hasOwnProperty.call(r,"@odata.nextLink")||(0,ss.moreRecordsClaim)(r)!=="none")throw hi(t,`${n} were answered incompletely (the answer says more rows exist)`);return r.value}var d2=new WeakMap;async function Uae(e,t){let n=d2.get(e);if(n)return n;try{let r=async(c,d)=>{let f=`/EntityDefinitions(LogicalName='${c}')/OneToManyRelationships${(0,Kn.odataQuery)([["$select","ReferencingEntity,ReferencingAttribute,ReferencedEntityNavigationPropertyName"]])}`;return c2((0,en.ensureSuccess)(await e.get(f),e.apiUrl(f)).body,t,`the relationships of '${c}'`).map(m=>{let h=m,g=h?.ReferencedEntityNavigationPropertyName,y=h?.ReferencingEntity;if(typeof g!="string"||typeof y!="string"||g===""||y==="")throw hi(t,`a relationship of '${c}' could not be read`);return{nav:g,table:y}}).filter(m=>!Mae.has(m.table)&&!d.has(m.table))},i=await r("customapi",xae),o=await r("sdkmessage",Fae),a=[...new Set([...i,...o].map(c=>c.table))],s=new Map;if(a.length>0){let c=`/EntityDefinitions${(0,Kn.odataQuery)([["$select","LogicalName,PrimaryIdAttribute"],["$filter",a.map(f=>`LogicalName eq '${(0,Kn.odataLiteral)(f)}'`).join(" or ")]])}`,d=c2((0,en.ensureSuccess)(await e.get(c),e.apiUrl(c)).body,t,"the referencing tables");for(let f of d){let p=f;typeof p?.LogicalName=="string"&&typeof p.PrimaryIdAttribute=="string"&&p.PrimaryIdAttribute&&s.set(p.LogicalName,p.PrimaryIdAttribute)}}let u=c=>c.map(d=>{let f=s.get(d.table);if(!f)throw hi(t,`the primary id of '${d.table}' could not be read`);return{...d,pk:f}}),l={apiReferences:u(i),messageReferences:u(o)};return d2.set(e,l),l}catch(r){throw r instanceof Zt.SdkError&&r.code===ut.CUSTOM_API_DELETE_UNVERIFIABLE_CODE?r:hi(t,"the relationships to inspect could not be read",r)}}var A0=15;function g2(e,t,n){let r=[e.slice(0,t)];for(let i=t;i<e.length;i+=n)r.push(e.slice(i,i+n));return r}var y2=e=>`${e.nav}($select=${e.pk};$top=1)`;function b2(e,t,n,r){for(let i of t){let o=e[i.nav];if(!Array.isArray(o))throw r(`the read did not answer '${i.nav}'`);if(o.length===0&&(0,ss.pageEnd)(e,i.nav).kind!=="end")throw r(`the read of '${i.nav}' carries no row but does not say it is the end`);for(let a of o){let s=a?.[i.pk];n.push({table:i.table,id:typeof s=="string"?(0,rt.canonicalGuid)(s):""})}}}async function qae(e,t,n,r,i){var o;let a=g2(r,A0-da.length,A0),s="";for(let u=0;u<a.length;u+=1){let l=u===0,c=[...l?[aC(h=>h.pk)]:[],...a[u].map(y2)].join(","),d=`${hl(t)}${(0,Kn.odataQuery)([["$select",l?"customapiid,_sdkmessageid_value":"customapiid"],...c?[["$expand",c]]:[]])}`,f=e.apiUrl(d),p=await e.get(d,Dp);if(p.status===404)throw new Zt.VersionConflictError("customApi",t,null,null,"The API no longer exists on the server (another writer deleted it); nothing was deleted.");if(p.status<200||p.status>=300)throw hi(t,`a safety read answered ${p.status}`,p.body);let m=(o=p.body)!==null&&o!==void 0?o:{};if(l){let h=m._sdkmessageid_value;if(typeof h!="string"||!sC.test((0,rt.canonicalGuid)(h)))throw hi(t,"the API's message could not be read");s=(0,rt.canonicalGuid)(h);for(let g of da){let y;try{y=await h2(e,m,g,t,f)}catch(w){throw hi(t,`the API's ${g.nav} could not be read completely`,w)}let b=new Set(y.map(w=>(0,rt.canonicalGuid)(String(w[g.pk])))),E=g.kind==="requestParameter"?n.requestParameters:n.responseProperties;if(b.size!==E.size||[...E.keys()].some(w=>!b.has(w)))throw new Zt.VersionConflictError("customApi",t,null,null,`The API has ${g.nav} other than the ones last fetched (another writer added or removed one); the platform would delete them with it. Nothing was deleted; re-fetch it first.`)}}b2(m,a[u],i,h=>hi(t,h))}return s}async function Bae(e,t,n,r,i){var o;for(let a of r.length===0?[]:g2(r,A0,A0)){let s=`/sdkmessages(${n})${(0,Kn.odataQuery)([["$select","sdkmessageid"],["$expand",a.map(y2).join(",")]])}`,u=await e.get(s,Dp);if(u.status<200||u.status>=300)throw hi(t,`the read of the API's message answered ${u.status}`,u.body);b2((o=u.body)!==null&&o!==void 0?o:{},a,i,l=>hi(t,l))}}ut.customApiApi={async get(e,t){let n=(0,Kn.normalizeGuid)(t,"id"),r=`${hl(n)}${(0,Kn.odataQuery)([["$select",Iae],["$expand",aC(u=>u.select)]])}`,i=e.apiUrl(r),o=(0,en.ensureSuccess)(await e.get(r,Dp),i),a=o.body;if(!a||typeof a!="object"||Array.isArray(a))throw Yc(i,"the custom API row");let s={...a};for(let u of da)s[u.nav]=await h2(e,a,u,n,i);return Tae(s,n),{raw:s,etag:s2((0,en.readEtag)(o),s)}},async list(e){let t=`/${E0}${(0,Kn.odataQuery)([["$select","customapiid,uniquename,displayname,boundentitylogicalname"]])}`;return(await(0,ss.collectPages)(e,t,"listArtifacts('customApi')")).map(r=>{var i;return{type:"customApi",id:String((i=r.customapiid)!==null&&i!==void 0?i:""),name:String(r.displayname||r.uniquename||""),...typeof r.boundentitylogicalname=="string"&&r.boundentitylogicalname?{entityLogicalName:r.boundentitylogicalname}:{},isDirty:!1}})},async create(e,t,n){let r=t,i=`/${E0}${(0,Kn.odataQuery)([["$select","customapiid"],["$expand",aC(c=>c.pk)]])}`,o=e.apiUrl(i),a=(0,en.ensureSuccess)(await e.post(i,r.create,{headers:{Prefer:"return=representation"}}),o),s=(0,en.resolveCreatedId)(a,"customapiid","custom API",n),u=a.body,l=null;if(u&&typeof u=="object"){let c=f=>{var p,m;return new Set(((m=(p=r.create)===null||p===void 0?void 0:p[f.nav])!==null&&m!==void 0?m:[]).map(h=>(0,rt.canonicalGuid)(String(h[f.pk]))))};l=da.every(f=>{let p=u[f.nav],m=u[`${f.nav}@odata.nextLink`];if(!Array.isArray(p)||p.length>=rt.EXPANSION_CAP||(0,ss.moreRecordsClaim)(u,f.nav)!=="none"||m!==void 0)return!1;let h=p.map(y=>y?.[f.pk]),g=c(f);return p.every(y=>(0,en.isVersionToken)(y?.["@odata.etag"]))&&h.length===g.size&&h.every(y=>typeof y=="string"&&g.has((0,rt.canonicalGuid)(y)))&&new Set(h.map(rt.canonicalGuid)).size===h.length})?s2((0,en.readEtag)(a),u):null}return{id:s,etag:l,warnings:[...r.warnings,...l===null?[`customApi '${s}' was created, but the server's answer did not carry every row's version \u2014 fetch it before the next push.`]:[]]}},async update(e,t,n,r){let i=n,o=(0,Kn.normalizeGuid)(t,"id"),a=(0,rt.parseCustomApiToken)(r,i.held);a||Oae(o,r);let s=Pae(o,i,a);if(s.length>1&&!e.supportsAtomicBatch)throw new Zt.SdkError(ut.CUSTOM_API_NOT_ATOMIC_CODE,`Refusing to push customApi '${o}': it writes ${s.length} rows, which must commit together in one change set, and the injected HttpClient does not implement postRaw(). Nothing was sent.`);i.labelEdits.length>0&&await Dae(e,o,i.labelEdits);let u=await Rae(e,s),l={api:a.api,requestParameter:new Map(a.requestParameters),responseProperty:new Map(a.responseProperties)},c=!1;s.forEach((f,p)=>{if(f.op.method==="DELETE"){l[f.target].delete(f.id);return}let m=kae(f,u[p]);if(m===void 0){c=!0;return}f.target==="api"?l.api=m:l[f.target].set(f.id,m)});let d=c?null:(0,rt.composeCustomApiToken)(l.api,{requestParameters:[...l.requestParameter],responseProperties:[...l.responseProperty]});return{id:o,etag:d,warnings:[...i.warnings,...c?[`customApi '${o}' was saved, but the server returned no version for a row it wrote \u2014 fetch it before the next push.`]:[]]}},delete(e,t,n){return $ae(e,t,n)}};async function v2(e,t,n){let r=`/${E0}${(0,Kn.odataQuery)([["$select","customapiid,uniquename"],["$filter",`uniquename eq '${(0,Kn.odataLiteral)(t)}'`],...n!==void 0?[["$top",String(n)]]:[]])}`,i=e.apiUrl(r),o;if(n===void 0)o=await(0,ss.collectPages)(e,r,"resolveArtifact('customApi')");else{let a=(0,en.ensureSuccess)(await e.get(r),i).body;if(o=a?.value,Array.isArray(o)&&!(0,ss.boundedPageComplete)(a,o.length,n))throw Yc(i,"the list of custom APIs (the answer says more rows exist)")}if(!Array.isArray(o))throw Yc(i,"the list of custom APIs");return o.map(a=>({id:String(a.customapiid),name:String(a.uniquename)}))}ut.resolveCustomApis=v2;async function Vae(e,t){let n=await v2(e,t,2);if(n.length>1)throw new Zt.AmbiguousArtifactError("customApi",t,n.length);return n.length===1?n[0].id:null}ut.findCustomApi=Vae;var f2=25;async function Gae(e,t){let n=t.filter(s=>s.customApi==="requestParameter"||s.customApi==="responseProperty"),r=new Map,i=[],o=[];for(let s of t)if(s.customApi==="api")try{let u=(0,Kn.normalizeGuid)(s.objectId,"objectid");r.set(u,{...s,objectId:u})}catch(u){o.push({component:s,error:u})}else s.customApi===void 0&&i.push(s);if(n.length>0){let s=(await(0,m2.resolveCustomApiComponentTypes)(e)).api;for(let u of da){let l=n.filter(c=>c.customApi===u.kind);for(let c=0;c<l.length;c+=f2){let d=l.slice(c,c+f2),f=[];for(let g of d)try{f.push((0,Kn.normalizeGuid)(g.objectId,"objectid"))}catch(y){o.push({component:g,error:y})}if(f.length===0)continue;let p=`/${u.set}${(0,Kn.odataQuery)([["$select",`${u.pk},_customapiid_value`],["$filter",f.map(g=>`${u.pk} eq ${g}`).join(" or ")]])}`,m,h;try{let g=await(0,ss.collectPages)(e,p,"fetchSolution custom API parents");m=new Map(g.filter(y=>typeof y[u.pk]=="string"&&typeof y._customapiid_value=="string").map(y=>[(0,rt.canonicalGuid)(String(y[u.pk])),(0,rt.canonicalGuid)(String(y._customapiid_value))]))}catch(g){h=g}for(let g of d){let y=m?.get((0,rt.canonicalGuid)(g.objectId));y&&s!==void 0?r.has(y)||r.set(y,{objectId:y,componentType:s,customApi:"api"}):o.some(b=>b.component===g)||o.push({component:g,error:h??Yc(e.apiUrl(p),`the custom API ${u.kind} '${g.objectId}' or its API`)})}}}}let a=s=>s.objectId.toLowerCase().replace(/^\{|\}$/g,"");return{components:[...i,...r.values()].sort((s,u)=>s.componentType-u.componentType||(a(s)<a(u)?-1:a(s)>a(u)?1:0)),failed:o}}ut.foldCustomApiChildComponents=Gae});var lC=C(qe=>{"use strict";Object.defineProperty(qe,"__esModule",{value:!0});qe.sameContent=qe.isRuleToken=qe.ruleToken=qe.projectAggregate=qe.statePath=qe.aggregatePath=qe.statusOf=qe.MATCH_CODES=qe.DUPLICATE_RULE_READ_INCOMPLETE=qe.CONDITIONS_NAV=qe.DUPLICATE_RULE_CONDITION_SET=qe.DUPLICATE_RULE_SET=void 0;var jae=Y(),Wae=Ke(),zae=r0(),w2=ae();qe.DUPLICATE_RULE_SET="duplicaterules";qe.DUPLICATE_RULE_CONDITION_SET="duplicateruleconditions";qe.CONDITIONS_NAV="DuplicateRule_DuplicateRuleConditions";qe.DUPLICATE_RULE_READ_INCOMPLETE="DUPLICATE_RULE_READ_INCOMPLETE";var Hae="duplicateruleid,name,description,baseentityname,matchingentityname,iscasesensitive,excludeinactiverecords,statecode,statuscode",Kae="duplicateruleconditionid,baseattributename,matchingattributename,operatorcode,operatorparam,ignoreblankvalues,_regardingobjectid_value";qe.MATCH_CODES={exact:0,firstCharacters:1,lastCharacters:2,sameDate:3,sameDateAndTime:4,exactChoiceLabel:5,exactChoiceValue:6};var Jae=new Map(Object.entries(qe.MATCH_CODES).map(([e,t])=>[t,e]));function E2(e,t){if(e===0&&t===0)return"unpublished";if(e===0&&t===1)return"publishing";if(e===1&&t===2)return"published"}qe.statusOf=E2;var Yae=/^\{?[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}\}?$/,Pp=e=>e.toLowerCase().replace(/^\{|\}$/g,"");function Qae(e){return`/${qe.DUPLICATE_RULE_SET}(${e})${(0,w2.odataQuery)([["$select",Hae],["$expand",`${qe.CONDITIONS_NAV}($select=${Kae})`]])}`}qe.aggregatePath=Qae;function Xae(e){return`/${qe.DUPLICATE_RULE_SET}(${e})${(0,w2.odataQuery)([["$select","statecode,statuscode"]])}`}qe.statePath=Xae;function Cr(e,t){return new jae.SdkError(qe.DUPLICATE_RULE_READ_INCOMPLETE,`Duplicate rule '${e}' could not be read completely: ${t}. Nothing is concluded from an incomplete read \u2014 an absent or malformed condition set is never taken as "no conditions".`)}function Zae(e,t){let n=Pp(String(t));if(e===null||typeof e!="object"||Array.isArray(e))throw Cr(n,"the answer is not an object");let r=e,i=l=>{let c=r[l];if(typeof c!="string"||c==="")throw Cr(n,`'${l}' is not a non-empty string`);return c},o=l=>{if(typeof r[l]!="boolean")throw Cr(n,`'${l}' is not a boolean`);return r[l]};if(typeof r.duplicateruleid!="string"||Pp(r.duplicateruleid)!==n)throw Cr(n,"the answer is not this rule");if(r.description!==null&&typeof r.description!="string")throw Cr(n,"'description' is neither a string nor null (absent from the answer)");let a=E2(r.statecode,r.statuscode);if(!a)throw Cr(n,`the state ${String(r.statecode)}/${String(r.statuscode)} is not a known pair`);if(r[`${qe.CONDITIONS_NAV}@odata.nextLink`]!==void 0)throw Cr(n,"the condition collection is paged");if((0,Wae.moreRecordsClaim)(r,qe.CONDITIONS_NAV)!=="none")throw Cr(n,"the condition collection says more rows exist");let s=r[qe.CONDITIONS_NAV];if(!Array.isArray(s))throw Cr(n,"the condition collection is absent");let u=s.map((l,c)=>ese(n,l,c));return{id:n,name:i("name"),description:r.description,entityLogicalName:i("baseentityname"),matchingEntityLogicalName:i("matchingentityname"),caseSensitive:o("iscasesensitive"),excludeInactiveRecords:o("excludeinactiverecords"),status:a,conditions:u.sort((l,c)=>l.id<c.id?-1:1)}}qe.projectAggregate=Zae;function ese(e,t,n){let r=`condition ${n}`;if(t===null||typeof t!="object")throw Cr(e,`${r} is not an object`);let i=t;if(typeof i.duplicateruleconditionid!="string"||!Yae.test(i.duplicateruleconditionid))throw Cr(e,`${r} has no id`);for(let a of["baseattributename","matchingattributename"])if(typeof i[a]!="string"||i[a]==="")throw Cr(e,`${r}: '${a}' is not a non-empty string`);let o=typeof i.operatorcode=="number"?Jae.get(i.operatorcode):void 0;if(!o)throw Cr(e,`${r}: operator ${String(i.operatorcode)} is not one of 0-6`);if(i.operatorparam!==null&&typeof i.operatorparam!="number")throw Cr(e,`${r}: 'operatorparam' is neither a number nor null`);if(typeof i.ignoreblankvalues!="boolean")throw Cr(e,`${r}: 'ignoreblankvalues' is not a boolean`);if(typeof i._regardingobjectid_value!="string"||Pp(i._regardingobjectid_value)!==e)throw Cr(e,`${r} does not belong to this rule`);return{id:Pp(i.duplicateruleconditionid),column:i.baseattributename,matchingColumn:i.matchingattributename,match:o,characters:i.operatorparam,ignoreBlankValues:i.ignoreblankvalues}}function tse(e){var t,n,r,i,o;return[Pp((t=e.id)!==null&&t!==void 0?t:""),e.column,(n=e.matchingColumn)!==null&&n!==void 0?n:e.column,(r=qe.MATCH_CODES[e.match])!==null&&r!==void 0?r:e.match,(i=e.characters)!==null&&i!==void 0?i:null,(o=e.ignoreBlankValues)!==null&&o!==void 0?o:!1]}function uC(e,t){var n,r,i,o,a;return[e.name,(n=e.description)!==null&&n!==void 0?n:null,e.entityLogicalName,(r=e.matchingEntityLogicalName)!==null&&r!==void 0?r:e.entityLogicalName,(i=e.caseSensitive)!==null&&i!==void 0?i:!1,(o=e.excludeInactiveRecords)!==null&&o!==void 0?o:!1,t,((a=e.conditions)!==null&&a!==void 0?a:[]).map(tse).sort((s,u)=>s[0]<u[0]?-1:s[0]>u[0]?1:0)]}function nse(e){return`dr1:${(0,zae.fnv128Hex)("duplicateRule",JSON.stringify(uC(e,e.status)))}`}qe.ruleToken=nse;function rse(e){return typeof e=="string"&&/^dr1:[0-9a-f]{32}$/.test(e)}qe.isRuleToken=rse;function ise(e,t){return JSON.stringify(uC(e,null))===JSON.stringify(uC(t,null))}qe.sameContent=ise});var S0=C(gt=>{"use strict";Object.defineProperty(gt,"__esModule",{value:!0});gt.foldDuplicateRuleConditionComponents=gt.findDuplicateRule=gt.resolveDuplicateRules=gt.duplicateRuleApi=gt.PUBLISH_WAIT_MS=gt.PUBLISH_POLL_MS=gt.DUPLICATE_RULE_READ_INCOMPLETE=gt.DUPLICATE_RULE_IDENTITY_MISMATCH=gt.DUPLICATE_RULE_UPDATE_NOT_ATOMIC=gt.DUPLICATE_RULE_PUBLISH_FAILED=void 0;var ou=Ke(),cC=Zo(),Zc=g0(),Pe=lC();Object.defineProperty(gt,"DUPLICATE_RULE_READ_INCOMPLETE",{enumerable:!0,get:function(){return Pe.DUPLICATE_RULE_READ_INCOMPLETE}});var vt=Y(),gl=pe(),ur=ae();gt.DUPLICATE_RULE_PUBLISH_FAILED="DUPLICATE_RULE_PUBLISH_FAILED";gt.DUPLICATE_RULE_UPDATE_NOT_ATOMIC="DUPLICATE_RULE_UPDATE_NOT_ATOMIC";gt.DUPLICATE_RULE_IDENTITY_MISMATCH="DUPLICATE_RULE_IDENTITY_MISMATCH";var T2="/CompoundUpdateDuplicateDetectionRule";gt.PUBLISH_POLL_MS=2e3;gt.PUBLISH_WAIT_MS=6e4;var Rp=e=>e instanceof Error?e:new Error(String(e));function fC(e){var t;let n=(t=e?.error)===null||t===void 0?void 0:t.message;return typeof n=="string"?n:""}async function Qc(e,t){let n=(0,Pe.aggregatePath)(t);try{let r=await e.get(n);if(r.status===404)return{kind:"gone"};(0,gl.ensureSuccess)(r,e.apiUrl(n));let i=await ose(e,t,e.apiUrl(n),r);return{kind:"read",rule:(0,Pe.projectAggregate)(i,t),raw:i}}catch(r){return{kind:"unusable",error:Rp(r)}}}async function ose(e,t,n,r){let i=r.body;if(i===null||typeof i!="object"||Array.isArray(i))return i;let o={...i},a=`${Pe.CONDITIONS_NAV}@odata.nextLink`,s=`${Pe.CONDITIONS_NAV}${ou.MORE_RECORDS_ANNOTATION}`,u=o[a];if((0,ou.pageEnd)(o,Pe.CONDITIONS_NAV).kind==="end")return delete o[a],o;let l;try{l=await(0,ou.continuePages)(e,{...r,body:{value:o[Pe.CONDITIONS_NAV],"@odata.nextLink":u,[ou.MORE_RECORDS_ANNOTATION]:o[s]}},n,`the conditions of duplicate rule '${t}'`)}catch(c){throw c instanceof vt.InvalidArgumentError||c instanceof vt.ConnectionError&&c.statusCode>=200&&c.statusCode<300?(0,vt.attachCause)(new vt.SdkError(Pe.DUPLICATE_RULE_READ_INCOMPLETE,`The conditions of duplicate rule '${t}' could not be read completely (${Rp(c).message}); a partial set is never taken as the whole one.`),c):c}return delete o[a],delete o[s],o[Pe.CONDITIONS_NAV]=l,o}function ed(e,t,n,r){return(0,vt.attachCause)(new vt.ConnectionError(e,n,`the outcome of the write of duplicateRule '${t}' is unknown \u2014 it may or may not have been applied, and it is not re-sent. Re-fetch the rule to see what the server holds.`),r)}var pC=e=>gl.AMBIGUOUS_WRITE_STATUSES.has(e)||e>=500;async function ase(e,t,n){let r=e.apiUrl(n.path),i=n.etag?{headers:{"If-Match":n.etag}}:void 0,o;try{o=n.method==="POST"?await e.post(n.path,n.body,i):n.method==="PATCH"?await e.patch(n.path,n.body,i):await e.delete(n.path,i)}catch(a){throw(0,Zc.isTransportFailure)(a)?ed(r,t,0,a):a}if(pC(o.status))throw ed(r,t,o.status,o.body);(0,gl.ensureSuccess)(o,r)}async function A2(e,t,n){var r;if(n.length===1){await ase(e,t,n[0]);return}let{body:i,batchId:o,contentIds:a}=(0,cC.renderChangeSet)(e,n),s=e.apiUrl("/$batch"),u;try{u=await e.postBatch(i,o)}catch(d){throw(0,Zc.isTransportFailure)(d)?ed(s,t,0,d):d}let l=(0,cC.parseChangeSetParts)(u.body,a),c=l?.find(d=>d.status<200||d.status>=300);if(c){let d=(0,cC.partResponse)(c),f=(r=(0,Zc.platformErrorCode)(d.body))!==null&&r!==void 0?r:"";throw new vt.ConnectionError(s,d.status,`the write of duplicateRule '${t}' was refused and changed nothing (the change set rolled back): HTTP `+`${d.status} ${f} ${fC(d.body)}`.trim(),d.body)}if(u.status<200||u.status>=300||!l||l.length!==n.length)throw ed(s,t,u.status,u.body)}function C2(e,t,n){var r,i,o,a;if(Xc((r=t?.desired)===null||r===void 0?void 0:r.id)!==e)throw iu(e,`the artifact names rule '${String((i=t?.desired)===null||i===void 0?void 0:i.id)}'`,!1);let u=`/${Pe.DUPLICATE_RULE_SET}(${e})`;for(let l of t.ops){let c=(o=l.body)!==null&&o!==void 0?o:{};if(l.path===`/${Pe.DUPLICATE_RULE_SET}`){if(!n||l.method!=="POST"||Xc(c.duplicateruleid)!==e)throw iu(e,`a create addresses rule '${String(c.duplicateruleid)}'`,!1)}else if(l.path.startsWith(`/${Pe.DUPLICATE_RULE_SET}(`)){if(l.path.toLowerCase()!==u)throw iu(e,`an operation addresses '${l.path}'`,!1)}else if(l.path===T2){let d=c.Entity;if(Xc(d?.duplicateruleid)!==e)throw iu(e,`the compound update names rule '${String(d?.duplicateruleid)}'`,!1)}else if(l.path===`/${Pe.DUPLICATE_RULE_CONDITION_SET}`&&l.method==="POST"){let d=String((a=c["[email protected]"])!==null&&a!==void 0?a:"");if(d.toLowerCase()!==u)throw iu(e,`a new condition is bound to '${d}'`,!1)}else if(!l.path.startsWith(`/${Pe.DUPLICATE_RULE_CONDITION_SET}(`))throw iu(e,`an operation addresses '${l.path}', which is not part of a duplicate rule`,!1)}}function sse(e,t,n){var r,i;let o=new Set(n.conditions.map(u=>u.id)),a=new Set(t.filter(u=>u.method==="POST"&&u.path===`/${Pe.DUPLICATE_RULE_CONDITION_SET}`).map(u=>{var l;return Xc((l=u.body)===null||l===void 0?void 0:l.duplicateruleconditionid)})),s=`/${Pe.DUPLICATE_RULE_CONDITION_SET}(`;for(let u of t){if(u.path.startsWith(s)){let l=Xc(u.path.slice(s.length,-1));if(!l||!o.has(l))throw iu(e,`an operation addresses condition '${u.path}', which the guard did not read on this rule`,!0)}if(u.path===T2){let l=(i=(r=u.body)===null||r===void 0?void 0:r.ChildEntities)!==null&&i!==void 0?i:[];for(let c of l){let d=Xc(c?.duplicateruleconditionid);if(!d||!o.has(d)&&!a.has(d))throw iu(e,`the compound update lists condition '${String(c?.duplicateruleconditionid)}', which is neither on this rule nor created by this push`,!0)}}}}function Xc(e){try{return typeof e=="string"?(0,ur.normalizeGuid)(e,"id"):void 0}catch{return}}function iu(e,t,n){return new vt.SdkError(gt.DUPLICATE_RULE_IDENTITY_MISMATCH,`Refusing to push duplicateRule '${e}': ${t}. A push writes only the rule it guarded, and a rule's id is fixed \u2014 to copy a rule, create a new one. Nothing was ${n?"written":"sent"}.`)}function S2(e,t,n){if(n.length>1&&!e.supportsAtomicBatch)throw new vt.SdkError(gt.DUPLICATE_RULE_UPDATE_NOT_ATOMIC,`Refusing to push duplicateRule '${t}': this change needs ${n.length} requests in one atomic change set, and the injected HttpClient has no postRaw() to send one. Nothing was sent.`)}var use={"0x80048419":"at most 5 rules can be published per table \u2014 unpublish one","0x80048410":"duplicate detection is off for this table (updateTable(table, { duplicateDetectionEnabled: true })) or for the organization","0x80048414":"a published rule needs a condition","0x80048434":"a publish is already running \u2014 re-fetch"};async function lse(e){await new Promise(t=>setTimeout(t,e))}async function cse(e,t,n,r){let i=n+gt.PUBLISH_WAIT_MS;for(;;){let o=i-Date.now();if(o<=0)return;await lse(Math.min(gt.PUBLISH_POLL_MS,o));let a;try{let s=await e.get((0,Pe.statePath)(t));if(s.status<200||s.status>=300)return;let u=s.body;a=(0,Pe.statusOf)(u?.statecode,u?.statuscode)}catch{return}if(a==="publishing"){r.sawPublishing=!0;continue}if(a==="published"||a===void 0||a==="unpublished"&&r.sawPublishing)return}}function dse(e,t,n,r){var i;if(!n){e.request="unknown",e.transportError=Rp(r);return}if(n.status>=200&&n.status<300){e.request="accepted";let a=(i=n.body)===null||i===void 0?void 0:i.asyncoperationid;typeof a=="string"&&(e.jobId=a);return}let o=new vt.ConnectionError(t,n.status,fC(n.body),n.body);if(pC(n.status)){e.request="unknown",e.transportError=o;return}e.request="refused",e.refusal={status:n.status,code:(0,Zc.platformErrorCode)(n.body),message:fC(n.body),error:o}}async function fse(e,t,n){let r=e.withoutSolution(),i=n.action==="publish"?`/${Pe.DUPLICATE_RULE_SET}(${t})/Microsoft.Dynamics.CRM.PublishDuplicateRule`:"/UnpublishDuplicateRule",o=n.action==="publish"?{}:{DuplicateRuleId:t},a=Date.now(),s,u;try{s=await r.post(i,o)}catch(l){if(!(0,Zc.isTransportFailure)(l))throw l;u=l}dse(n,r.apiUrl(i),s,u),n.action==="publish"&&n.request!=="refused"&&await cse(e,t,a,n)}async function O2(e,t,n){var r;if(n.request==="refused"&&n.refusal){let a=n.refusal.code?use[n.refusal.code]:void 0;return(0,vt.attachCause)(new vt.SdkError(gt.DUPLICATE_RULE_PUBLISH_FAILED,`Publishing duplicate rule '${t}' was refused (HTTP ${n.refusal.status} ${(r=n.refusal.code)!==null&&r!==void 0?r:""})${a?`: ${a}`:`: ${n.refusal.message}`}. The save is unaffected; push again once it is resolved.`),n.refusal.error)}let i="";if(n.jobId)try{let a=`/asyncoperations(${n.jobId})${(0,ur.odataQuery)([["$select","message,friendlymessage"]])}`,s=await e.get(a),u=s.body,l=u?.friendlymessage||u?.message;i=s.status===200&&typeof l=="string"&&l?` The publish job says: ${l}`:""}catch{i=""}let o=new vt.SdkError(gt.DUPLICATE_RULE_PUBLISH_FAILED,`Duplicate rule '${t}': the rule reads unpublished after the publish request${n.request==="unknown"?" (whose answer was lost)":""}.${i} The save is unaffected; push again to retry the publish.`);return n.transportError?(0,vt.attachCause)(o,n.transportError):o}async function pse(e,t,n,r,i){var o,a,s,u;let l=r.request==="accepted"||r.request==="unknown",c,d;if(n==="published"&&r.action==="publish"&&l)c={kind:"submitted"},d=`Duplicate rule '${t}' was saved and is still publishing \u2014 re-fetch to see the result.${i}`;else if(n==="published"&&r.action==="publish"&&r.request==="refused")c={kind:"failed",error:await O2(e,t,r)},d=`Duplicate rule '${t}' was saved, but its publish was refused and the rule reads publishing \u2014 another writer is publishing it; re-fetch to see the result.${i}`;else if(n==="published")c={kind:"failed",error:new vt.VersionConflictError("duplicateRule",t,null,null,"Saved, but another writer is publishing the rule; this push did not publish it.")},d=`Duplicate rule '${t}' was saved; the rule reads publishing \u2014 another writer is publishing it, this push did not; re-fetch to see the result.${i}`;else{c={kind:"notRequested"};let f=r.action!=="unpublish"||r.request==="none"?"":r.request==="refused"?` its unpublish was refused (HTTP ${(a=(o=r.refusal)===null||o===void 0?void 0:o.status)!==null&&a!==void 0?a:""} ${(u=(s=r.refusal)===null||s===void 0?void 0:s.code)!==null&&u!==void 0?u:""}),`:r.request==="unknown"?" its unpublish answer was lost,":" its unpublish was accepted,";d=`Duplicate rule '${t}' was saved;${f} and the rule reads publishing \u2014 another writer is publishing it, so it is not unpublished; re-fetch.${i}`}return{id:t,etag:null,publish:c,warnings:[d]}}async function mse(e,t,n,r,i){var o;let a=n.desired.status,u=n.heldStatus==="published"&&n.statusAfterContent==="unpublished"?" This edit took the published rule offline.":"";if(r.kind==="read"&&(0,Pe.sameContent)(r.rule,n.desired)){let d=r.rule.status;if(d===a)return{id:t,etag:(0,Pe.ruleToken)(r.rule),serverState:d,publish:a==="published"?{kind:"verified"}:{kind:"notRequested"}};if(d==="publishing")return pse(e,t,a,i,u);if(a==="published")return{id:t,etag:(0,Pe.ruleToken)(r.rule),serverState:d,publish:{kind:"failed",error:await O2(e,t,i)},warnings:[`Duplicate rule '${t}' was saved; the rule reads unpublished \u2014 it is NOT checking records.${u}`]};let f=i.request==="refused"&&i.refusal?`the platform refused it: HTTP ${i.refusal.status} ${(o=i.refusal.code)!==null&&o!==void 0?o:""} ${i.refusal.message}`.trim():"its outcome is unknown";return{id:t,etag:(0,Pe.ruleToken)(r.rule),serverState:d,publish:{kind:"notRequested"},warnings:[`Duplicate rule '${t}' was saved but could not be unpublished (${f}) \u2014 the rule is still checking records.`]}}let l=r.kind==="gone"?"the rule is gone \u2014 another writer deleted it after the save":r.kind==="unusable"?`the rule could not be read (${r.error.message})`:"the rule changed on the server after the save \u2014 another writer changed it",c={kind:"notRequested"};return a==="published"&&(i.g2Stopped?c={kind:"failed",error:r.kind==="unusable"?r.error instanceof vt.SdkError&&r.error.code===Pe.DUPLICATE_RULE_READ_INCOMPLETE?r.error:(0,vt.attachCause)(new vt.SdkError(Pe.DUPLICATE_RULE_READ_INCOMPLETE,`Saved, but ${l}; this push did not publish it.`),r.error):new vt.VersionConflictError("duplicateRule",t,null,null,`Saved, but ${l}; this push did not publish it.`)}:c={kind:"unverifiable",reason:l}),{id:t,etag:null,publish:c,warnings:[`Duplicate rule '${t}' was saved, but ${l}; whether it is published is unknown \u2014 re-fetch before the next push (it refuses until then).${u}`]}}async function N2(e,t,n){let r=n.desired.status,i=n.statusAfterContent,o={g2Stopped:!1,request:"none",sawPublishing:!1};r==="published"&&i==="unpublished"?o.action="publish":r==="unpublished"&&i==="published"&&(o.action="unpublish");try{let a;if(!o.action)a=await Qc(e,t);else{let s=await Qc(e,t);s.kind!=="read"||(0,Pe.ruleToken)(s.rule)!==(0,Pe.ruleToken)({...n.desired,status:i})?(o.g2Stopped=!0,a=s):(await fse(e,t,o),a=await Qc(e,t))}return await mse(e,t,n,a,o)}catch(a){return{id:t,etag:null,publish:r==="published"?{kind:"unverifiable",reason:`the publish step failed: ${Rp(a).message}`}:{kind:"notRequested"},warnings:[`Duplicate rule '${t}' was saved, but the step after the save failed (${Rp(a).message}); its state is unknown \u2014 re-fetch before the next push.`]}}}function D2(e,t,n,r){return new vt.VersionConflictError("duplicateRule",e,t,n.kind==="read"?(0,Pe.ruleToken)(n.rule):null,n.kind==="gone"?`Another writer deleted it since it was fetched; ${r}.`:`Another writer changed it since it was fetched; ${r}.`)}async function hse(e,t,n){var r;let i=(0,ur.normalizeGuid)(t,"id"),o=(r=n?.token)!==null&&r!==void 0?r:null;if(!(0,Pe.isRuleToken)(o))throw new vt.SdkError(gl.DELETE_NO_ETAG_CODE,`Refusing to delete duplicateRule '${i}': no usable version is held for it, so the delete could not be guarded and could remove what another writer changed. Fetch it first (fetchArtifact).`);let a=await Qc(e,i);if(a.kind==="unusable")throw a.error;if(a.kind==="gone"||(0,Pe.ruleToken)(a.rule)!==o)throw D2(i,o,a,"nothing was deleted");let s=`/${Pe.DUPLICATE_RULE_SET}(${i})`,u=e.apiUrl(s),l;try{l=await e.delete(s)}catch(c){throw(0,Zc.isTransportFailure)(c)?ed(u,i,0,c):c}if(l.status===404)throw new vt.VersionConflictError("duplicateRule",i,o,null,"It was deleted by another writer in between.");if(pC(l.status))throw ed(u,i,l.status,l.body);(0,gl.ensureSuccess)(l,u)}gt.duplicateRuleApi={async get(e,t){let n=(0,ur.normalizeGuid)(t,"id"),r=await Qc(e,n);if(r.kind==="gone"){let i=(0,Pe.aggregatePath)(n);throw new vt.ConnectionError(e.apiUrl(i),404,`duplicate rule '${n}' does not exist`)}if(r.kind==="unusable")throw r.error;return{raw:r.raw,etag:(0,Pe.ruleToken)(r.rule)}},async list(e,t){let n=`/${Pe.DUPLICATE_RULE_SET}${(0,ur.odataQuery)([["$select","duplicateruleid,name,baseentityname"],["$filter",t?.entityLogicalName?`baseentityname eq '${(0,ur.odataLiteral)(t.entityLogicalName)}'`:void 0]])}`;return(await(0,ou.collectPages)(e,n,"fetchArtifactList('duplicateRule')")).map(i=>{var o,a,s;return{type:"duplicateRule",id:(0,ur.normalizeGuid)(String((o=i.duplicateruleid)!==null&&o!==void 0?o:""),"duplicateruleid"),name:String((a=i.name)!==null&&a!==void 0?a:""),entityLogicalName:String((s=i.baseentityname)!==null&&s!==void 0?s:""),isDirty:!1}})},async create(e,t,n){let r=t,i=(0,ur.normalizeGuid)(n??r.desired.id,"id");return C2(i,r,!0),S2(e,i,r.ops),await A2(e,i,r.ops),N2(e,i,r)},async update(e,t,n,r){let i=(0,ur.normalizeGuid)(t,"id"),o=n;if(!(0,Pe.isRuleToken)(r))throw new vt.SdkError(gl.UPDATE_NO_ETAG_CODE,`Refusing to push duplicateRule '${i}': ${r?`the version held for it ('${r}') is not a duplicate-rule version`:"no version is held for it"}, so the write could not be guarded. Re-fetch the rule and re-apply the change.`);C2(i,o,!1),S2(e,i,o.ops);let a=await Qc(e,i);if(a.kind==="unusable")throw a.error;if(a.kind==="gone"||(0,Pe.ruleToken)(a.rule)!==r)throw D2(i,r,a,"nothing was written");return sse(i,o.ops,a.rule),await A2(e,i,o.ops),N2(e,i,o)},delete(e,t,n){return hse(e,t,n)}};async function P2(e,t,n,r){let i=`name eq '${(0,ur.odataLiteral)(t)}'${n?` and baseentityname eq '${(0,ur.odataLiteral)(n)}'`:""}`,o=`/${Pe.DUPLICATE_RULE_SET}${(0,ur.odataQuery)([["$select","duplicateruleid,name"],["$filter",i],...r!==void 0?[["$top",String(r)]]:[]])}`,a=e.apiUrl(o),s;if(r===void 0)s=await(0,ou.collectPages)(e,o,"resolveArtifact('duplicateRule')");else{let u=(0,gl.ensureSuccess)(await e.get(o),a).body;if(s=u?.value,Array.isArray(s)&&!(0,ou.boundedPageComplete)(u,s.length,r))throw new vt.ConnectionError(a,200,"the list of duplicate rules is incomplete (the answer says more rows exist), so it proves neither absence nor a single match")}if(!Array.isArray(s))throw new vt.ConnectionError(a,200,"the response could not be read as a list of duplicate rules");return s.map(u=>{var l,c;return{id:(0,ur.normalizeGuid)(String((l=u.duplicateruleid)!==null&&l!==void 0?l:""),"duplicateruleid"),name:String((c=u.name)!==null&&c!==void 0?c:"")}})}gt.resolveDuplicateRules=P2;async function gse(e,t,n){let r=await P2(e,t,n,2);if(r.length>1)throw new vt.AmbiguousArtifactError("duplicateRule",t,r.length);return r.length===1?r[0].id:null}gt.findDuplicateRule=gse;var dC=4414,_2=4416,I2=50;async function yse(e,t){let n=[],r=[],i=t.filter(d=>d.componentType===_2);if(i.length===0&&!t.some(d=>d.componentType===dC))return{components:t,failed:n,orphaned:r};let o=new Set,a=[];for(let d of t)if(d.componentType===dC)try{o.add((0,ur.normalizeGuid)(d.objectId,"objectid"))}catch(f){n.push({component:d,error:f})}else d.componentType!==_2&&a.push(d);let s=new Map;for(let d of i)try{s.set((0,ur.normalizeGuid)(d.objectId,"objectid"),d)}catch(f){n.push({component:d,error:f})}let u=[...s.keys()];for(let d=0;d<u.length;d+=I2){let f=u.slice(d,d+I2),p=`/${Pe.DUPLICATE_RULE_CONDITION_SET}${(0,ur.odataQuery)([["$select","duplicateruleconditionid,_regardingobjectid_value"],["$filter",f.map(m=>`duplicateruleconditionid eq ${m}`).join(" or ")]])}`;try{let m=await(0,ou.collectPages)(e,p,"fetchSolution (duplicate rule conditions)"),h=new Map;for(let g of m)typeof g.duplicateruleconditionid=="string"&&h.set(g.duplicateruleconditionid.toLowerCase(),g._regardingobjectid_value);for(let g of f){let y=s.get(g),b=h.get(g);typeof b=="string"?o.add((0,ur.normalizeGuid)(b,"_regardingobjectid_value")):r.push({component:y,detail:"A duplicate-rule condition that no longer exists (or has no rule), so there is no rule to fetch for it."})}}catch(m){for(let h of f)n.push({component:s.get(h),error:m})}}let l=[...o].map(d=>({objectId:d,componentType:dC})),c=d=>d.objectId.toLowerCase().replace(/^\{|\}$/g,"");return{components:[...a,...l].sort((d,f)=>d.componentType-f.componentType||(c(d)<c(f)?-1:c(d)>c(f)?1:0)),failed:n,orphaned:r}}gt.foldDuplicateRuleConditionComponents=yse});var gC=C(He=>{"use strict";Object.defineProperty(He,"__esModule",{value:!0});He.compileGenPage=He.legacyEnumsNeeded=He.createGenPageTypeScriptLoader=He.acceptGenPageTypeScript=He.isLoadableGenPageOutput=He.runtimeTypesImportSpans=He.resolveGenPageIteration=He.GENPAGE_ITERATION_DEFAULT=He.GENPAGE_RUNTIME_TYPES_END=He.GENPAGE_RUNTIME_TYPES_BEGIN=He.GENPAGE_TYPESCRIPT_VERSION=void 0;var au=Y();He.GENPAGE_TYPESCRIPT_VERSION="5.8.3";He.GENPAGE_RUNTIME_TYPES_BEGIN="// --- BEGIN GENERATED RUNTIME TYPES ---";He.GENPAGE_RUNTIME_TYPES_END="// --- END GENERATED RUNTIME TYPES ---";He.GENPAGE_ITERATION_DEFAULT="iterator";function bse(e){if(e===void 0)return He.GENPAGE_ITERATION_DEFAULT;if(e==="legacy"||e==="iterator")return e;throw new au.InvalidArgumentError(`genPageIteration must be 'legacy' or 'iterator', or omitted (got ${typeof e=="string"?`'${e}'`:String(e)}).`)}He.resolveGenPageIteration=bse;var _o="./RuntimeTypes",vse="'\"`",R2=/\s/;function wse(e){return e===10||e===13||e===8232||e===8233}function Ese(e,t){let n=[];e.lastIndex=0;for(let r=e.exec(t);r!==null;r=e.exec(t))n.push(r.index);return n}function M2(e){let t=[],n=_o.length;for(let u=e.indexOf(_o);u!==-1;u=e.indexOf(_o,u+1)){let l=u-1;l>=0&&vse.includes(e[l])&&e[l+1+n]===e[l]&&t.push(l)}let r=[];if(t.length===0)return r;let i=-1,o=u=>{if(i<u)for(i=u;i<e.length&&e[i]!=="'"&&e[i]!=='"';)i+=1;return i},a=-1,s=u=>{for(;a+1<t.length&&t[a+1]<=u;)a+=1;return a>=0?t[a]:-1/0};for(let u=e.indexOf("import");u!==-1;){let l=u+1;if(u+6<e.length&&R2.test(e[u+6])){let c=s(o(u+6));if(c>=u+8){let d=c+2+n;for(e[d]===";"&&(d+=1);d<e.length&&R2.test(e[d]);)d+=1;r.push({start:u,end:d}),l=d}}u=e.indexOf("import",l)}return r}He.runtimeTypesImportSpans=M2;var Ase=/\b(?:import\s*['"]|export\s)/;function Cse(e){let t=Ese(/from\s+['"]/g,e);if(t.length===0)return!1;let n=/\bimport\s/g,r=-1,i=0;for(let o=n.exec(e);o!==null;o=n.exec(e)){let a=o.index+7;if(a>r)for(r=a;r<e.length&&!wse(e.charCodeAt(r));)r+=1;for(;i<t.length&&t[i]<a+1;)i+=1;if(i<t.length&&t[i]<r)return!0}return!1}function Sse(e){return e!==void 0&&e!==""&&(Ase.test(e)||Cse(e))}He.isLoadableGenPageOutput=Sse;var k2=["transpileModule","createSourceFile","createProgram","getParseTreeNode","flattenDiagnosticMessageText","forEachChild","getModifiers","canHaveModifiers","isImportDeclaration","isExportDeclaration","isExportAssignment","isStringLiteral"];function x2(e){var t;let n=s=>s!==null&&(typeof s=="object"||typeof s=="function")?s:void 0,r=n(e);r&&typeof r.transpileModule!="function"&&(r=(t=n(r.default))!==null&&t!==void 0?t:r);let i=r?k2.filter(s=>typeof r?.[s]!="function"):[...k2];if(!r||i.length>0)throw new au.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@${He.GENPAGE_TYPESCRIPT_VERSION}'s lib/typescript.js.`);let o=typeof r.version=="string"?r.version:"",a=He.GENPAGE_TYPESCRIPT_VERSION.split(".").slice(0,2).join(".");if(o.split(".").slice(0,2).join(".")!==a)throw new au.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 (${He.GENPAGE_TYPESCRIPT_VERSION}). Another version can emit different JavaScript for the same page. Supply typescript@${He.GENPAGE_TYPESCRIPT_VERSION}.`);return r}He.acceptGenPageTypeScript=x2;function Nse(e){let t;return()=>{if(!t){if(e===void 0)return Promise.reject(new au.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@${He.GENPAGE_TYPESCRIPT_VERSION}'s lib/typescript.js. Nothing was written.`));t=Promise.resolve().then(()=>typeof e=="function"?e():e).then(x2).catch(n=>{throw t=void 0,n instanceof au.SdkError?n:new au.SdkError("GENPAGE_COMPILER_UNAVAILABLE",`The TypeScript compiler could not be loaded, so a generative page cannot be compiled (${n instanceof Error?n.message:String(n)}). Nothing was written.`)})}return t}}He.createGenPageTypeScriptLoader=Nse;var F2=e=>`${e.kind}:${e.pos}:${e.end}`;function _se(e,t){return()=>n=>{let r=i=>{let o=e.getParseTreeNode(i);o&&t.add(F2(o)),e.forEachChild(i,r)};return r(n),n}}function hC(e,t){return{target:e.ScriptTarget.ES5,module:e.ModuleKind.ES2020,jsx:e.JsxEmit.React,...t==="iterator"?{downlevelIteration:!0}:{}}}var Ise="The generative page could not be compiled because compilation exceeded this JavaScript engine's call-stack limit. Reduce nested JSX or expression complexity and retry. The page was not written.";function U2(e){if(typeof e!="object"||e===null)return!1;let{name:t,message:n}=e;return t==="RangeError"&&n==="Maximum call stack size exceeded"}var Tse=2301;function $2(e,t,n,r){var i;let o=e.transpileModule(t,{compilerOptions:hC(e,n),reportDiagnostics:!0,...r?{transformers:{after:[_se(e,r)]}}:{}}),a=((i=o.diagnostics)!==null&&i!==void 0?i:[]).filter(s=>s.category===e.DiagnosticCategory.Error).map(s=>{let u=s.file&&typeof s.start=="number"?s.file.getLineAndCharacterOfPosition(s.start):{line:0,character:0};return{line:u.line+1,column:u.character+1,rule:"genpage-source-syntax",code:s.code,message:e.flattenDiagnosticMessageText(s.messageText,`+`)}});return{code:o.outputText,diagnostics:a}}var L2=e=>e.startsWith(".")||e.startsWith("/"),N0={line:1,column:1};function mC(e,t){let n=o=>{let a=t.getLineAndCharacterOfPosition(o.getStart(t));return{line:a.line+1,column:a.character+1}},r=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)&&r(a)===o);return{statement(o,a){let s=t.statements.find(u=>r(u)===o&&(a==="import"?e.isImportDeclaration(u):e.isExportDeclaration(u)));return s?n(s):N0},element(o,a){var s;for(let u of i(o)){let l=(s=u.importClause)===null||s===void 0?void 0:s.namedBindings,c=l&&e.isNamedImports(l)?l.elements.find(d=>d.name.text===a):void 0;if(c)return n(c)}return this.statement(o,"import")},binding(o){var a,s;for(let u of t.statements)if(e.isImportDeclaration(u)&&u.importClause){let l=u.importClause,c=l.namedBindings,d=((a=l.name)===null||a===void 0?void 0:a.text)===o?l.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 n(d)}else{if((e.isFunctionDeclaration(u)||e.isClassDeclaration(u))&&((s=u.name)===null||s===void 0?void 0:s.text)===o)return n(u.name);if(e.isVariableStatement(u)){let l=u.declarationList.declarations.find(c=>e.isIdentifier(c.name)&&c.name.text===o);if(l)return n(l.name)}}return N0}}}function Ose(e,t,n,r){var i,o;let a=[],s=mC(e,n),u=(m,h,g)=>{a.push({...m,rule:h,code:0,message:g})},l=(m,h)=>{var g;return(e.canHaveModifiers(m)?(g=e.getModifiers(m))!==null&&g!==void 0?g:[]:[]).some(y=>y.kind===h)},c=(m,h)=>u(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)){l(m,e.SyntaxKind.ExportKeyword)&&l(m,e.SyntaxKind.DefaultKeyword)&&(f=!0),m.name&&p.add(m.name.text);continue}if(e.isExportDeclaration(m)){let b=m.exportClause;b&&e.isNamedExports(b)&&b.elements.some(w=>w.name.text==="default")&&(f=!0);let E=m.moduleSpecifier&&e.isStringLiteral(m.moduleSpecifier)?m.moduleSpecifier.text:void 0;E===_o?u(s.statement(E,"export"),d,"a page cannot re-export from './RuntimeTypes': that module does not exist at runtime"):E!==void 0&&L2(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!==_o){L2(h)&&c(s.statement(h,"import"),h),g?.name&&p.add(g.name.text);let b=g?.namedBindings;b&&e.isNamespaceImport(b)?p.add(b.name.text):b&&e.isNamedImports(b)&&b.elements.forEach(E=>p.add(E.name.text));continue}if(!g){u(s.statement(h,"import"),d,"a side-effect import of './RuntimeTypes' cannot resolve at runtime; import the names it declares");continue}g.name&&u(s.binding(g.name.text),d,"'./RuntimeTypes' has no default export at runtime; import its names");let y=g.namedBindings;if(y&&e.isNamespaceImport(y))u(s.binding(y.name.text),d,"a namespace import of './RuntimeTypes' is undefined at runtime \u2014 its enums are inlined under their own names; import the names instead");else if(y&&e.isNamedImports(y))for(let b of y.elements){let E=b.name.text,w=(o=(i=b.propertyName)===null||i===void 0?void 0:i.text)!==null&&o!==void 0?o:E,_=s.element(h,E);w!==E?u(_,d,`'${w} as ${E}' would be undefined at runtime: the enum is inlined as '${w}', so import it under its own name`):r?.text?r.enums.has(E)||u(_,"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'.`):u(_,"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||u(N0,"genpage-no-default-export","the page has no default export \u2014 the runtime renders the module's default export as the page component"),r?.text)for(let m of p)r.enums.has(m)&&u(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 q2(e,t,n){let r,i=()=>{if(!r){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={...n,noLib:!0,noResolve:!0,allowJs:!0,types:[],alwaysStrict:!0,moduleDetection:e.ModuleDetectionKind.Force};r=e.createProgram({rootNames:[t.fileName],options:h,host:m})}return r},o,a=()=>(o||(o=i().getTypeChecker()),o),s,u=()=>{if(!s){s=new Map;try{for(let m of i().getSemanticDiagnostics(t))m.code===Tse&&typeof m.start=="number"&&s.set(m.start,e.flattenDiagnosticMessageText(m.messageText," "))}catch(m){if(U2(m))throw m}}return s},l=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=l(m);return h!==void 0&&e.isImportDeclaration(h)&&e.isStringLiteral(h.moduleSpecifier)&&h.moduleSpecifier.text===_o},d=m=>{var h;for(let g=m;g;g=g.parent)if(e.canHaveModifiers(g)&&((h=e.getModifiers(g))!==null&&h!==void 0?h:[]).some(y=>y.kind===e.SyntaxKind.DeclareKeyword))return!0;return!1},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=>u().get(m.getStart(t))}}function Dse(e,t,n,r,i){let o=[],a=n?.enums;if(!a||a.size===0)return o;let s=(c,d,f)=>{let p=t.getLineAndCharacterOfPosition(c.getStart(t));o.push({line:p.line+1,column:p.character+1,rule:d,code:0,message:f})},u=q2(e,t,hC(e,i)),l=c=>{let d,f;if(e.isPropertyAccessExpression(c)&&e.isIdentifier(c.expression))d=c.expression,f=c.name.text;else if(e.isElementAccessExpression(c)&&e.isIdentifier(c.expression)){let m=c.argumentExpression;e.isStringLiteral(m)||e.isNoSubstitutionTemplateLiteral(m)?(d=c.expression,f=m.text):e.isNumericLiteral(m)&&(d=c.expression,f=String(Number(m.text)))}let p=d&&a.has(d.text)&&r.has(F2(c))&&!u.pageOwns(d)?a.get(d.text):void 0;if(d&&p&&f!==void 0){let m=e.isPropertyAccessExpression(c)?`${p.name}.${f}`:`${p.name}[${JSON.stringify(f)}]`,h=Object.prototype.hasOwnProperty.call(p.runtime,f)?p.runtime[f]:void 0,g=p.labels.get(f),y;h===void 0?y={rule:"genpage-enum-member-unknown",message:`${m} is undefined at runtime: '${p.name}' has no member '${f}' in this environment's metadata \u2014 members are the column's choice labels, so a renamed or differently localized label no longer matches. Known: ${[...p.labels.keys()].map(E=>`'${E}'`).join(", ")}`}:g&&typeof h!="number"?y={rule:"genpage-enum-member-clobbered",message:`${m} is the string '${String(h)}' at runtime, not a choice value: the label '${f}' looks like a number, and another option's reverse mapping overwrites it. Use the choice's numeric value instead.`}:g&&g.length>1&&(y={rule:"genpage-enum-member-ambiguous",message:`${m} labels more than one choice (${g.join(", ")}); the compiled value is whichever option comes last. Use the choice's numeric value instead.`});let b=y?u.initializerShadow(d):void 0;y&&b!==void 0?s(c,"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 '${d.text}'. If you meant the constructor's '${d.text}', move the assignment into the constructor body, or make it a parameter property and read \`this.${d.text}\`. If you meant the choice enum, rename the constructor's parameter or local.`):y&&s(c,y.rule,y.message)}e.forEachChild(c,l)};return l(t),o}function Pse(e,t){return e.createSourceFile("page.js",t,e.ScriptTarget.ES2020,!1,e.ScriptKind.JS).statements.some(r=>(e.isImportDeclaration(r)||e.isExportDeclaration(r))&&r.moduleSpecifier!==void 0&&e.isStringLiteral(r.moduleSpecifier)&&r.moduleSpecifier.text===_o)}function B2(e,t){return t.statements.filter(n=>e.isImportDeclaration(n)&&e.isStringLiteral(n.moduleSpecifier)&&n.moduleSpecifier.text===_o).map(n=>n.getStart(t))}function Rse(e,t){let n=e.createSourceFile("page.js",t,e.ScriptTarget.ES2020,!0,e.ScriptKind.JS),r=B2(e,n),i=new Set(r),o,a="",s=0;for(let u of M2(t))!o&&!i.has(u.start)&&(o={swallows:r.some(l=>l>u.start&&l<u.end),text:t.slice(u.start,u.end).trimEnd()}),a+=t.slice(s,u.start),s=u.end;return a+=t.slice(s),{code:a,inexact:o}}function kse(e,t,n){let r=new Set(B2(e,t));for(let i=t.text.indexOf(n);i!==-1;i=t.text.indexOf(n,i+1))if(!r.has(i)){let o=t.getLineAndCharacterOfPosition(i);return{line:o.line+1,column:o.character+1}}return N0}function V2(e,t,n,r=He.GENPAGE_ITERATION_DEFAULT){if(!n||n.size===0)return[];let i=q2(e,t,{...hC(e,r),target:e.ScriptTarget.ESNext}),o=new Set,a=u=>{var l,c;let d=u.parent;if(e.isImportSpecifier(d)){let f=d.parent.parent.parent;e.isImportDeclaration(f)&&e.isStringLiteral(f.moduleSpecifier)&&f.moduleSpecifier.text===_o&&((l=d.propertyName)!==null&&l!==void 0?l:d.name)===u&&o.add(u.text);return}if(e.isExportSpecifier(d)){!(d.parent.parent.moduleSpecifier!==void 0)&&((c=d.propertyName)!==null&&c!==void 0?c:d.name)===u&&!i.pageOwnsLocalExport(d)&&o.add(u.text);return}e.isPropertyAccessExpression(d)&&d.name===u||e.isBindingElement(d)&&d.propertyName===u||e.isLabeledStatement(d)||e.isBreakOrContinueStatement(d)||i.pageOwns(u)||o.add(u.text)},s=u=>{e.isIdentifier(u)&&n.has(u.text)&&a(u),e.forEachChild(u,s)};return s(t),[...n.keys()].filter(u=>o.has(u))}He.legacyEnumsNeeded=V2;function $se(e,t,n){if(!e?.text||!t||n.length===0)return e;let r=new Map(e.enums),i=e.text;for(let o of n){let a=t.get(o);a&&(i+=a.declaration,r.set(o,a.model))}return{text:i,enums:r}}function Lse(e,t,n,r,i){try{return Mse(e,t,n,r,i)}catch(o){throw U2(o)?new au.SdkError("GENPAGE_COMPILE_DEPTH_EXCEEDED",Ise):o}}He.compileGenPage=Lse;function Mse(e,t,n,r,i){var o,a;let s=(o=i?.iteration)!==null&&o!==void 0?o:He.GENPAGE_ITERATION_DEFAULT,u=new Set,l=$2(e,t,s,u);if(l.diagnostics.length>0)return l;let c=e.createSourceFile("page.tsx",t,e.ScriptTarget.ES2020,!0,e.ScriptKind.TSX),d=e.createSourceFile("page.js",l.code,e.ScriptTarget.ES2020,!0,e.ScriptKind.JS),f=$se(n,r,V2(e,d,r,s)),p=[...Ose(e,d,c,f),...Dse(e,c,f,u,s)];if(!f?.text)return{code:l.code,diagnostics:p};let m=$2(e,f.text,s);if(m.diagnostics.length>0)throw new au.SdkError("GENPAGE_RUNTIME_TYPES_INVALID",`The generated runtime types do not compile (${m.diagnostics.map(b=>`${b.line}:${b.column} ${b.message}`).join("; ")}). This is an SDK defect: the page was not written.`);let h=Rse(e,l.code),g=h.code;if(p.length===0&&(!((a=h.inexact)===null||a===void 0)&&a.swallows))p.push({...mC(e,c).statement(_o,"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(p.length===0&&h.inexact){let{text:b}=h.inexact;p.push({...kse(e,c,b),rule:"genpage-runtime-types-import-form",code:0,message:`the maker portal's patch would delete \`${b.length>80?`${b.slice(0,79)}\u2026`:b}\` 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 p.length===0&&Pse(e,g)&&p.push({...mC(e,c).statement(_o,"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:[He.GENPAGE_RUNTIME_TYPES_BEGIN,m.code,He.GENPAGE_RUNTIME_TYPES_END,g].join(`-`),diagnostics:c}}ke.compileGenPage=Y5});var xg=v(ys=>{"use strict";Object.defineProperty(ys,"__esModule",{value:!0});ys.isFailureAfterPrimaryWrite=ys.failedAfterPrimaryWrite=void 0;var QN=Symbol.for("cds-maker-sdk.createFailedAfterPrimaryWrite");function Q5(e){return typeof e=="object"&&e!==null&&(e[QN]=!0),e}ys.failedAfterPrimaryWrite=Q5;function X5(e){return typeof e=="object"&&e!==null&&e[QN]===!0}ys.isFailureAfterPrimaryWrite=X5});var zd=v(Xn=>{"use strict";Object.defineProperty(Xn,"__esModule",{value:!0});Xn.appApi=Xn.deleteAppResolvingOnce=Xn.mainFormSetShapeIssues=Xn.unpublishedAppModulesQuery=void 0;var mo=Lt(),Z5=zg(),e8=bg(),XN=Qr(),t8=Fd(),r8=xg(),fe=ye(),Ce=le(),Mg=pt(),Ug=Kl(),de=Q(),n8=(0,Ce.odataQuery)([["$select","appmoduleid,name,uniquename,description,aiappdescription"]]),Bg="appmoduleid,name,uniquename,description,aiappdescription";function uu(e,t,r){return"/appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,Ce.odataQuery)([["$select",e],["$filter",t],["$top",r]])}Xn.unpublishedAppModulesQuery=uu;function qg(e,t){return uu(e,t?`appmoduleid eq ${t}`:void 0,t?1:void 0)}function Gd(e,t){return"/sitemaps/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,Ce.odataQuery)([["$select",t],["$filter",`sitemapid eq ${e}`],["$top",1]])}function su(e){var t;let r=(t=e.body)===null||t===void 0?void 0:t.value;if(Array.isArray(r))return r[0]}function i8(e){let t=e?.["@odata.etag"];return typeof t=="string"?t:null}function Wd(e,t){if(typeof e!="string")return!1;try{return(0,Ce.normalizeGuid)(e,"sitemapid")===t}catch{return!1}}function na(e){let t=new Set,r=[];for(let n of e??[])n&&!t.has(n)&&(t.add(n),r.push(n));return r}function o8(e){return`cdsapp_${(e||"").replace(/[^a-zA-Z0-9]/g,"")||"app"}`}async function a8(e,t){var r,n;let i=u=>{throw new de.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,Ce.odataQuery)([["$select","sitemapid"],["$filter",`sitemapnameunique eq '${(0,Ce.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 s8(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,Ce.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 ZN="627090ff-40a3-4053-8790-584edc5be201";function Dr(e){return e instanceof Error?e.message:String(e)}async function l8(e,t){var r;try{let n=`/roles${(0,Ce.odataQuery)([["$select","roleid,_parentrootroleid_value"],["$filter",`_roletemplateid_value eq ${ZN}`]])}`,i=await(0,mo.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 ${ZN}) 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,fe.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 (${Dr(n)}); it will not be visible or playable until a role is granted access to it.`}}async function u8(e,t,r=!0){let n=[];async function i(l,u,c){try{return(await(0,mo.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}' (${Dr(d)}); they were NOT added to the app.`),[]}}let[o,a,s]=await Promise.all([r?i(`/systemforms${(0,Ce.odataQuery)([["$select","formid"],["$filter",`objecttypecode eq '${(0,Ce.odataLiteral)(t)}' and type eq 2 and formactivationstate eq 1`]])}`,"formid","forms"):Promise.resolve([]),i(`/savedqueries${(0,Ce.odataQuery)([["$select","savedqueryid"],["$filter",`returnedtypecode eq '${(0,Ce.odataLiteral)(t)}' and querytype eq 0 and statecode eq 0`]])}`,"savedqueryid","views"),i(`/savedqueryvisualizations${(0,Ce.odataQuery)([["$select","savedqueryvisualizationid"],["$filter",`primaryentitytypecode eq '${(0,Ce.odataLiteral)(t)}'`]])}`,"savedqueryvisualizationid","charts")]);return{forms:o,views:a,charts:s,warnings:n}}var e_=new WeakMap;async function c8(e,t){let r=e_.get(e);r||(r=new Map,e_.set(e,r));let n=r.get(t);if(n!==void 0)return n;let i=await d8(e,t);return i&&r.set(t,i),i}async function t_(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 d8(e,t){let r=`/EntityDefinitions(LogicalName='${(0,Ce.odataPathLiteral)(t)}')${(0,Ce.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 r_(e,t,r){let n=[],i=na(t.entities),o=4,a=await t_(i,o,g=>c8(e,g)),s=i.filter((g,b)=>!a[b]);if(s.length>0)throw new de.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 na(t.components.forms))n.push({"@odata.type":"Microsoft.Dynamics.CRM.systemform",formid:g});for(let g of na(t.components.views))n.push({"@odata.type":"Microsoft.Dynamics.CRM.savedquery",savedqueryid:g});for(let g of na(t.components.charts))n.push({"@odata.type":"Microsoft.Dynamics.CRM.savedqueryvisualization",savedqueryvisualizationid:g});for(let g of na(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 t_(i,o,g=>u8(e,g,!f.has(g.toLowerCase()))),p=m.flatMap(g=>g.warnings),h=new Set([...na(t.components.forms),...na(t.components.dashboards)].map(at));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 at(e){let t=String(e).trim();return(t.startsWith("{")&&t.endsWith("}")?t.slice(1,-1):t).toLowerCase()}var bs=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,Vg="/components/mainFormsByTable",n_=50;function f_(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}function p_(e,t){if(e===void 0)return[];if(e===null||typeof e!="object"||Array.isArray(e))return[{pointer:Vg,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=`${Vg}/${f_(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"||!bs.test(at(c))?r.push({pointer:f,rule:"app-main-form-set-shape",message:`'${String(c)}' is not a form id`}):u.has(at(c))?r.push({pointer:f,rule:"app-main-form-set-shape",message:`form '${c}' is listed twice`}):u.add(at(c))})}return r}Xn.mainFormSetShapeIssues=p_;async function i_(e,t,r){let n=t.components.mainFormsByTable;if(n===void 0)return;let i=p_(n,t.entities);if(i.length>0)throw new de.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,mo.collectPages)(e,`/systemforms${(0,Ce.odataQuery)([["$select","formid,formactivationstate"],["$filter",`objecttypecode eq '${(0,Ce.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(at(h.formid)),Number(h.formactivationstate)===1&&m.add(at(h.formid)));let p=u.map(at);p.forEach((h,g)=>{let b=`${Vg}/${f_(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=at(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 de.ValidationError("app",r,o);return a}async function Wg(e,t){var r,n;let i=u=>({kind:"inconclusive",reason:u}),o=await e.get(uu("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"||!bs.test(at(l))?i(`no single current layer among ${a.length} app row(s)`):{kind:"read",unique:at(l)}}function qd(e,t){let r;return()=>r??(r=Wg(e,t))}var m_=62;function f8(e,t,r,n,i){let o=i.map(a=>`'${a}'`).join(", ");return t==="delete"?new de.SdkError("APP_SITEMAP_SHARED",`Refusing to delete app '${e}': its sitemap '${r.sitemapId}' is also the navigation of app ${o}. The delete removes an app's sitemap with it, and the platform does not stop that for a sitemap another app uses, so those apps would be left without navigation. Nothing was deleted. Remove the sitemap from the other app first, then retry.`):new de.SdkError("APP_SITEMAP_SHARED",`Refusing to ${t} app '${e}': it has no SiteMap component, and the sitemap named like it ('${n??""}', '${r.sitemapId}') is the navigation of app ${o}, so it is not this app's. Nothing was ${t==="fetch"?"saved":"modified"}.`)}async function lu(e,t,r,n,i=!1){var o;let a=c=>{throw new de.SdkError("APP_SITEMAP_UNRESOLVED",`Refusing to ${n} app '${t}': ${c}, so it cannot be determined which sitemap is this app's. Nothing was ${n==="fetch"?"saved":n==="delete"?"deleted":"modified"}. Retry.`)},s;try{s=await Wg(e,t)}catch(c){return a(`reading its current layer failed (${Dr(c)})`)}if(s.kind==="inconclusive")return a(`its current layer could not be read (${s.reason})`);let l;try{l=await(0,mo.collectPages)(e,`/appmodulecomponents${(0,Ce.odataQuery)([["$select","objectid"],["$filter",`_appmoduleidunique_value eq ${s.unique} and componenttype eq ${m_}`]])}`,`app SiteMap component ('${t}')`)}catch(c){return a(`reading its SiteMap component failed (${Dr(c)})`)}let u;if(l.length>1)return a(`its current layer carries ${l.length} SiteMap components, where an app can hold one`);if(l.length===1){let c=(o=l[0])===null||o===void 0?void 0:o.objectid;if(typeof c!="string"||!bs.test(at(c)))return a(`its SiteMap component carries an object id that is not a GUID ('${String(c)}')`);u={sitemapId:at(c),by:"component"}}else{let c=await a8(e,r);if(!c)return;let d;try{d=(0,Ce.normalizeGuid)(c,"sitemapId")}catch{return a(`the sitemap lookup by unique name returned a sitemapid that is not a GUID ('${String(c)}')`)}u={sitemapId:d,by:"name"}}if(i||u.by==="name"){let c=await p8(e,u.sitemapId,t,a);if(c.length>0)throw f8(t,n,u,r,c)}return u}async function p8(e,t,r,n){var i;let o;try{o=await(0,mo.collectPages)(e,`/appmodulecomponents${(0,Ce.odataQuery)([["$select","_appmoduleidunique_value"],["$filter",`componenttype eq ${m_} and objectid eq ${t}`]])}`,`apps using sitemap '${t}'`)}catch(u){return n(`reading which apps use sitemap '${t}' failed (${Dr(u)})`)}let a=new Set;for(let u of o){let c=u?._appmoduleidunique_value;if(typeof c!="string"||!bs.test(at(c)))return n(`a SiteMap component naming sitemap '${t}' carries no app layer id`);a.add(at(c))}let s=at(r),l=[];for(let u of a){let c;try{c=await e.get(uu("appmoduleid",`appmoduleidunique eq ${u}`))}catch(f){return n(`resolving app layer '${u}' failed (${Dr(f)})`)}if(c.status<200||c.status>=300)return n(`resolving app layer '${u}' returned HTTP ${c.status}`);let d=(i=c.body)===null||i===void 0?void 0:i.value;if(!Array.isArray(d))return n(`resolving app layer '${u}' returned a malformed body`);for(let f of d){let m=f?.appmoduleid;if(typeof m!="string"||!bs.test(at(m)))return n(`app layer '${u}' resolved to a row with no app id`);let p=at(m);if(p===s||l.includes(p))continue;let h;try{h=await Wg(e,p)}catch(g){return n(`reading the current layer of app '${p}' failed (${Dr(g)})`)}if(h.kind==="inconclusive")return n(`the current layer of app '${p}' could not be read (${h.reason})`);h.unique===u&&l.push(p)}}return l}async function h_(e,t,r,n=qd(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,mo.collectPages)(e,`/appmodulecomponents${(0,Ce.odataQuery)([["$select","objectid"],["$filter",`_appmoduleidunique_value eq ${at(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=>at(String(p.objectid)))}catch(m){return i(`reading its form components failed (${Dr(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=>!bs.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+=n_){let p=u.slice(m,m+n_);try{let h=await(0,mo.collectPages)(e,`/systemforms${(0,Ce.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=at(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 (${Dr(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 m8(e,t,r,n){let i=await h_(e,t,r,n);if(i.kind==="inconclusive")throw new de.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 de.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 h8(e,t,r,n){let i;try{i=await h_(e,t,r,n)}catch(a){i={kind:"inconclusive",reason:Dr(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 o_(e,t,r){if(r.length===0)return;let n="/AddAppComponents";(0,fe.ensureSuccess)(await e.post(n,{AppId:t,Components:r}),e.apiUrl(n))}async function a_(e,t,r,n=qd(e,t)){var i;if(r.length===0)return;let o=await n();if(o.kind==="inconclusive")throw new de.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,Ce.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 de.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 de.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 de.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 g8(e,t,r){let n=`/appmodules(${t})`,i=`/sitemaps(${r.sitemapId})`,o;try{o=await b8(e,r.sitemapId,r.sitemapNameUnique)}catch(l){return{outcome:"kept",reason:`whether its sitemap row exists could not be determined (${Dr(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 (${Dr(l.error)})`,...l.lock?{lock:!0}:{}}:{outcome:"unconfirmed",foreignSitemap:a,reason:`its delete was sent but its outcome is unknown (${Dr(l.error)})`,...l.lock?{lock:!0}:{}};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,fe.resendAppSearchIndexRace)(()=>e.delete(n));if(l.status===404)return s({kind:"deleted"});let u=Gg(l,e.apiUrl(n));return s(u.kind!=="deleted"&&(0,fe.isConcurrencyLockRefusal)(l)?{...u,lock:!0}:u)}return e.supportsAtomicBatch?r.sitemapWriteToken?s(await y_(e,[{path:n},{path:i,etag:r.sitemapWriteToken}],{reportLock:!0})):{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 y8(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}')`}.`,s="Once the lock frees \u2014 another customization operation holds it \u2014 check that the rows exist and are this create's own before removing them.";return t.lock&&t.outcome==="kept"?e.message+=` The partial app this create wrote was KEPT \u2014 its rollback deleted nothing, because the environment's customization lock refused it (another customization operation was running): ${i}. ${s} While it exists, ${a}`:t.lock?e.message+=` Whether the partial app this create wrote was removed could not be confirmed, because the environment's customization lock refused or interrupted its rollback, so it may not have run. Check for ${i}. ${s} While any of it exists, ${a}`: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 b8(e,t,r){var n,i,o;let a=Gd(t,"sitemapid,sitemapnameunique"),s=await e.get(a);if(s.status<200||s.status>=300)throw new de.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 de.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 v8(e,t){var r;let n;try{n=await e.get(uu("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!Wd(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 g_(e,t){var r;let n=(0,Ce.normalizeGuid)(t,"id"),i=w=>{throw new de.SdkError("APP_SITEMAP_UNRESOLVED",`Refusing to delete app '${n}': ${w} Deleting the app would destroy the only pointer to its sitemap, stranding that row and reserving its unique name forever. Retry.`)},o=`/appmodules(${n})${n8}`,a;try{a=await e.get(o)}catch(w){return i(`reading the app failed (${w.message}).`)}let s,l=!1;if(a.status===404){let w=await v8(e,n);if(w.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; ${w.why}.`);s=w.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,fe.readEtag)(a)},c=await lu(e,n,s,"delete");if(!c)return{uniquename:s,...u};let d=c.sitemapId,f=await Vd(e,d),m=Gd(d,"sitemapid,sitemapnameunique,sitemapxml"),p;try{p=await e.get(m)}catch(w){return i(`reading sitemap '${d}' failed (${w.message}).`)}if(p.status<200||p.status>=300)return i(`reading sitemap '${d}' returned HTTP ${p.status}.`);let h=su(p);if(!h)return i(`sitemap '${d}' was not returned by the unpublished-aware read.`);if(c.by==="name"&&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(!Wd(h.sitemapid,d))return i(`sitemap '${d}' was read back as a row carrying sitemapid '${String(h.sitemapid)}'.`);let g=h.sitemapxml;if(typeof g!="string")return i(`sitemap '${d}' returned no sitemapxml.`);let b=await lu(e,n,s,"delete",!0);return b?.sitemapId!==d||b.by!==c.by?i(`its sitemap link changed while it was read (sitemap '${d}' by ${c.by}, then ${b?`'${b.sitemapId}' by ${b.by}`:"none"}).`):{sitemapId:d,uniquename:s,sitemapXml:g,...u,sitemapEtag:f}}async function w8(e,t,r){let n=(0,Ce.normalizeGuid)(t,"id"),i=await g_(e,n);await r?.(i.sitemapXml),await v_(e,n,i)}Xn.deleteAppResolvingOnce=w8;async function C8(e,t){let r=await y_(e,t);if(r.kind!=="deleted")throw r.error}function Gg(e,t){try{return(0,fe.ensureSuccess)(e,t),{kind:"deleted"}}catch(r){return b_(e.status)?{kind:"refused",error:r}:{kind:"unknown",error:r}}}function E8(e,t){var r;if(e.status!==400&&(e.status<200||e.status>=300))return!1;let n=(r=(0,Ug.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,fe.namesAppSearchIndexRace)(i.text))}async function y_(e,t,r={}){let n=`batch_${(0,Mg.newId)()}`,i=`changeset_${(0,Mg.newId)()}`,o=t.map((p,h)=>[`--${i}`,"Content-Type: application/http","Content-Transfer-Encoding: binary",`Content-ID: ${h+1}`,"",`DELETE ${e.apiUrl(p.path)} HTTP/1.1`,...p.etag?[`If-Match: ${p.etag}`]:[],""].join(`\r-`)),a=[`--${n}`,`Content-Type: multipart/mixed;boundary=${i}`,"",...o,`--${i}--`,`--${n}--`,""].join(`\r-`),s=e.apiUrl("/$batch"),l=o.map((p,h)=>String(h+1)),u;try{u=await(0,fe.resendWhile)(p=>E8(p,l),()=>e.postBatch(a,n),fe.DEADLOCK_BACKOFF_MS)}catch(p){return{kind:"unknown",error:p}}if(r.reportLock){if((0,Ug.isChangeSetLockRefusal)(u,l))return{kind:"refused",lock:!0,error:new de.ConnectionError(s,u.status,`atomic delete of app '${t[0].path}' was refused whole by the customization lock, so it deleted nothing`)};if((0,fe.isConcurrencyLockRefusal)(u)){let p=Gg(u,s);return p.kind==="deleted"?p:{...p,lock:!0}}}let c=Gg(u,s);if(c.kind!=="deleted")return c;let d=`app '${t[0].path}'`;if(typeof u.body!="string"||u.body.length===0)return{kind:"unknown",error:new de.ConnectionError(s,u.status,`atomic delete of ${d} cannot be confirmed: the $batch response had no readable body, so the change set's outcome is unknown`)};let f=(0,Ug.parseChangeSetStatuses)(u.body,l);if(f===void 0)return{kind:"unknown",error:new de.ConnectionError(s,u.status,`atomic delete of ${d} cannot be confirmed: the $batch response could not be parsed as a change set, so the outcome is unknown`)};let m=f.find(p=>p<200||p>=300);return m!==void 0?{kind:"refused",error:new de.ConnectionError(s,m,`atomic delete of ${d} was rolled back: the change set reported HTTP ${m}`)}:f.length!==o.length?{kind:"unknown",error:new de.ConnectionError(s,u.status,`atomic delete of ${d} cannot be confirmed: the $batch response reported ${f.length} operation result(s), expected exactly ${o.length}`)}:{kind:"deleted"}}async function Vd(e,t){try{let r=await e.get(`/sitemaps(${t})?$select=sitemapid`);return r.status<200||r.status>=300?null:(0,fe.readEtag)(r)}catch{return null}}async function s_(e,t){let r=`/appmodules(${t})?$select=appmoduleid`,n=await e.get(r);if(n.status!==404)return(0,fe.ensureSuccess)(n,e.apiUrl(r)),(0,fe.readEtag)(n)}function l_(e){return{sitemapxml:e.sitemapxml,...e.sitemapname!==void 0?{sitemapname:e.sitemapname}:{}}}async function Fg(e,t,r,n){if(!n)return null;let i=await Vd(e,t);if(!i)return null;try{let o=await e.get(Gd(t,"sitemapid,sitemapname,sitemapnameunique,sitemapxml"));if(o.status<200||o.status>=300)return null;let a=su(o);return!a||!Wd(a.sitemapid,t)||a.sitemapnameunique!==n||a.sitemapxml!==r.sitemapxml||r.sitemapname!==void 0&&a.sitemapname!==r.sitemapname?null:i}catch{return null}}function b_(e){return e>=400&&e<500&&e!==408&&e!==429}function u_(e,t,r){if(!e)throw new de.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 v_(e,t,r){let n=`/appmodules(${t})`,i=r.draft?void 0:u_(r.appEtag,t,"app");if(!r.sitemapId){if(r.draft){(0,fe.ensureSuccess)(await(0,fe.resendAppSearchIndexRace)(()=>e.delete(n)),e.apiUrl(n));return}await A8(e,n,i);return}if(!e.supportsAtomicBatch)throw new de.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 C8(e,[{path:n,etag:i},{path:`/sitemaps(${r.sitemapId})`,etag:u_(r.sitemapEtag,t,"sitemap")}])}async function A8(e,t,r){(0,fe.ensureSuccess)(await(0,fe.resendAppSearchIndexRace)(()=>e.delete(t,{headers:{"If-Match":r}})),e.apiUrl(t))}async function c_(e,t){if(!/GenPageId/i.test(t))return;let r;try{r=[...new Set((0,Z5.collectGenPageIds)(t))]}catch(i){throw new de.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 (${Dr(i)}).`)}if(r.length===0)return;let n=await(0,e8.findMissingGenPages)(e,r,"sitemap generative-page preflight");if(n.length>0)throw new de.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 S8(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")}function N8(e,t){var r;let n=[["name",e.appModuleName],["description",e.appModuleDescription],["aiappdescription",e.appModuleAiDescription]],i={};for(let[o,a]of n)a!==void 0&&(t!==void 0&&String((r=t[o])!==null&&r!==void 0?r:"")===String(a??"")||(i[o]=a));return i}async function d_(e,t,r){var n;let i=(0,Ce.normalizeGuid)(t,"id"),o=r==="tokens-first",a=o?await s_(e,i):null,s=qg(Bg,i),l=(0,fe.ensureSuccess)(await e.get(s),e.apiUrl(s)),u=(n=su(l))!==null&&n!==void 0?n:{};if(!u.appmoduleid)throw new de.SdkError("APP_NOT_FOUND",`App '${i}' was not found (checked the unpublished-aware projection, which includes drafts).`);let c=await lu(e,i,u.uniquename,"fetch"),d=c?.sitemapId,f=null;if(c&&d){o&&(f=await Vd(e,d));let p=Gd(d,"sitemapid,sitemapname,sitemapnameunique,sitemapxml"),h=(0,fe.ensureSuccess)(await e.get(p),e.apiUrl(p)),g=su(h),b=C=>{throw new de.SdkError("APP_SITEMAP_UNRESOLVED",`Refusing to fetch app '${i}': its sitemap '${d}' was located by its ${c.by==="component"?"SiteMap component":"unique name"}, but ${C}, 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(c.by==="name"&&g.sitemapnameunique!==u.uniquename)throw new de.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(!Wd(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");let w=await lu(e,i,u.uniquename,"fetch");if(w?.sitemapId!==d||w.by!==c.by)throw new de.SdkError("APP_SITEMAP_UNRESOLVED",`Refusing to fetch app '${i}': its sitemap link changed while it was read (sitemap '${d}' by ${c.by}, then ${w?`'${w.sitemapId}' by ${w.by}`:"none"}). Nothing was saved. Retry.`);u.$sitemap=g,o||(f=await Vd(e,d))}o||(a=await s_(e,i));let m=a??i8(u);return{raw:u,etag:f,...u.appmoduleid?{siblingEtags:{[(0,Ce.normalizeGuid)(u.appmoduleid,"appmoduleid")]:m}}:{}}}Xn.appApi={get(e,t){return d_(e,t,"tokens-first")},readContentThenToken(e,t){return d_(e,t,"content-first")},async list(e,t){let r=qg(Bg);return(await(0,mo.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;if(typeof n.appModuleName!="string"||n.appModuleName.trim()==="")throw new de.ValidationError("app",n.appModuleId,[{pointer:"/name",rule:"app-name-required",message:"an app needs a name to be created, and its 'name' is missing or blank \u2014 set it (updateElement('app', id, '/name', \u2026), or addElement when the key was removed) and push again. Nothing was written."}]);await c_(e,n.sitemapxml);let i=await i_(e,n,n.appModuleId),o=n.iconWebResourceId?void 0:await s8(e),a=n.iconWebResourceId||o?.id;if(!a)throw new de.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||o8(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,fe.ensureSuccess)(await(0,fe.resendDeadlockVictim)(()=>e.post(c,(0,fe.withClientMintedId)(u,"appmoduleid",r))),e.apiUrl(c)),f=(0,fe.resolveCreatedId)(d,"appmoduleid","app module",r),m=null,p=null,h=[];s&&h.push(s);let g={kind:"notRequested"},b=n.sitemapId?(0,Ce.normalizeGuid)(n.sitemapId,"sitemapId"):(0,Mg.newId)(),w=!1,C=l_(n);try{let O="/sitemaps",k=(0,fe.echoWrite)("sitemapid"),I=await e.post(`${O}${k.query}`,{sitemapid:b,sitemapnameunique:l,...C},k.options);w=b_(I.status);let D=(0,fe.ensureSuccess)(I,e.apiUrl(O));p=(0,fe.readEtag)(D),m=p??await Fg(e,b,C,l);let P=await r_(e,n,i);h.push(...P.warnings);let x=P.components;x.unshift({"@odata.type":"Microsoft.Dynamics.CRM.sitemap",sitemapid:b}),await o_(e,f,x);let K=qd(e,f);await a_(e,f,P.tables,K),i&&await m8(e,f,i,K);let Oe=await l8(e,f);Oe&&h.push(Oe),n.appSettings&&Object.keys(n.appSettings).length>0&&h.push(...await(0,t8.applyAppSettings)(e,f,n.appSettings)),n.published!==!1&&(await(0,XN.publishAppModule)(e,f),g={kind:"submitted"})}catch(O){let k=await g8(e,f,{sitemapId:b,sitemapNameUnique:l,serverRefusedSitemap:w,sitemapWriteToken:p});throw(0,r8.failedAfterPrimaryWrite)(y8(O,k,{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,fe.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;let u=r,c=(0,Ce.normalizeGuid)(t,"id");if(await c_(e,u.sitemapxml),!u.sitemapId)throw new de.ValidationError("app",c,[{pointer:"/sitemapId",rule:"app-sitemap-identity-missing",message:`missing sitemap identity \u2014 re-fetch the app before pushing edits: fetchArtifact('app', '${c}', { 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', '${c}'), clear the local copy with deleteArtifact('app', '${c}'), then author the app again and push.`}]);let d=(0,Ce.normalizeGuid)(u.sitemapId,"sitemapId");if(!(0,fe.isVersionToken)(n))throw new de.SdkError("APP_UPDATE_NO_ETAG",`Refusing to push app '${c}': ${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 f=await i_(e,u,c),m=await r_(e,u,f),p=`/appmodules(${c})`,h=(a=o?.[c])!==null&&a!==void 0?a:null,g,b;try{let Ne=qg(Bg,c),se=await e.get(Ne);if(se.status>=200&&se.status<300){let We=su(se);if(typeof We=="object"&&We!==null&&!Array.isArray(We)){g=We;let ir=g.uniquename;b=typeof ir=="string"&&ir?ir:void 0}}}catch{}let w=N8(u,g),C=await lu(e,c,b||u.appModuleUniqueName,"push");if(C?.sitemapId!==d)throw new de.SdkError("APP_SITEMAP_UNRESOLVED",`Refusing to push app '${c}': ${C?`its sitemap is now '${C.sitemapId}'`:"it has no sitemap now"}, not '${d}', the one this copy holds \u2014 the app's sitemap is no longer the one this copy was fetched with. Nothing was modified. Re-fetch the app (fetchArtifact('app', '${c}', { overwrite: true })) and re-apply the change.`);let S=h;if(Object.keys(w).length>0){if(!(0,fe.isVersionToken)(h))throw new de.SdkError("APP_UPDATE_NO_ETAG",`Refusing to push app '${c}': ${h?`the concurrency token held for its appmodule header ('${h}') 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', '${c}', { overwrite: true })) and re-apply the change.`);let Ne=(0,fe.echoWrite)("appmoduleid",{"If-Match":h}),se=await e.patch(`${p}${Ne.query}`,w,Ne.options);if(S8(se))throw new de.SdkError("APP_DRAFT_HEADER_NOT_WRITABLE",`Refusing to update app '${c}': 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,fe.ensureSuccess)(se,e.apiUrl(p)),S=(0,fe.readEtag)(se)}let O=l_(u),k=u.sitemapNameUnique||b||u.appModuleUniqueName||void 0,I=(0,fe.echoWrite)("sitemapid",{"If-Match":n}),D=`/sitemaps(${d})`,P;try{P=(0,fe.ensureSuccess)(await e.patch(`${D}${I.query}`,{...O},I.options),e.apiUrl(D))}catch(Ne){throw(0,de.withPartialTokens)(Ne,{siblingEtags:{[c]:S}})}let x=[...m.warnings],K=qd(e,c);try{await o_(e,c,m.components),await a_(e,c,m.tables,K)}catch(Ne){x.push(`App '${c}': one or more components were not pinned (${Ne.message}). Navigation may reference content not included in the app; re-push to retry.`)}f&&x.push(...await h8(e,c,f,K));let Oe={kind:"notRequested"},Vt=S,Xe=(s=(0,fe.readEtag)(P))!==null&&s!==void 0?s:await Fg(e,d,O,k);if(u.published===!0){try{await(0,XN.publishAppModule)(e,c),Oe={kind:"submitted"}}catch(Ne){Oe={kind:"failed",error:Ne},x.push(`App '${c}': saved, but publishing failed (${Ne.message}). The app remains unpublished; re-push to retry.`)}if(Oe.kind==="submitted"){Vt=null;try{let Ne=await e.get(`/appmodules(${c})?$select=appmoduleid`);Ne.status>=200&&Ne.status<300&&(Vt=(0,fe.readEtag)(Ne)),Xe=(l=await Fg(e,d,O,k))!==null&&l!==void 0?l:Xe}catch{}}}return{id:c,etag:Xe,siblingEtags:{[c]:Vt},publish:Oe,...x.length>0?{warnings:x}:{}}},async delete(e,t){let r=(0,Ce.normalizeGuid)(t,"id");await v_(e,r,await g_(e,r))}}});var zg=v(vs=>{"use strict";Object.defineProperty(vs,"__esModule",{value:!0});vs.deleteAppCascade=vs.collectGenPageIds=void 0;var _8=zd(),T8=Q(),jg=le(),D8=ns();function w_(e){let t=[],r=s=>l=>t.push(`${s}: ${l}`),n=new D8.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 T8.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,jg.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}vs.collectGenPageIds=w_;async function I8(e,t,r){let n=(0,jg.normalizeGuid)(t,"appModuleId");(0,jg.normalizeGuid)(r,"appModuleIdUnique");let i=[],o=[],a=[];await(0,_8.deleteAppResolvingOnce)(e,n,l=>{l!==void 0&&a.push(...w_(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}}vs.deleteAppCascade=I8});var C_={};Jr(C_,{Guid:()=>U});var U,ht=L(()=>{"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,Xt=L(()=>{"use strict";st();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 E_={};Jr(E_,{ScriptUtilities:()=>R});var R,st=L(()=>{"use strict";ht();Xt();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 jd,Hd,ia,Kd,Hg,Jd,Kg=L(()=>{"use strict";(function(e){e[e.FormElementNodeChange=0]="FormElementNodeChange",e[e.FormElementAttributeChange=1]="FormElementAttributeChange"})(jd||(jd={}));Hd=class{type;targetNode;constructor(t,r){this.type=t,this.targetNode=r}},ia=class extends Hd{key;oldValue;newValue;constructor(t,r,n,i){super(jd.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)}},Kd=class extends Hd{property;oldValue;newValue;constructor(t,r,n,i){super(jd.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)}},Hg=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()})}},Jd=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 Hg(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 A_={};Jr(A_,{ChartGridMode:()=>ln,ColumnLayoutWidths:()=>L8,ComponentCategory:()=>Qd,ComponentType:()=>Jg,ControlLayoutTypes:()=>r0,DisplayConditionsInfo:()=>R8,ElementNames:()=>E,ElementProperties:()=>y,ElementType:()=>Qg,EntityAttributeProperty:()=>Xg,EventType:()=>cu,FormActivationState:()=>t0,FormCanvasServiceScope:()=>j8,FormDesignerSideBarTab:()=>Yg,FormPresentation:()=>Zg,FormState:()=>Yd,FormType:()=>gt,HeaderDensityType:()=>ho,LookUpTable:()=>Zn,MORE_TAB_PREFIX:()=>x8,NavBarChildElementType:()=>e0,PREVIEW_ID_HEADER_FLYOUT:()=>B8,PREVIEW_ID_HEADER_OVERFLOW_BUTTON:()=>V8,PREVIEW_ID_NAVIGATION_AREA:()=>M8,PREVIEW_ID_QUICKCREATE_ROOT:()=>W8,PREVIEW_ID_TAB:()=>G8,PREVIEW_ID_TAB_LIST:()=>q8,PREVIEW_ID_TAB_PANEL:()=>U8,PropertyModelKeys:()=>o0,PropertyModelSectionKeys:()=>$8,RELATED_TAB_ID:()=>a0,RELATED_TAB_PREFIX:()=>F8,SectionDefaultProperties:()=>k8,SectionLayoutTypes:()=>je,TabContentType:()=>n0,TabDefaultProperties:()=>go,TabLayoutTypes:()=>ze,TelemetryPropertyNames:()=>z8,UnboundControlPropertyKeys:()=>i0,compositeAddressFields:()=>P8,compositeFieldNames:()=>zr,compositeFields:()=>O8});var gt,Jg,Yg,E,y,Qg,zr,O8,P8,Xg,Zn,Yd,ho,Zg,R8,e0,t0,ze,k8,go,je,r0,n0,L8,i0,o0,$8,cu,ln,a0,x8,F8,M8,U8,B8,q8,V8,G8,W8,z8,Qd,j8,ue=L(()=>{"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"})(gt||(gt={}));(function(e){e[e.Form=0]="Form",e[e.Dialog=1]="Dialog"})(Jg||(Jg={}));(function(e){e[e.Components=0]="Components",e[e.Properties=1]="Properties",e[e.Relationship=2]="Relationship",e[e.BusinessRules=3]="BusinessRules"})(Yg||(Yg={}));(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"})(Qg||(Qg={}));zr={fullname:"fullname",yomifullname:"yomifullname",address1_composite:"address1_composite",address2_composite:"address2_composite",address3_composite:"address3_composite",billto:"billto_composite",shipto:"shipto_composite"},O8=[zr.fullname,zr.yomifullname,zr.address1_composite,zr.address2_composite,zr.address3_composite,zr.billto,zr.shipto],P8=[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"})(Xg||(Xg={}));(function(e){e[e.DependencyFieldTable=0]="DependencyFieldTable",e[e.LockedFieldTable=1]="LockedFieldTable"})(Zn||(Zn={}));(function(e){e[e.Published=0]="Published",e[e.Draft=1]="Draft",e[e.New=2]="New",e[e.SaveAs=3]="SaveAs"})(Yd||(Yd={}));(function(e){e.Low="Low",e.HighReadOnlyValues="HighReadOnlyValues",e.HighWithControls="HighWithControls"})(ho||(ho={}));(function(e){e[e.ClassicForm=0]="ClassicForm",e[e.AirForm=1]="AirForm",e[e.ConvertedICForm=2]="ConvertedICForm"})(Zg||(Zg={}));R8={TopOrderFormId:"topOrderFormId",NextDisplayOrder:"nextDisplayOrder"};(function(e){e[e.NavBarRelationShipItem=0]="NavBarRelationShipItem",e[e.NavBarItem=1]="NavBarItem"})(e0||(e0={}));(function(e){e[e.InActive=0]="InActive",e[e.Active=1]="Active"})(t0||(t0={}));(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={}));k8={ShowLabel:"false",LockLevel:"0",IsUserDefined:"0",LabelWidth:"115",columns:"1",ShowBar:"false",Layout:"varwidth",namePrefix:"_section_"},go={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"})(r0||(r0={}));(function(e){e.cardSections="cardSections",e.singleComponent="singleComponent",e.default="default",e.expandAvailableSpace="expandAvailableSpace"})(n0||(n0={}));L8={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"})(i0||(i0={}));(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"})(o0||(o0={}));$8={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"})(cu||(cu={}));(function(e){e.All="All",e.Chart="Chart",e.Grid="Grid"})(ln||(ln={}));a0="tab_related3b554255-7717-4d17-bb7f-9936fb1e75ca",x8="more_tab_",F8="related_tab_",M8="preview_id_navigation_area",U8="tab-section",B8="headerFieldsFlyout",q8="tablist",V8="header_overflowButton",G8="tab",W8="quickCreateRoot",z8={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"})(Qd||(Qd={}));j8="CellCanvasServiceScope"});var S_={};Jr(S_,{Attribute:()=>Xd,FormElementNode:()=>re});var Xd,re,It=L(()=>{"use strict";st();Xt();Kg();ue();ht();Xd=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 Xd(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 ia(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 ia(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 ia(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 Kd(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 ia(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 N_={};Jr(N_,{ControlClassId:()=>N,ControlNamePrefixes:()=>Zd,getControlDisplayNames:()=>H8});function H8(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,oa=L(()=>{"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 aa=v((Ble,T_)=>{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{}}}),__=function(){return du};Object.setPrototypeOf(__,du);T_.exports=__});var cr,Ri,D_,I_,ws=L(()=>{"use strict";cr="cds-designer-models",Ri="FormCustomControl",D_="FormCell",I_="Form"});var sa,s0=L(()=>{"use strict";Wl();ue();sa=class e{static lockedFieldCount=new ar;static dependencyFieldCount=new ar;static getNecessaryLookUpTable(t){switch(t){case Zn.DependencyFieldTable:return e.dependencyFieldCount;case Zn.LockedFieldTable:return e.lockedFieldCount}}static initCanvasLockedFieldLookUp(t){switch(t){case Zn.DependencyFieldTable:e.dependencyFieldCount=new ar;case Zn.LockedFieldTable:e.lockedFieldCount=new ar}}}});var ef,O_=L(()=>{"use strict";ht();st();ue();It();ef=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 ki(){return ei||(ei=window._makerConfig,ei&&window?.location?.search?.indexOf("useProductionConfig")>-1&&(ei={...ei,region:"prod",graphQLEndpoint:"https://graph.make.powerapps.com/"}),ei?.region==="prod"&&(ei={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/"}}},...ei}),ei||{aadClientId:"a8f7a65c-f5ba-4859-b2d6-df772c264e9d",location:"cus",region:"test",publicPath:"/",graphQLEndpoint:"https://graph.make.test.powerapps.com/"})}var ei,tf=L(()=>{"use strict";});function P_(e,t,r){if(!e)return rf.has(e)||(window._ppux?.log?.("PPUX/Geo/NonExistent",{eventType:"Trace",team:"Shell",severity:"Error",errorCode:"GeoIsEmpty"}),rf.add("")),!1;if(e){if(e=e.toLowerCase(),rf.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}}),rf.add(e),!1}return!0}function K8(e){return P_(e,l0,"Location dictionary")?l0[e.toLowerCase()]:"us"}function J8(){let e=ki().location.toLowerCase();return P_(e,l0,"Current location dictionary")?e:"us"}var rf,l0,Zle,R_=L(()=>{"use strict";tf();rf=new Set,l0={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"};Zle=K8(J8())});var Y,tue,k_=L(()=>{"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"},tue={[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 L_=L(()=>{"use strict";tf();});var fu=L(()=>{"use strict";tf();R_();k_();L_();});function pu(e,t){return $_?$_.isOverridden(e,t):{overridden:!1}}var $_,mu=L(()=>{"use strict";});var u0=L(()=>{"use strict";fu();mu();});function Y8(e,t){let{region:r}=ki();return()=>{let n=e.settings[t];if(n.allowOverrides){let s=pu(e.packageName,t);if(s.overridden)return typeof s.value=="string"?Q8(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 Q8(e){return isNaN(Number(e))?e==="true"?!0:e==="false"?!1:e:Number(e)}function X8(e){let t=e.packageName;if(nf.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=>d0(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=>!af(i))){let i=`error parsing settings config for package ${t}, setting ${r} has invalid region`;throw console.error(i),new Error(i)}})}function hu(e){X8(e);let t={};return Object.keys(e.settings).forEach(r=>{t[r]={enumerable:!0,get:Y8(e,r)}}),nf.set(e.packageName,e),Object.defineProperties({},t)}function c0(e,t){return nf.has(e)?!!nf.get(e).settings[t]:!1}var nf,of=L(()=>{"use strict";fu();mu();f0();gu();nf=new Map});function x_(e,t){let{region:r}=ki();return()=>{let n=pu(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 Z8(e){let t=e.packageName;if(sf.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=>c0(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=>!af(i))){let i=`error parsing feature gates config for package ${t}, feature ${r} has invalid region`;throw console.error(i),new Error(i)}})}function p0(e){Z8(e);let t={};Object.keys(e.features).forEach(i=>{t[i]={enumerable:!0,configurable:!0,get:x_(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:x_(e,o.toString())}}),Object.defineProperties(r,i),n.clear()}},sf.set(e.packageName,e),Object.defineProperties(r,t)}function d0(e,t){return sf.has(e)?!!sf.get(e).features[t]:!1}var sf,f0=L(()=>{"use strict";fu();gu();mu();of();sf=new Map});var M_=v((_ue,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 q_=v(m0=>{"use strict";var e6=Object.prototype.hasOwnProperty,t6;function U_(e){try{return decodeURIComponent(e.replace(/\+/g," "))}catch{return null}}function B_(e){try{return encodeURIComponent(e)}catch{return null}}function r6(e){for(var t=/([^=?#&]+)=?([^&]*)/g,r={},n;n=t.exec(e);){var i=U_(n[1]),o=U_(n[2]);i===null||o===null||i in r||(r[i]=o)}return r}function n6(e,t){t=t||"";var r=[],n,i;typeof t!="string"&&(t="?");for(i in e)if(e6.call(e,i)){if(n=e[i],!n&&(n===null||n===t6||isNaN(n))&&(n=""),i=B_(i),n=B_(n),i===null||n===null)continue;r.push(i+"="+n)}return r.length?t+r.join("&"):""}m0.stringify=n6;m0.parse=r6});var y0=v((Due,H_)=>{"use strict";var G_=M_(),lf=q_(),W_=/[\n\r\t]/g,i6=/^[A-Za-z][A-Za-z0-9+-.]*:\/\//,o6=/^([a-z][a-z0-9.+-]*:)?(\/\/)?([\\/]+)?([\S\s]*)/i,a6=/^[a-zA-Z]:/,s6=/^[\x00-\x20\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]+/;function g0(e){return(e||"").toString().replace(s6,"")}var h0=[["#","hash"],["?","query"],function(t,r){return ti(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]],V_={hash:1,query:1};function z_(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 ri(unescape(e.pathname),{});else if(i==="string"){n=new ri(e,{});for(o in V_)delete n[o]}else if(i==="object"){for(o in e)o in V_||(n[o]=e[o]);n.slashes===void 0&&(n.slashes=i6.test(e.href))}return n}function ti(e){return e==="file:"||e==="ftp:"||e==="http:"||e==="https:"||e==="ws:"||e==="wss:"}function j_(e,t){e=g0(e),e=e.replace(W_,""),t=t||{};var r=o6.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)):ti(n)?s=r[4]:n?i&&(s=s.slice(2)):a>=2&&ti(t.protocol)&&(s=r[4]),{protocol:n,slashes:i||ti(n),slashesCount:a,rest:s}}function l6(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 ri(e,t,r){if(e=g0(e),e=e.replace(W_,""),!(this instanceof ri))return new ri(e,t,r);var n,i,o,a,s,l,u=h0.slice(),c=typeof t,d=this,f=0;for(c!=="object"&&c!=="string"&&(r=t,t=null),r&&typeof r!="function"&&(r=lf.parse),t=z_(t),i=j_(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||a6.test(e))||!i.slashes&&(i.protocol||i.slashesCount<2||!ti(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=l6(d.pathname,t.pathname)),d.pathname.charAt(0)!=="/"&&ti(d.protocol)&&(d.pathname="/"+d.pathname),G_(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:"&&ti(d.protocol)&&d.host?d.protocol+"//"+d.host:"null",d.href=d.toString()}function u6(e,t,r){var n=this;switch(e){case"query":typeof t=="string"&&t.length&&(t=(r||lf.parse)(t)),n[e]=t;break;case"port":n[e]=t,G_(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<h0.length;a++){var s=h0[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:"&&ti(n.protocol)&&n.host?n.protocol+"//"+n.host:"null",n.href=n.toString(),n}function c6(e){(!e||typeof e!="function")&&(e=lf.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||ti(r.protocol)?"//":"");return r.username?(o+=r.username,r.password&&(o+=":"+r.password),o+="@"):r.password?(o+=":"+r.password,o+="@"):r.protocol!=="file:"&&ti(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}ri.prototype={set:u6,toString:c6};ri.extractProtocol=j_;ri.location=z_;ri.trimLeft=g0;ri.qs=lf;H_.exports=ri});var d6,K_=L(()=>{"use strict";d6=Ae(y0());});function b0(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 uf=L(()=>{"use strict";});var v0,w0,C0=L(()=>{"use strict";uf();v0=class{features=new Map;register(t,r){let n=b0(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()}},w0=new v0});var E0=L(()=>{"use strict";});function af(e){return f6.has(e)}var f6,gu=L(()=>{"use strict";u0();f0();of();mu();u0();K_();C0();uf();E0();f6=new Set(["tie","test","prod","preview","preprod","gov","high","dod","mooncake","ex","rx"])});var p6,J_=L(()=>{"use strict";gu();p6=hu({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 Z_,S0,Cs,la,A0,cf,Es,Li,Ue,Y_,Q_,X_,Tn=L(()=>{"use strict";Z_={ThreeEqColumn_FirstColumn:34,ThreeEqColumn_SecondColumn:33,ThreeEqColumn_ThirdColumn:33,FiveEqColumn:20},S0={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"})(Cs||(Cs={}));(function(e){e.Left="Left",e.Right="Right",e.Center="Center"})(la||(la={}));(function(e){e[e.Mobile=0]="Mobile",e[e.Tablet=1]="Tablet",e[e.Web=2]="Web"})(A0||(A0={}));cf=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"})(Es||(Es={}));Li=class{static StartTag="<"},Ue={ShowLabel:"true",LockLevel:"0",IsUserDefined:"0",LabelWidth:"115",columns:"1",ShowBar:"false",Layout:"varwidth",namePrefix:"_section_",labelAlignment:la.Left,labelPosition:Es.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"})(Y_||(Y_={}));(function(e){e.TabWithLockedFieldRemoval="TabWithLockedFieldRemoval",e.SectionWithLockedFieldRemoval="SectionWithLockedFieldRemoval",e.LockedSectionRemoval="LockedSectionRemoval",e.LockedFieldRemoval="LockedFieldRemoval",e.RequiredFieldRemoval="RequiredFieldRemoval",e.LastRemainingTab="LastRemainingTab",e.UnknownRemoval="UnknownRemoval"})(Q_||(Q_={}));(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"})(X_||(X_={}))});var N0,eT=L(()=>{"use strict";(function(e){e.DefaultValue="defaultValue",e.Loaded="loaded"})(N0||(N0={}))});var nT,m6,tT,Ace,Sce,yu,rT,Nce,_ce,iT=L(()=>{"use strict";nT=Ae(aa());st();ws();J_();os();Tn();Ho();ue();m6=Ae(Qi());eT();(function(e){e.Model="Model",e.Canvas="Canvas",e.CustomPages="CustomPages"})(tT||(tT={}));Ace={Read:io.Read,Edit:io.Edit,Both:io.Both,Container:io.Container},Sce={input:jo.Input,bound:jo.Bound,output:jo.Output};(function(e){e[e.dataset=0]="dataset",e[e.property=1]="property",e[e.groups=2]="groups",e[e.group=3]="group"})(yu||(yu={}));(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"})(rT||(rT={}));Nce=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]),_ce={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 Dn,df,oT=L(()=>{"use strict";Dn=Ae(aa());ht();st();Xt();ws();Ho();iT();os();ue();It();Tn();df=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(Ht.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===Ht.name)?.value}getParameterChildrenValues(t,r,n){if(this.isDataSet(t)){let i=r.find(u=>u.key===Ht.name)?.value,o={Name:i,Type:F.Grid,Columns:[]},l=this.getParameters().get(Ht.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(Li.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:qh.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===yu.dataset?o.get(Ht.dataset)?.some(m=>this.getDatasetName(m)===d)||r.push({Name:d,Value:{Name:d,Columns:[],Type:F.Grid}}):c.propertyType===yu.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,Dn.trackInfoTrace)(cr,{eventName:`${Ri}/parametersToJSON`,eventData:{message:`Configuration metadata for custom control parameter ${a} is not available for custom control : ${this.name}.`}}),r=[];break}}}else(0,Dn.trackErrorTrace)(cr,{eventName:`${Ri}/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,Dn.trackErrorTrace)(cr,{eventName:`${Ri}/parametersToJSON`,eventData:{message:"Custom Control Manifest not found"}},new Error(`No custom control manifest found for ${this.name}`))}catch(n){(0,Dn.trackErrorTrace)(cr,{eventName:`${Ri}/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===Ht.name)?.value;if(o)return this.getParameterChildrenValues(t,r);{let s=new Error(`No dataset manifest info for ${a}`);(0,Dn.trackErrorTrace)(cr,{eventName:`${Ri}/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=>!fd.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===Ti.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(Bh.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,Dn.trackErrorTrace)(cr,{eventName:`${Ri}/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,Dn.trackErrorTrace)(cr,{eventName:`${Ri}/parameterJSON`,eventData:{message:"Missing property type info"}},f)}else{let l=new Error(`No property manifest info for ${t}`);(0,Dn.trackWarningTrace)(cr,{eventName:`${Ri}/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 fd.includes(t)}isNumberTypeProperty(t,r){return pd.includes(r)||t.ofTypeGroup.some(n=>pd.includes(n))}isDataSet(t){return Ht.dataset===t}isGroups(t){return!!t[0].getAllProperties().find(n=>n.key==="isGroup"&&n.value==="true")}}});var ee,_0=L(()=>{"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 aT={};Jr(aT,{CustomControlUniqueId:()=>ua,DeprecatedControlClassIds:()=>G,FieldControlTypes:()=>lt,mapFieldTypeToControl:()=>h6});function h6(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,ua,lt,bu=L(()=>{"use strict";ht();Wl();st();Xt();os();oa();_0();Tn();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"}};ua=class{static get RelationshipAssistant(){return"3ff9a528-dd50-4aca-8f10-2e5ed73513ad"}static get PredictiveLeadScoring(){return"6f503f2a-d033-4106-b62c-f8f2e5f01a57"}},lt=class e{static FieldControlIds=e.initializeFieldControls();static UnboundControlIds=e.initializeUnboundControls();static ControlsAllowedForReferencePanel=e.initializeReferencePanelControls();static ControlsAllowedForFooter=e.initializeFooterControls();static CustomControlIdMap=new ar;static initializeFieldControls(){let t=new ar,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 k=e.getControlName($.MultipleLineofText,W.TextArea);t.add(k,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 Oe=e.getControlName($.TwoOptions,"Radio");t.add(Oe,new U(G.RadioControl));let Vt=e.getControlName($.TwoOptions,"CheckBox");t.add(Vt,new U(G.CheckBoxControl));let Xe=e.getControlName($.TwoOptions,"List");t.add(Xe,new U(G.PicklistControl));let Ne=e.getControlName($.State,W.None);t.add(Ne,new U(G.PicklistControl));let se=e.getControlName($.Status,W.None);t.add(se,new U(G.PicklistStatusControl));let We=e.getControlName($.OwnerType,W.None);t.add(We,new U(G.LookupControl));let ir=e.getControlName($.PartyListType,W.None);t.add(ir,new U(G.PartyListControl));let PU=e.getControlName($.LookupType,W.Regarding);t.add(PU,new U(G.RegardingControl));let RU=e.getControlName($.MultiSelectOptionSet,W.None);return t.add(RU,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 ar;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(ua.RelationshipAssistant,ee.CustomControl),t}static initializeReferencePanelControls(){let t=new ar;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 is;return t.add(Cs.IFRAME,!0),t.add(Cs.SPACER,!0),t.add(Cs.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(Ue.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===ua.RelationshipAssistant||t.guidString===ua.PredictiveLeadScoring)}static isRelationshipAssistantControl(t){return!R.IsNullOrUndefined(t)&&e.isRelationshipAssistant(t.UniqueId)}static isRelationshipAssistant(t){return!R.IsNullOrUndefined(t)&&t.guidString===ua.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 ff,sT=L(()=>{"use strict";ff=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,As,lT,uT,yo,cT,dT,T0=L(()=>{"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"})(As||(As={}));(function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle"})(lT||(lT={}));(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"})(uT||(uT={}));(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"})(yo||(yo={}));(function(e){e[e.None=0]="None",e[e.SystemRequired=1]="SystemRequired",e[e.ApplicationRequired=2]="ApplicationRequired",e[e.Recommended=3]="Recommended"})(cT||(cT={}));(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"})(dT||(dT={}))});var Ss,fT=L(()=>{"use strict";gu();Ss=p0({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 pT(e){return{...e,extractConfig:t=>g6(t,Object.keys(e.fallback))}}function g6(e,t){let r={};for(let n of t)typeof e[n]<"u"&&(r[n]=e[n]);return r}var D0=L(()=>{"use strict";});var I0=v((Zce,hT)=>{var vu=new Proxy(function(){return vu},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:vu},apply:function(){return vu},construct:function(){return{}}}),mT=function(){return vu};Object.setPrototypeOf(mT,vu);hT.exports=mT});var bT=v((ede,yT)=>{var wu=new Proxy(function(){return wu},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:wu},apply:function(){return wu},construct:function(){return{}}}),gT=function(){return wu};Object.setPrototypeOf(gT,wu);yT.exports=gT});var O0=v((tde,wT)=>{var Cu=new Proxy(function(){return Cu},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:Cu},apply:function(){return Cu},construct:function(){return{}}}),vT=function(){return Cu};Object.setPrototypeOf(vT,Cu);wT.exports=vT});var ET=v((rde,CT)=>{function y6(){this.__data__=[],this.size=0}CT.exports=y6});var Ns=v((nde,AT)=>{function b6(e,t){return e===t||e!==e&&t!==t}AT.exports=b6});var Eu=v((ide,ST)=>{var v6=Ns();function w6(e,t){for(var r=e.length;r--;)if(v6(e[r][0],t))return r;return-1}ST.exports=w6});var _T=v((ode,NT)=>{var C6=Eu(),E6=Array.prototype,A6=E6.splice;function S6(e){var t=this.__data__,r=C6(t,e);if(r<0)return!1;var n=t.length-1;return r==n?t.pop():A6.call(t,r,1),--this.size,!0}NT.exports=S6});var DT=v((ade,TT)=>{var N6=Eu();function _6(e){var t=this.__data__,r=N6(t,e);return r<0?void 0:t[r][1]}TT.exports=_6});var OT=v((sde,IT)=>{var T6=Eu();function D6(e){return T6(this.__data__,e)>-1}IT.exports=D6});var RT=v((lde,PT)=>{var I6=Eu();function O6(e,t){var r=this.__data__,n=I6(r,e);return n<0?(++this.size,r.push([e,t])):r[n][1]=t,this}PT.exports=O6});var Au=v((ude,kT)=>{var P6=ET(),R6=_T(),k6=DT(),L6=OT(),$6=RT();function _s(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])}}_s.prototype.clear=P6;_s.prototype.delete=R6;_s.prototype.get=k6;_s.prototype.has=L6;_s.prototype.set=$6;kT.exports=_s});var $T=v((cde,LT)=>{var x6=Au();function F6(){this.__data__=new x6,this.size=0}LT.exports=F6});var FT=v((dde,xT)=>{function M6(e){var t=this.__data__,r=t.delete(e);return this.size=t.size,r}xT.exports=M6});var UT=v((fde,MT)=>{function U6(e){return this.__data__.get(e)}MT.exports=U6});var qT=v((pde,BT)=>{function B6(e){return this.__data__.has(e)}BT.exports=B6});var P0=v((mde,VT)=>{var q6=typeof global=="object"&&global&&global.Object===Object&&global;VT.exports=q6});var In=v((hde,GT)=>{var V6=P0(),G6=typeof self=="object"&&self&&self.Object===Object&&self,W6=V6||G6||Function("return this")();GT.exports=W6});var Su=v((gde,WT)=>{var z6=In(),j6=z6.Symbol;WT.exports=j6});var KT=v((yde,HT)=>{var zT=Su(),jT=Object.prototype,H6=jT.hasOwnProperty,K6=jT.toString,Nu=zT?zT.toStringTag:void 0;function J6(e){var t=H6.call(e,Nu),r=e[Nu];try{e[Nu]=void 0;var n=!0}catch{}var i=K6.call(e);return n&&(t?e[Nu]=r:delete e[Nu]),i}HT.exports=J6});var YT=v((bde,JT)=>{var Y6=Object.prototype,Q6=Y6.toString;function X6(e){return Q6.call(e)}JT.exports=X6});var da=v((vde,ZT)=>{var QT=Su(),Z6=KT(),ez=YT(),tz="[object Null]",rz="[object Undefined]",XT=QT?QT.toStringTag:void 0;function nz(e){return e==null?e===void 0?rz:tz:XT&&XT in Object(e)?Z6(e):ez(e)}ZT.exports=nz});var $i=v((wde,eD)=>{function iz(e){var t=typeof e;return e!=null&&(t=="object"||t=="function")}eD.exports=iz});var pf=v((Cde,tD)=>{var oz=da(),az=$i(),sz="[object AsyncFunction]",lz="[object Function]",uz="[object GeneratorFunction]",cz="[object Proxy]";function dz(e){if(!az(e))return!1;var t=oz(e);return t==lz||t==uz||t==sz||t==cz}tD.exports=dz});var nD=v((Ede,rD)=>{var fz=In(),pz=fz["__core-js_shared__"];rD.exports=pz});var aD=v((Ade,oD)=>{var R0=nD(),iD=(function(){var e=/[^.]+$/.exec(R0&&R0.keys&&R0.keys.IE_PROTO||"");return e?"Symbol(src)_1."+e:""})();function mz(e){return!!iD&&iD in e}oD.exports=mz});var k0=v((Sde,sD)=>{var hz=Function.prototype,gz=hz.toString;function yz(e){if(e!=null){try{return gz.call(e)}catch{}try{return e+""}catch{}}return""}sD.exports=yz});var uD=v((Nde,lD)=>{var bz=pf(),vz=aD(),wz=$i(),Cz=k0(),Ez=/[\\^$.*+?()[\]{}|]/g,Az=/^\[object .+?Constructor\]$/,Sz=Function.prototype,Nz=Object.prototype,_z=Sz.toString,Tz=Nz.hasOwnProperty,Dz=RegExp("^"+_z.call(Tz).replace(Ez,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function Iz(e){if(!wz(e)||vz(e))return!1;var t=bz(e)?Dz:Az;return t.test(Cz(e))}lD.exports=Iz});var dD=v((_de,cD)=>{function Oz(e,t){return e?.[t]}cD.exports=Oz});var bo=v((Tde,fD)=>{var Pz=uD(),Rz=dD();function kz(e,t){var r=Rz(e,t);return Pz(r)?r:void 0}fD.exports=kz});var mf=v((Dde,pD)=>{var Lz=bo(),$z=In(),xz=Lz($z,"Map");pD.exports=xz});var _u=v((Ide,mD)=>{var Fz=bo(),Mz=Fz(Object,"create");mD.exports=Mz});var yD=v((Ode,gD)=>{var hD=_u();function Uz(){this.__data__=hD?hD(null):{},this.size=0}gD.exports=Uz});var vD=v((Pde,bD)=>{function Bz(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t}bD.exports=Bz});var CD=v((Rde,wD)=>{var qz=_u(),Vz="__lodash_hash_undefined__",Gz=Object.prototype,Wz=Gz.hasOwnProperty;function zz(e){var t=this.__data__;if(qz){var r=t[e];return r===Vz?void 0:r}return Wz.call(t,e)?t[e]:void 0}wD.exports=zz});var AD=v((kde,ED)=>{var jz=_u(),Hz=Object.prototype,Kz=Hz.hasOwnProperty;function Jz(e){var t=this.__data__;return jz?t[e]!==void 0:Kz.call(t,e)}ED.exports=Jz});var ND=v((Lde,SD)=>{var Yz=_u(),Qz="__lodash_hash_undefined__";function Xz(e,t){var r=this.__data__;return this.size+=this.has(e)?0:1,r[e]=Yz&&t===void 0?Qz:t,this}SD.exports=Xz});var TD=v(($de,_D)=>{var Zz=yD(),ej=vD(),tj=CD(),rj=AD(),nj=ND();function Ts(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])}}Ts.prototype.clear=Zz;Ts.prototype.delete=ej;Ts.prototype.get=tj;Ts.prototype.has=rj;Ts.prototype.set=nj;_D.exports=Ts});var OD=v((xde,ID)=>{var DD=TD(),ij=Au(),oj=mf();function aj(){this.size=0,this.__data__={hash:new DD,map:new(oj||ij),string:new DD}}ID.exports=aj});var RD=v((Fde,PD)=>{function sj(e){var t=typeof e;return t=="string"||t=="number"||t=="symbol"||t=="boolean"?e!=="__proto__":e===null}PD.exports=sj});var Tu=v((Mde,kD)=>{var lj=RD();function uj(e,t){var r=e.__data__;return lj(t)?r[typeof t=="string"?"string":"hash"]:r.map}kD.exports=uj});var $D=v((Ude,LD)=>{var cj=Tu();function dj(e){var t=cj(this,e).delete(e);return this.size-=t?1:0,t}LD.exports=dj});var FD=v((Bde,xD)=>{var fj=Tu();function pj(e){return fj(this,e).get(e)}xD.exports=pj});var UD=v((qde,MD)=>{var mj=Tu();function hj(e){return mj(this,e).has(e)}MD.exports=hj});var qD=v((Vde,BD)=>{var gj=Tu();function yj(e,t){var r=gj(this,e),n=r.size;return r.set(e,t),this.size+=r.size==n?0:1,this}BD.exports=yj});var hf=v((Gde,VD)=>{var bj=OD(),vj=$D(),wj=FD(),Cj=UD(),Ej=qD();function Ds(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])}}Ds.prototype.clear=bj;Ds.prototype.delete=vj;Ds.prototype.get=wj;Ds.prototype.has=Cj;Ds.prototype.set=Ej;VD.exports=Ds});var WD=v((Wde,GD)=>{var Aj=Au(),Sj=mf(),Nj=hf(),_j=200;function Tj(e,t){var r=this.__data__;if(r instanceof Aj){var n=r.__data__;if(!Sj||n.length<_j-1)return n.push([e,t]),this.size=++r.size,this;r=this.__data__=new Nj(n)}return r.set(e,t),this.size=r.size,this}GD.exports=Tj});var L0=v((zde,zD)=>{var Dj=Au(),Ij=$T(),Oj=FT(),Pj=UT(),Rj=qT(),kj=WD();function Is(e){var t=this.__data__=new Dj(e);this.size=t.size}Is.prototype.clear=Ij;Is.prototype.delete=Oj;Is.prototype.get=Pj;Is.prototype.has=Rj;Is.prototype.set=kj;zD.exports=Is});var HD=v((jde,jD)=>{var Lj="__lodash_hash_undefined__";function $j(e){return this.__data__.set(e,Lj),this}jD.exports=$j});var JD=v((Hde,KD)=>{function xj(e){return this.__data__.has(e)}KD.exports=xj});var QD=v((Kde,YD)=>{var Fj=hf(),Mj=HD(),Uj=JD();function gf(e){var t=-1,r=e==null?0:e.length;for(this.__data__=new Fj;++t<r;)this.add(e[t])}gf.prototype.add=gf.prototype.push=Mj;gf.prototype.has=Uj;YD.exports=gf});var ZD=v((Jde,XD)=>{function Bj(e,t){for(var r=-1,n=e==null?0:e.length;++r<n;)if(t(e[r],r,e))return!0;return!1}XD.exports=Bj});var tI=v((Yde,eI)=>{function qj(e,t){return e.has(t)}eI.exports=qj});var $0=v((Qde,rI)=>{var Vj=QD(),Gj=ZD(),Wj=tI(),zj=1,jj=2;function Hj(e,t,r,n,i,o){var a=r&zj,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&jj?new Vj: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(!Gj(t,function(b,w){if(!Wj(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}rI.exports=Hj});var x0=v((Xde,nI)=>{var Kj=In(),Jj=Kj.Uint8Array;nI.exports=Jj});var oI=v((Zde,iI)=>{function Yj(e){var t=-1,r=Array(e.size);return e.forEach(function(n,i){r[++t]=[i,n]}),r}iI.exports=Yj});var sI=v((efe,aI)=>{function Qj(e){var t=-1,r=Array(e.size);return e.forEach(function(n){r[++t]=n}),r}aI.exports=Qj});var fI=v((tfe,dI)=>{var lI=Su(),uI=x0(),Xj=Ns(),Zj=$0(),e7=oI(),t7=sI(),r7=1,n7=2,i7="[object Boolean]",o7="[object Date]",a7="[object Error]",s7="[object Map]",l7="[object Number]",u7="[object RegExp]",c7="[object Set]",d7="[object String]",f7="[object Symbol]",p7="[object ArrayBuffer]",m7="[object DataView]",cI=lI?lI.prototype:void 0,F0=cI?cI.valueOf:void 0;function h7(e,t,r,n,i,o,a){switch(r){case m7:if(e.byteLength!=t.byteLength||e.byteOffset!=t.byteOffset)return!1;e=e.buffer,t=t.buffer;case p7:return!(e.byteLength!=t.byteLength||!o(new uI(e),new uI(t)));case i7:case o7:case l7:return Xj(+e,+t);case a7:return e.name==t.name&&e.message==t.message;case u7:case d7:return e==t+"";case s7:var s=e7;case c7:var l=n&r7;if(s||(s=t7),e.size!=t.size&&!l)return!1;var u=a.get(e);if(u)return u==t;n|=n7,a.set(e,t);var c=Zj(s(e),s(t),n,i,o,a);return a.delete(e),c;case f7:if(F0)return F0.call(e)==F0.call(t)}return!1}dI.exports=h7});var mI=v((rfe,pI)=>{function g7(e,t){for(var r=-1,n=t.length,i=e.length;++r<n;)e[i+r]=t[r];return e}pI.exports=g7});var vo=v((nfe,hI)=>{var y7=Array.isArray;hI.exports=y7});var yI=v((ife,gI)=>{var b7=mI(),v7=vo();function w7(e,t,r){var n=t(e);return v7(e)?n:b7(n,r(e))}gI.exports=w7});var vI=v((ofe,bI)=>{function C7(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}bI.exports=C7});var CI=v((afe,wI)=>{function E7(){return[]}wI.exports=E7});var SI=v((sfe,AI)=>{var A7=vI(),S7=CI(),N7=Object.prototype,_7=N7.propertyIsEnumerable,EI=Object.getOwnPropertySymbols,T7=EI?function(e){return e==null?[]:(e=Object(e),A7(EI(e),function(t){return _7.call(e,t)}))}:S7;AI.exports=T7});var _I=v((lfe,NI)=>{function D7(e,t){for(var r=-1,n=Array(e);++r<e;)n[r]=t(r);return n}NI.exports=D7});var wo=v((ufe,TI)=>{function I7(e){return e!=null&&typeof e=="object"}TI.exports=I7});var II=v((cfe,DI)=>{var O7=da(),P7=wo(),R7="[object Arguments]";function k7(e){return P7(e)&&O7(e)==R7}DI.exports=k7});var M0=v((dfe,RI)=>{var OI=II(),L7=wo(),PI=Object.prototype,$7=PI.hasOwnProperty,x7=PI.propertyIsEnumerable,F7=OI((function(){return arguments})())?OI:function(e){return L7(e)&&$7.call(e,"callee")&&!x7.call(e,"callee")};RI.exports=F7});var LI=v((ffe,kI)=>{function M7(){return!1}kI.exports=M7});var yf=v((Du,Os)=>{var U7=In(),B7=LI(),FI=typeof Du=="object"&&Du&&!Du.nodeType&&Du,$I=FI&&typeof Os=="object"&&Os&&!Os.nodeType&&Os,q7=$I&&$I.exports===FI,xI=q7?U7.Buffer:void 0,V7=xI?xI.isBuffer:void 0,G7=V7||B7;Os.exports=G7});var bf=v((pfe,MI)=>{var W7=9007199254740991,z7=/^(?:0|[1-9]\d*)$/;function j7(e,t){var r=typeof e;return t=t??W7,!!t&&(r=="number"||r!="symbol"&&z7.test(e))&&e>-1&&e%1==0&&e<t}MI.exports=j7});var U0=v((mfe,UI)=>{var H7=9007199254740991;function K7(e){return typeof e=="number"&&e>-1&&e%1==0&&e<=H7}UI.exports=K7});var qI=v((hfe,BI)=>{var J7=da(),Y7=U0(),Q7=wo(),X7="[object Arguments]",Z7="[object Array]",eH="[object Boolean]",tH="[object Date]",rH="[object Error]",nH="[object Function]",iH="[object Map]",oH="[object Number]",aH="[object Object]",sH="[object RegExp]",lH="[object Set]",uH="[object String]",cH="[object WeakMap]",dH="[object ArrayBuffer]",fH="[object DataView]",pH="[object Float32Array]",mH="[object Float64Array]",hH="[object Int8Array]",gH="[object Int16Array]",yH="[object Int32Array]",bH="[object Uint8Array]",vH="[object Uint8ClampedArray]",wH="[object Uint16Array]",CH="[object Uint32Array]",$e={};$e[pH]=$e[mH]=$e[hH]=$e[gH]=$e[yH]=$e[bH]=$e[vH]=$e[wH]=$e[CH]=!0;$e[X7]=$e[Z7]=$e[dH]=$e[eH]=$e[fH]=$e[tH]=$e[rH]=$e[nH]=$e[iH]=$e[oH]=$e[aH]=$e[sH]=$e[lH]=$e[uH]=$e[cH]=!1;function EH(e){return Q7(e)&&Y7(e.length)&&!!$e[J7(e)]}BI.exports=EH});var GI=v((gfe,VI)=>{function AH(e){return function(t){return e(t)}}VI.exports=AH});var zI=v((Iu,Ps)=>{var SH=P0(),WI=typeof Iu=="object"&&Iu&&!Iu.nodeType&&Iu,Ou=WI&&typeof Ps=="object"&&Ps&&!Ps.nodeType&&Ps,NH=Ou&&Ou.exports===WI,B0=NH&&SH.process,_H=(function(){try{var e=Ou&&Ou.require&&Ou.require("util").types;return e||B0&&B0.binding&&B0.binding("util")}catch{}})();Ps.exports=_H});var vf=v((yfe,KI)=>{var TH=qI(),DH=GI(),jI=zI(),HI=jI&&jI.isTypedArray,IH=HI?DH(HI):TH;KI.exports=IH});var q0=v((bfe,JI)=>{var OH=_I(),PH=M0(),RH=vo(),kH=yf(),LH=bf(),$H=vf(),xH=Object.prototype,FH=xH.hasOwnProperty;function MH(e,t){var r=RH(e),n=!r&&PH(e),i=!r&&!n&&kH(e),o=!r&&!n&&!i&&$H(e),a=r||n||i||o,s=a?OH(e.length,String):[],l=s.length;for(var u in e)(t||FH.call(e,u))&&!(a&&(u=="length"||i&&(u=="offset"||u=="parent")||o&&(u=="buffer"||u=="byteLength"||u=="byteOffset")||LH(u,l)))&&s.push(u);return s}JI.exports=MH});var wf=v((vfe,YI)=>{var UH=Object.prototype;function BH(e){var t=e&&e.constructor,r=typeof t=="function"&&t.prototype||UH;return e===r}YI.exports=BH});var V0=v((wfe,QI)=>{function qH(e,t){return function(r){return e(t(r))}}QI.exports=qH});var ZI=v((Cfe,XI)=>{var VH=V0(),GH=VH(Object.keys,Object);XI.exports=GH});var tO=v((Efe,eO)=>{var WH=wf(),zH=ZI(),jH=Object.prototype,HH=jH.hasOwnProperty;function KH(e){if(!WH(e))return zH(e);var t=[];for(var r in Object(e))HH.call(e,r)&&r!="constructor"&&t.push(r);return t}eO.exports=KH});var Pu=v((Afe,rO)=>{var JH=pf(),YH=U0();function QH(e){return e!=null&&YH(e.length)&&!JH(e)}rO.exports=QH});var iO=v((Sfe,nO)=>{var XH=q0(),ZH=tO(),eK=Pu();function tK(e){return eK(e)?XH(e):ZH(e)}nO.exports=tK});var aO=v((Nfe,oO)=>{var rK=yI(),nK=SI(),iK=iO();function oK(e){return rK(e,iK,nK)}oO.exports=oK});var uO=v((_fe,lO)=>{var sO=aO(),aK=1,sK=Object.prototype,lK=sK.hasOwnProperty;function uK(e,t,r,n,i,o){var a=r&aK,s=sO(e),l=s.length,u=sO(t),c=u.length;if(l!=c&&!a)return!1;for(var d=l;d--;){var f=s[d];if(!(a?f in t:lK.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}lO.exports=uK});var dO=v((Tfe,cO)=>{var cK=bo(),dK=In(),fK=cK(dK,"DataView");cO.exports=fK});var pO=v((Dfe,fO)=>{var pK=bo(),mK=In(),hK=pK(mK,"Promise");fO.exports=hK});var hO=v((Ife,mO)=>{var gK=bo(),yK=In(),bK=gK(yK,"Set");mO.exports=bK});var yO=v((Ofe,gO)=>{var vK=bo(),wK=In(),CK=vK(wK,"WeakMap");gO.exports=CK});var NO=v((Pfe,SO)=>{var G0=dO(),W0=mf(),z0=pO(),j0=hO(),H0=yO(),AO=da(),Rs=k0(),bO="[object Map]",EK="[object Object]",vO="[object Promise]",wO="[object Set]",CO="[object WeakMap]",EO="[object DataView]",AK=Rs(G0),SK=Rs(W0),NK=Rs(z0),_K=Rs(j0),TK=Rs(H0),fa=AO;(G0&&fa(new G0(new ArrayBuffer(1)))!=EO||W0&&fa(new W0)!=bO||z0&&fa(z0.resolve())!=vO||j0&&fa(new j0)!=wO||H0&&fa(new H0)!=CO)&&(fa=function(e){var t=AO(e),r=t==EK?e.constructor:void 0,n=r?Rs(r):"";if(n)switch(n){case AK:return EO;case SK:return bO;case NK:return vO;case _K:return wO;case TK:return CO}return t});SO.exports=fa});var kO=v((Rfe,RO)=>{var K0=L0(),DK=$0(),IK=fI(),OK=uO(),_O=NO(),TO=vo(),DO=yf(),PK=vf(),RK=1,IO="[object Arguments]",OO="[object Array]",Cf="[object Object]",kK=Object.prototype,PO=kK.hasOwnProperty;function LK(e,t,r,n,i,o){var a=TO(e),s=TO(t),l=a?OO:_O(e),u=s?OO:_O(t);l=l==IO?Cf:l,u=u==IO?Cf:u;var c=l==Cf,d=u==Cf,f=l==u;if(f&&DO(e)){if(!DO(t))return!1;a=!0,c=!1}if(f&&!c)return o||(o=new K0),a||PK(e)?DK(e,t,r,n,i,o):IK(e,t,l,r,n,i,o);if(!(r&RK)){var m=c&&PO.call(e,"__wrapped__"),p=d&&PO.call(t,"__wrapped__");if(m||p){var h=m?e.value():e,g=p?t.value():t;return o||(o=new K0),i(h,g,r,n,o)}}return f?(o||(o=new K0),OK(e,t,r,n,i,o)):!1}RO.exports=LK});var FO=v((kfe,xO)=>{var $K=kO(),LO=wo();function $O(e,t,r,n,i){return e===t?!0:e==null||t==null||!LO(e)&&!LO(t)?e!==e&&t!==t:$K(e,t,r,n,$O,i)}xO.exports=$O});var UO=v((Lfe,MO)=>{var xK=FO();function FK(e,t){return xK(e,t)}MO.exports=FK});var J0=v(($fe,BO)=>{var MK=bo(),UK=(function(){try{var e=MK(Object,"defineProperty");return e({},"",{}),e}catch{}})();BO.exports=UK});var Ef=v((xfe,VO)=>{var qO=J0();function BK(e,t,r){t=="__proto__"&&qO?qO(e,t,{configurable:!0,enumerable:!0,value:r,writable:!0}):e[t]=r}VO.exports=BK});var Y0=v((Ffe,GO)=>{var qK=Ef(),VK=Ns();function GK(e,t,r){(r!==void 0&&!VK(e[t],r)||r===void 0&&!(t in e))&&qK(e,t,r)}GO.exports=GK});var zO=v((Mfe,WO)=>{function WK(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}}WO.exports=WK});var HO=v((Ufe,jO)=>{var zK=zO(),jK=zK();jO.exports=jK});var XO=v((Ru,ks)=>{var HK=In(),QO=typeof Ru=="object"&&Ru&&!Ru.nodeType&&Ru,KO=QO&&typeof ks=="object"&&ks&&!ks.nodeType&&ks,KK=KO&&KO.exports===QO,JO=KK?HK.Buffer:void 0,YO=JO?JO.allocUnsafe:void 0;function JK(e,t){if(t)return e.slice();var r=e.length,n=YO?YO(r):new e.constructor(r);return e.copy(n),n}ks.exports=JK});var tP=v((Bfe,eP)=>{var ZO=x0();function YK(e){var t=new e.constructor(e.byteLength);return new ZO(t).set(new ZO(e)),t}eP.exports=YK});var nP=v((qfe,rP)=>{var QK=tP();function XK(e,t){var r=t?QK(e.buffer):e.buffer;return new e.constructor(r,e.byteOffset,e.length)}rP.exports=XK});var oP=v((Vfe,iP)=>{function ZK(e,t){var r=-1,n=e.length;for(t||(t=Array(n));++r<n;)t[r]=e[r];return t}iP.exports=ZK});var lP=v((Gfe,sP)=>{var eJ=$i(),aP=Object.create,tJ=(function(){function e(){}return function(t){if(!eJ(t))return{};if(aP)return aP(t);e.prototype=t;var r=new e;return e.prototype=void 0,r}})();sP.exports=tJ});var Q0=v((Wfe,uP)=>{var rJ=V0(),nJ=rJ(Object.getPrototypeOf,Object);uP.exports=nJ});var dP=v((zfe,cP)=>{var iJ=lP(),oJ=Q0(),aJ=wf();function sJ(e){return typeof e.constructor=="function"&&!aJ(e)?iJ(oJ(e)):{}}cP.exports=sJ});var pP=v((jfe,fP)=>{var lJ=Pu(),uJ=wo();function cJ(e){return uJ(e)&&lJ(e)}fP.exports=cJ});var gP=v((Hfe,hP)=>{var dJ=da(),fJ=Q0(),pJ=wo(),mJ="[object Object]",hJ=Function.prototype,gJ=Object.prototype,mP=hJ.toString,yJ=gJ.hasOwnProperty,bJ=mP.call(Object);function vJ(e){if(!pJ(e)||dJ(e)!=mJ)return!1;var t=fJ(e);if(t===null)return!0;var r=yJ.call(t,"constructor")&&t.constructor;return typeof r=="function"&&r instanceof r&&mP.call(r)==bJ}hP.exports=vJ});var X0=v((Kfe,yP)=>{function wJ(e,t){if(!(t==="constructor"&&typeof e[t]=="function")&&t!="__proto__")return e[t]}yP.exports=wJ});var Z0=v((Jfe,bP)=>{var CJ=Ef(),EJ=Ns(),AJ=Object.prototype,SJ=AJ.hasOwnProperty;function NJ(e,t,r){var n=e[t];(!(SJ.call(e,t)&&EJ(n,r))||r===void 0&&!(t in e))&&CJ(e,t,r)}bP.exports=NJ});var wP=v((Yfe,vP)=>{var _J=Z0(),TJ=Ef();function DJ(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?TJ(r,s,l):_J(r,s,l)}return r}vP.exports=DJ});var EP=v((Qfe,CP)=>{function IJ(e){var t=[];if(e!=null)for(var r in Object(e))t.push(r);return t}CP.exports=IJ});var SP=v((Xfe,AP)=>{var OJ=$i(),PJ=wf(),RJ=EP(),kJ=Object.prototype,LJ=kJ.hasOwnProperty;function $J(e){if(!OJ(e))return RJ(e);var t=PJ(e),r=[];for(var n in e)n=="constructor"&&(t||!LJ.call(e,n))||r.push(n);return r}AP.exports=$J});var ey=v((Zfe,NP)=>{var xJ=q0(),FJ=SP(),MJ=Pu();function UJ(e){return MJ(e)?xJ(e,!0):FJ(e)}NP.exports=UJ});var TP=v((epe,_P)=>{var BJ=wP(),qJ=ey();function VJ(e){return BJ(e,qJ(e))}_P.exports=VJ});var kP=v((tpe,RP)=>{var DP=Y0(),GJ=XO(),WJ=nP(),zJ=oP(),jJ=dP(),IP=M0(),OP=vo(),HJ=pP(),KJ=yf(),JJ=pf(),YJ=$i(),QJ=gP(),XJ=vf(),PP=X0(),ZJ=TP();function eY(e,t,r,n,i,o,a){var s=PP(e,r),l=PP(t,r),u=a.get(l);if(u){DP(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),m=!f&&KJ(l),p=!f&&!m&&XJ(l);c=l,f||m||p?OP(s)?c=s:HJ(s)?c=zJ(s):m?(d=!1,c=GJ(l,!0)):p?(d=!1,c=WJ(l,!0)):c=[]:QJ(l)||IP(l)?(c=s,IP(s)?c=ZJ(s):(!YJ(s)||JJ(s))&&(c=jJ(l))):d=!1}d&&(a.set(l,c),i(c,l,n,o,a),a.delete(l)),DP(e,r,c)}RP.exports=eY});var ty=v((rpe,$P)=>{var tY=L0(),rY=Y0(),nY=HO(),iY=kP(),oY=$i(),aY=ey(),sY=X0();function LP(e,t,r,n,i){e!==t&&nY(t,function(o,a){if(i||(i=new tY),oY(o))iY(e,t,a,r,LP,n,i);else{var s=n?n(sY(e,a),o,a+"",e,t,i):void 0;s===void 0&&(s=o),rY(e,a,s)}},aY)}$P.exports=LP});var ry=v((npe,xP)=>{function lY(e){return e}xP.exports=lY});var MP=v((ipe,FP)=>{function uY(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=uY});var qP=v((ope,BP)=>{var cY=MP(),UP=Math.max;function dY(e,t,r){return t=UP(t===void 0?e.length-1:t,0),function(){for(var n=arguments,i=-1,o=UP(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),cY(e,this,s)}}BP.exports=dY});var GP=v((ape,VP)=>{function fY(e){return function(){return e}}VP.exports=fY});var jP=v((spe,zP)=>{var pY=GP(),WP=J0(),mY=ry(),hY=WP?function(e,t){return WP(e,"toString",{configurable:!0,enumerable:!1,value:pY(t),writable:!0})}:mY;zP.exports=hY});var KP=v((lpe,HP)=>{var gY=800,yY=16,bY=Date.now;function vY(e){var t=0,r=0;return function(){var n=bY(),i=yY-(n-r);if(r=n,i>0){if(++t>=gY)return arguments[0]}else t=0;return e.apply(void 0,arguments)}}HP.exports=vY});var YP=v((upe,JP)=>{var wY=jP(),CY=KP(),EY=CY(wY);JP.exports=EY});var XP=v((cpe,QP)=>{var AY=ry(),SY=qP(),NY=YP();function _Y(e,t){return NY(SY(e,t,AY),e+"")}QP.exports=_Y});var eR=v((dpe,ZP)=>{var TY=Ns(),DY=Pu(),IY=bf(),OY=$i();function PY(e,t,r){if(!OY(r))return!1;var n=typeof t;return(n=="number"?DY(r)&&IY(t,r.length):n=="string"&&t in r)?TY(r[t],e):!1}ZP.exports=PY});var ny=v((fpe,tR)=>{var RY=XP(),kY=eR();function LY(e){return RY(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&&kY(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})}tR.exports=LY});var nR=v((ppe,rR)=>{var $Y=ty(),xY=ny(),FY=xY(function(e,t,r,n){$Y(e,t,r,n)});rR.exports=FY});var un,ku=L(()=>{"use strict";(function(e){e[e.NotLoaded=0]="NotLoaded",e[e.Initialized=1]="Initialized",e[e.ConfigsLoaded=2]="ConfigsLoaded",e[e.Error=3]="Error"})(un||(un={}))});function oR(e,t,r="PROD"){let n=i=>`ShellSettings_ECS_ClientCache_${e}_${iR.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 iR,MY,aR=L(()=>{"use strict";iR=Ae(O0()),MY=Ae(I0());});var iy,sR=L(()=>{"use strict";of();iy=hu({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 uR,cR,dR,fR,oy,UY,Af,lR,ay=L(()=>{"use strict";uR=Ae(I0()),cR=Ae(bT()),dR=Ae(O0()),fR=Ae(UO()),oy=Ae(nR());ku();aR();sR();UY=60*1e3,Af=class{clientName;logger;ecsEndpoint;resolveLoadingPromise;loadingPromise=new Promise(t=>this.resolveLoadingPromise=t);_status=un.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"?iy.prodEcsEndpoint:iy.integrationEcsEndpoint}client=new cR.default;init=async({clientVersion:t,getFilters:r,cacheStorage:n=uR.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:[dR.EcsConfigType.Default],hosts:[this.ecsEndpoint],initialAppActiveState:!0,getEcsParameters:a,databaseInterface:oR(this.clientName,n,this.endpointType),...o}),this.client.requestUpdate(),this._status===un.NotLoaded&&(this._status=un.Initialized)}catch(s){this._status=un.Error,this.resolveLoadingPromise(),this.logEvent("FeaturesClient/initializationFailed",{ecsClientName:this.clientName,error:s},"Error")}i&&window.setInterval(()=>this.client.requestUpdate(),i*UY)};getConfig=t=>{let r=this.getMergedClientConfigByTeamName(t.teamName),n=r?t.extractConfig(r):{};return(0,oy.default)({},t.fallback,n,t.override,lR)};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,fR.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,oy.default)({},this.client.getConfig()?.config,this.clientConfigOverride,lR);getMergedClientConfigByTeamName=t=>this.getMergedClientConfig()?.[t];handleConfigUpdated=()=>{let t=this.client.getConfig();if(t===void 0)return;this.resolveLoadingPromise(),this._status=un.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})}},lR=(e,t)=>{if(Array.isArray(t))return t}});var mR=v((Epe,pR)=>{"use strict";var BY=()=>{let e={};return e.promise=new Promise((t,r)=>{e.resolve=t,e.reject=r}),e};pR.exports=BY});var sy=v((Ape,gR)=>{var Lu=new Proxy(function(){return Lu},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:Lu},apply:function(){return Lu},construct:function(){return{}}}),hR=function(){return Lu};Object.setPrototypeOf(hR,Lu);gR.exports=hR});var vR=v((Spe,bR)=>{var $u=new Proxy(function(){return $u},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:$u},apply:function(){return $u},construct:function(){return{}}}),yR=function(){return $u};Object.setPrototypeOf(yR,$u);bR.exports=yR});var _R=v((Npe,NR)=>{"use strict";var ly=vR(),qY={childContextTypes:!0,contextType:!0,contextTypes:!0,defaultProps:!0,displayName:!0,getDefaultProps:!0,getDerivedStateFromError:!0,getDerivedStateFromProps:!0,mixins:!0,propTypes:!0,type:!0},VY={name:!0,length:!0,prototype:!0,caller:!0,callee:!0,arguments:!0,arity:!0},GY={$$typeof:!0,render:!0,defaultProps:!0,displayName:!0,propTypes:!0},AR={$$typeof:!0,compare:!0,defaultProps:!0,displayName:!0,propTypes:!0,type:!0},uy={};uy[ly.ForwardRef]=GY;uy[ly.Memo]=AR;function wR(e){return ly.isMemo(e)?AR:uy[e.$$typeof]||qY}var WY=Object.defineProperty,zY=Object.getOwnPropertyNames,CR=Object.getOwnPropertySymbols,jY=Object.getOwnPropertyDescriptor,HY=Object.getPrototypeOf,ER=Object.prototype;function SR(e,t,r){if(typeof t!="string"){if(ER){var n=HY(t);n&&n!==ER&&SR(e,n,r)}var i=zY(t);CR&&(i=i.concat(CR(t)));for(var o=wR(e),a=wR(t),s=0;s<i.length;++s){var l=i[s];if(!VY[l]&&!(r&&r[l])&&!(a&&a[l])&&!(o&&o[l])){var u=jY(t,l);try{WY(e,l,u)}catch{}}}}return e}NR.exports=SR});function DR(e,t,r){let[n,i]=(0,Ls.useState)(e.getConfig(t));return(0,Ls.useEffect)(()=>{if(!r?.subscribe&&e.status===un.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 DR(e,t,r)}}function OR(e,t,r,n){let i=o=>{let a=DR(e,t,n),s={...o,...a};return Ls.default.createElement(r,{...s})};return(0,TR.default)(i,r),i.displayName=`WithFeature(${r.name})`,i}function PR(e,t,r,n){return t.reduce((i,o)=>OR(e,o,i,n),r)}function RR(e){return function(t,r,n){return OR(e,t,r,n)}}var TR,Ls,cy=L(()=>{"use strict";TR=Ae(_R()),Ls=Ae(sy());ku();});var LR=v((Dpe,kR)=>{var KY=ty(),JY=ny(),YY=JY(function(e,t,r){KY(e,t,r)});kR.exports=YY});var Sf=v((Ipe,$R)=>{var QY=da(),XY=wo(),ZY="[object Symbol]";function eQ(e){return typeof e=="symbol"||XY(e)&&QY(e)==ZY}$R.exports=eQ});var FR=v((Ope,xR)=>{var tQ=vo(),rQ=Sf(),nQ=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,iQ=/^\w*$/;function oQ(e,t){if(tQ(e))return!1;var r=typeof e;return r=="number"||r=="symbol"||r=="boolean"||e==null||rQ(e)?!0:iQ.test(e)||!nQ.test(e)||t!=null&&e in Object(t)}xR.exports=oQ});var BR=v((Ppe,UR)=>{var MR=hf(),aQ="Expected a function";function dy(e,t){if(typeof e!="function"||t!=null&&typeof t!="function")throw new TypeError(aQ);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(dy.Cache||MR),r}dy.Cache=MR;UR.exports=dy});var VR=v((Rpe,qR)=>{var sQ=BR(),lQ=500;function uQ(e){var t=sQ(e,function(n){return r.size===lQ&&r.clear(),n}),r=t.cache;return t}qR.exports=uQ});var WR=v((kpe,GR)=>{var cQ=VR(),dQ=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,fQ=/\\(\\)?/g,pQ=cQ(function(e){var t=[];return e.charCodeAt(0)===46&&t.push(""),e.replace(dQ,function(r,n,i,o){t.push(i?o.replace(fQ,"$1"):n||r)}),t});GR.exports=pQ});var jR=v((Lpe,zR)=>{function mQ(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}zR.exports=mQ});var XR=v(($pe,QR)=>{var HR=Su(),hQ=jR(),gQ=vo(),yQ=Sf(),bQ=1/0,KR=HR?HR.prototype:void 0,JR=KR?KR.toString:void 0;function YR(e){if(typeof e=="string")return e;if(gQ(e))return hQ(e,YR)+"";if(yQ(e))return JR?JR.call(e):"";var t=e+"";return t=="0"&&1/e==-bQ?"-0":t}QR.exports=YR});var e2=v((xpe,ZR)=>{var vQ=XR();function wQ(e){return e==null?"":vQ(e)}ZR.exports=wQ});var r2=v((Fpe,t2)=>{var CQ=vo(),EQ=FR(),AQ=WR(),SQ=e2();function NQ(e,t){return CQ(e)?e:EQ(e,t)?[e]:AQ(SQ(e))}t2.exports=NQ});var i2=v((Mpe,n2)=>{var _Q=Sf(),TQ=1/0;function DQ(e){if(typeof e=="string"||_Q(e))return e;var t=e+"";return t=="0"&&1/e==-TQ?"-0":t}n2.exports=DQ});var s2=v((Upe,a2)=>{var IQ=Z0(),OQ=r2(),PQ=bf(),o2=$i(),RQ=i2();function kQ(e,t,r,n){if(!o2(e))return e;t=OQ(t,e);for(var i=-1,o=t.length,a=o-1,s=e;s!=null&&++i<o;){var l=RQ(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=o2(c)?c:PQ(t[i+1])?[]:{})}IQ(s,l,u),s=s[l]}return e}a2.exports=kQ});var u2=v((Bpe,l2)=>{var LQ=s2();function $Q(e,t,r){return e==null?e:LQ(e,t,r)}l2.exports=$Q});function p2(e){let{query:t}=(0,f2.default)(window.location.href,!0);return FQ(e,t),e}function FQ(e,t){let r=xQ+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+m2,u={};if(o===r)u=s;else if(o.startsWith(l)){let c=o.substring(l.length);(0,d2.default)(u,c,s)}(0,c2.default)(i,u)}catch{}}),Object.keys(i).length>0&&e.overrideClientConfig(i)}var c2,d2,f2,m2,xQ,h2=L(()=>{"use strict";c2=Ae(LR()),d2=Ae(u2()),f2=Ae(y0());m2=".",xQ="ecs"+m2});function _f(e,t,r){let n=p2(new Af(e,t,r));function i(o){(0,Nf.useEffect)(()=>{n.init(o)},[])}return{featuresClient:n,createFeature:UQ(n),useFeaturesClientInitParams:i,withFeatures:(o,a,s)=>PR(n,o,a,s)}}function UQ(e){let t=IR(e),r=RR(e);return function(i){let o=pT(i);return o.getConfig=()=>e.getConfig(o),o.isLoaded=()=>e.status===un.ConfigsLoaded,w0.register(o,e.clientName),{useFeature:a=>t(o,a),withFeature:(a,s)=>r(o,a,s),feature:o}}}var MQ,Nf,fy=L(()=>{"use strict";MQ=Ae(mR()),Nf=Ae(sy());D0();ay();ku();cy();h2();C0();});var g2=L(()=>{"use strict";D0();ay();fy();ku();cy();uf();E0();});function Tf(e){return{logEvent:(t,r,n)=>{switch(n){case"Error":(0,$s.trackErrorTrace)(e,{eventName:t,eventData:r});break;case"Warning":(0,$s.trackWarningTrace)(e,{eventName:t,eventData:r});break;default:(0,$s.trackInfoTrace)(e,{eventName:t,eventData:r});break}}}}var $s,py=L(()=>{"use strict";$s=Ae(aa());});var ame,sme,lme,y2=L(()=>{"use strict";g2();py();({featuresClient:ame,createFeature:sme,useFeaturesClientInitParams:lme}=_f("PowerApps-Shell-Test",Tf("shell-features")))});var w2=v((cme,v2)=>{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{}}}),b2=function(){return xu};Object.setPrototypeOf(b2,xu);v2.exports=b2});var BQ,qQ,C2=L(()=>{"use strict";fu();BQ=Ae(w2()),qQ=Ae(aa());});var E2=L(()=>{"use strict";y2();py();C2();});var vme,xs,wme,A2=L(()=>{"use strict";E2();fy();({featuresClient:vme,createFeature:xs,useFeaturesClientInitParams:wme}=_f("PowerApps-MakerPortal",Tf("powerapps-features")))});var S2,N2,Sme,Nme,_me,Tme,my=L(()=>{"use strict";fT();A2();({feature:S2}=xs({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:Ss.enableAutoInsertionOfCellInRow}})),{feature:N2}=xs({teamName:"MakerPortal",owners:["aansu"],description:"Enable the one grid events for form designer",createdOn:"08/21/2024",fallback:{enableOneGridEventsForFormDesigner:Ss.enableOneGridEvents}}),{feature:Sme}=xs({teamName:"MakerPortal",owners:["adekulkarni"],description:"Disables PBI components and cleans them up from the form",createdOn:"01/03/2023",fallback:{enableFallbackFormTemplate:Ss.disablePBIComponents}}),{feature:Nme}=xs({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:Ss.enableAgentResponse}}),{feature:_me,useFeature:Tme}=xs({teamName:"MakerPortal",owners:["aansu"],description:"Enables delayed localization of custom control",createdOn:"06/08/2025",fallback:{enableDelayedLocalizationForCustomControls:Ss.enableDelayedLocalizationForCustomControls}})});var D2=v((Ime,T2)=>{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{}}}),_2=function(){return Fu};Object.setPrototypeOf(_2,Fu);T2.exports=_2});var Zt,Co=L(()=>{"use strict";ht();st();Xt();bu();ue();It();Zt=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=lt.getUniqueIdentifierForControl(t);return!R.IsNullOrUndefined(r)&<.isUnboundFormControlByIdentifier(r)}else return!1}IsAllowedUBCForAvailableOnPhone(){let t=this.getFirstChild(E.formControl);if(t){let n=lt.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=lt.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 Fs,hy=L(()=>{"use strict";Xt();ue();It();Fs=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 I2,Ms,gy=L(()=>{"use strict";st();hy();ue();It();Co();(function(e){e[e.Form=0]="Form",e[e.Cell=1]="Cell",e[e.Tab=2]="Tab",e[e.Control=3]="Control"})(I2||(I2={}));Ms=class extends Zt{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 Fs(r,n.toString()))}}}});var On,Mu=L(()=>{"use strict";ht();Wl();st();oa();ue();It();Tn();On=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 ar,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=(Li.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)===Li.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 ar;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()===gt.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 Us,yy=L(()=>{"use strict";Xt();Ho();Mu();ue();It();Us=class extends On{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 ln.Chart:return ln.Chart;case ln.Grid:return ln.Grid;default:return ln.All}}set chartGridMode(t){this.setParameter(y.chartGridMode,t)}updateChartGridMode(t){t?this.chartGridMode=ln.Chart:this.chartGridMode=this.enableChartPicker?ln.All:ln.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(Ht.dataset)?n[i].getParameters().get(Ht.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 Bs,by=L(()=>{"use strict";Xt();Ho();Mu();ue();Bs=class extends On{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(Ht.value)?n[i].getParameters().get(Ht.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,vy,Ir,Uu=L(()=>{"use strict";O2=Ae(D2());Co();ue();st();ht();gy();Mu();bu();_0();s0();Tn();oa();ws();yy();by();wy();os();vy="_",Ir=class e extends Zt{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 On?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:!sa.dependencyFieldCount.containsKey(this.control.id):!sa.dependencyFieldCount.containsKey(this.control.dataFieldName)}createOnLoadEvent(){this.addEvent(new Ms(this,cu.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&&Zd[i])o=Zd[i].replace(/ /g,vy)+vy;else{o="Control_";let u=new Error("Control class id does not exist or is undefined");(0,O2.trackErrorTrace)(cr,{eventName:`${D_}/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===cn.Grid?(l=new Us(this),l.indicationOfSubgrid=!0):o===cn.Lookup?l=new Bs(this):l=new On(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=lt.getUniqueIdentifierForControl(l);R.IsNullOrUndefined(d)||(lt.getControlDataTypeByControlOrUniqueId(d)===ee.QuickFormCollectionControl||!lt.isUnboundFormControlByIdentifier(d)?o!==cn.Grid&&a&&u!==N.IframeControl&&u!==N.SubgridControl&&u!==N.ReferencePanelSubgridControl&&(l.dataFieldName=a,e.prototype.setProperty.call(l,y.disabled,"false")):(this.rowspan=lt.GetRowSpan(l),(lt.getControlDataTypeByControlOrUniqueId(d)===ee.NotesControl||lt.getControlDataTypeByControlOrUniqueId(d)===ee.TimeLineControl)&&(e.prototype.setProperty.call(l,y.disabled,"false"),l.id=ee.NotesControl)),(lt.getUnboundControlNameFromIdentifier(n)===ee.SubGridControl||lt.getUnboundControlNameFromIdentifier(n)===ee.NotesControl||lt.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(S0.ONE_COLUMN),n=Number(S0.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===oo.ApplicationRequired||a===oo.SystemRequired)&&!o||this.isCellLockedByExternal(t)&&!o)return!0}}return!1}getRequiredLevel(t){return!this.control?.dataFieldName||!this.control?.id||this.IsNewField||!this.control?.ClassId?oo.None:t.getEntityAttributeByName(this.control.dataFieldName)?.requiredLevel?.toString()??oo.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)===vy&&(r++,n=parseInt(t.substr(r,t.length-r),10)),n}}});var qs,Cy=L(()=>{"use strict";Xt();ue();It();qs=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 pa,Ey=L(()=>{"use strict";st();Uu();ue();It();pa=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 Ir(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 VQ(e){switch(e){case la.Left:return ca.Left;case la.Right:return ca.Right;case la.Center:return ca.Center;default:return ca.Left}}function GQ(e){switch(e){case Es.Left:return As.Left;case Es.Top:return As.Top;default:return As.Left}}function P2(e){switch(e){case 1:return 1;case 2:return 11;case 3:return 111;case 4:return 1111;default:return 1}}var WQ,ni,Bu=L(()=>{"use strict";T0();ht();st();Xt();my();Uu();ue();Tn();Co();Ey();WQ=115,ni=class e extends Zt{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=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===je.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),R.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 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 pa(null);if(this.addGrandChild(E.formRows,r),S2.getConfig().enableAutoInsertionOfCellInRow)for(let n=0;n<t;n++){let i=new Ir(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 P2(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=Ue.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)?Ue.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?WQ: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:VQ(this.fieldLabelAlignment),Position:GQ(this.fieldLabelPosition)},Columns:P2(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(Ue.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 Eo,Df=L(()=>{"use strict";ue();It();Bu();Eo=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 ni(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 If,R2=L(()=>{"use strict";ht();ue();Tn();Bu();If=class extends ni{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 Of,k2=L(()=>{"use strict";Df();ue();R2();Of=class extends Eo{addAndIntializeNavBarSection(t,r,n,i){let o=new If(E.formSection,null);return o.initializeNavArea(t,r,i),this.addGrandChildAtIndex(E.formSections,o,n),o}}});var xi,Pf=L(()=>{"use strict";ht();st();Xt();Df();ue();It();Co();xi=class extends Zt{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,go.namePrefix+t.toString()),this.addProperty(y.id,new U(U.NewGuid()).guidString),this.addProperty(y.IsUserDefined,go.IsUserDefined),this.addProperty(y.locklevel,go.LockLevel),this.addProperty(y.showlabel,go.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 Eo(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 ma,Ay=L(()=>{"use strict";ht();ue();It();Tn();k2();Pf();ma=class extends xi{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<cf.FIVE_COLUMN;t++){let r=new Of(this.getChildren(E.formColumns)[0]);r.initializeDefaultProperties(Z_.FiveEqColumn),this.addGrandChild(E.formColumns,r)}}}});function jQ(e){switch(e){case gt.Main:return yo.Main;case gt.QuickCreate:return yo.QuickCreate;case gt.QuickViewForm:return yo.Quick;case gt.Dialog:return yo.Dialog;default:return yo.None}}function HQ(e,t){if(t===gt.Main){if(e)switch(e.toLowerCase()){case"low":return ho.Low;case"highreadonlyvalues":return ho.HighReadOnlyValues;default:return ho.HighWithControls}return ho.Low}}var kf,zQ,Rf,L2=L(()=>{"use strict";sT();kf=Ae(aa());T0();st();Xt();ws();my();ue();Ho();Kg();oa();Uu();ue();Co();Cy();Ay();Pf();zQ="1920";Rf=class e extends Zt{_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 Jd,this._metadataChangeEvent=new ff}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 Ir).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 Ir){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 qs(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,kf.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))?zQ: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===gt.Main?this.setProperty(y.HeaderDensityType,t):this.formType!==gt.Main&&this.headerDensityType&&this.removeProperty(y.HeaderDensityType)}IsMainOrQuickCreateForm(){return this.formType===gt.Main||this.formType===gt.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 xi(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 xi(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===go.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 ma)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 Ir))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 Ir&&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,Ti.EditableGridControl)||N2.getConfig()?.enableOneGridEventsForFormDesigner&&this.cellHasCustomControlWithName(t,Ti.PowerAppsOneGrid)}isCellCanvasAppControl(t){return t?.control?.ClassId.guidString.toUpperCase()===N.CustomControl&&this.cellHasCustomControlWithName(t,Ti.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 ma)){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,kf.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===gt.Main?{HeaderDensity:HQ(this.headerDensityType,this.formType)}:{},InlineEditGridRow:[],InlineQuickForms:[],QuickFormEntities:[],EventHandlers:[],LinkControlSections:[],FormType:jQ(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 Lf,Sy,$2=L(()=>{"use strict";ht();st();ue();It();Co();Lf=class extends Zt{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 Sy(this))}},Sy=class extends re{constructor(t){super(E.formEveryOne,t)}}});var $f,x2=L(()=>{"use strict";ue();It();$f=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 Vs,Ny=L(()=>{"use strict";ue();Bu();Vs=class extends ni{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 qu,F2=L(()=>{"use strict";ue();Ny();qu=class extends Vs{_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 Vu,M2=L(()=>{"use strict";ue();Ny();Vu=class extends Vs{_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 Or,ha=L(()=>{"use strict";ht();Xt();ue();Co();Or=class e extends Zt{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 Gu,U2=L(()=>{"use strict";(function(e){e[e.NavLinkNotAvailable=-1]="NavLinkNotAvailable",e[e.NavLinkIdConflict=-2]="NavLinkIdConflict",e[e.NavBarNotAvailable=-3]="NavBarNotAvailable"})(Gu||(Gu={}))});var xf,B2=L(()=>{"use strict";st();ue();ha();U2();xf=class extends Or{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)?Gu.NavLinkNotAvailable:r.length===1?this.deleteChild(r[0]):Gu.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 xe,KQ,q2,b0e,Gs,_y=L(()=>{"use strict";ht();ue();ha();(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"})(xe||(xe={}));KQ=new Map([[xe.Info,"Info"],[xe.Sales,"Sales"],[xe.Service,"Service"],[xe.Marketing,"Marketing"],[xe.ProcessCenter,"ProcessCenter"]]),q2=new Map([["Info",xe.Info],["Sales",xe.Sales],["Service",xe.Service],["Marketing",xe.Marketing],["ProcessCenter",xe.ProcessCenter]]),b0e=new Map([[xe.Info,9e3],[xe.Sales,9200],[xe.Service,9400],[xe.Marketing,9600],[xe.ProcessCenter,9800],[xe.InternetMarketing,1e4],[xe.Async,10200]]),Gs=class extends Or{constructor(t,r){super(E.formNavBarArea,r)}setDefaultPropertiesByType(t,r,n){this.AreaId=KQ.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 Ws,Ty=L(()=>{"use strict";ue();ha();Ws=class extends Or{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 Ff,V2=L(()=>{"use strict";st();ue();ha();Ff=class extends Or{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 Mf,G2=L(()=>{"use strict";ue();ha();Mf=class extends Or{constructor(t){super(E.formNavBarItem,t)}get Url(){return this.getProperty(y.url)}set Url(t){this.setProperty(y.url,t)}}});var Uf,W2=L(()=>{"use strict";ht();ue();_y();Ty();ha();Uf=class extends Or{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=[xe.Info,xe.Sales,xe.Service,xe.Marketing,xe.ProcessCenter];if(this.navBarAreas){let i=this.navBarAreas?.AllNavBarAreaItems;if(i&&i.length>0){let o=new Set(i.map(a=>q2.get(a.AreaId)));n=n.filter(a=>!o.has(a))}}else{let i=new Ws(E.formNavBarAreas,this);i.isTransient=!0,this.addChild(i)}return n.length>0?(n.forEach(i=>{let o=new Gs(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(a0,!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 z2={};Jr(z2,{ControlType:()=>cn,DeserializationService:()=>Oy,DeserializationServiceScope:()=>Iy,DeserializedFormElementNode:()=>Pr});var Dy,Pr,Iy,cn,Oy,wy=L(()=>{"use strict";Dy=Ae(aa());ht();st();Xt();ws();s0();oa();O_();oT();bu();L2();Uu();Df();Mu();hy();ue();ue();$2();It();Tn();gy();x2();F2();yy();by();M2();Cy();Ey();Bu();Pf();B2();_y();Ty();V2();G2();W2();Pr=class extends re{constructor(t,r){super(t,r)}insertProperty(t,r){this.addProperty(t,r)}insertChild(t){this.addChild(t)}},Iy="DeserializationService";(function(e){e.Grid="Grid",e.Lookup="Lookup",e.Base="Base"})(cn||(cn={}));Oy=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,Dy.trackErrorTrace)(cr,{eventName:Iy,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!==gt.Dialog&&this.appendDefaultDisplayCondition(f),f}upsertFieldCount(t,r){let n=sa.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 Rf(r,n,i,o,a,s,l,u,c);return this.populateElementProperties(d,t.attributes),this.populateElementChildren(d,t.childNodes),s===gt.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 Vu(r,!0):new qu(r,!0);Pr.prototype.insertProperty.call(i,y.id,"{"+U.NewGuid()+"}"),Pr.prototype.insertProperty.call(i,y.Fieldlabelposition,"Top"),Pr.prototype.insertProperty.call(i,y.columnName,Ue.MarginalControlColumns),Pr.prototype.insertProperty.call(i,y.LabelWidth,Ue.LabelWidth),Pr.prototype.insertProperty.call(i,y.Fieldlabelalignment,"Left");let o=null,a=new pa(o);for(let s=0;s<i.maxColumns;s++){let l=new Ir(a);Pr.prototype.insertProperty.call(l,y.id,"{"+U.NewGuid()+"}"),l.setDisplayName(q.EmptyString,this.lcid),Pr.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 Pr(`<${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,Dy.trackErrorTrace)(cr,{eventName:Iy,eventData:{error:n}}),new Error(n)}for(let n=0;n<r.length;n++){let i=r.item(n);i&&(Pr.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&&Pr.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 xi(r);case E.formColumn:return new Eo(r);case E.formHeader:return new Vu(r,!1);case E.formFooter:return new qu(r,!1);case E.formSection:return new ni(E.formSection,r);case E.formRow:return new pa(r);case E.formCell:return new Ir(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=cn.Grid;else if(l.name===y.classid&&l.value?.toLocaleUpperCase()===`{${N.LookupControl}}`)o=cn.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=cn.Lookup)}return o===cn.Grid?new Us(r):o===cn.Lookup?new Bs(r):new On(r);case E.formEvent:return new Ms(r,q.EmptyString);case E.dependency:return this.populateDependencyTable(t),new Fs(r,q.EmptyString);case E.Handler:let a=[];return new $f(a,r);case E.formNavigation:return new Uf(t.nodeName,r);case E.formNavBarArea:return new Gs(t.nodeName,r);case E.formNavBarAreas:return new Ws(t.nodeName,r);case E.formNavBar:return new xf(r);case E.formNavBarByRelationshipItem:return new Ff(r);case E.formNavBarItem:return new Mf(r);case E.formDisplayConditions:return new Lf(r);case E.library:return new qs(r,q.EmptyString,q.EmptyString);case E.controlDescription:return new ef(r);case E.customControl:return this.populateCustomControlConfigurationId(t),new df(r);default:return new Pr(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,Zn.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);lt.CustomControlIdMap.upsert(l,o);break}}break}}}}});var j2={};Jr(j2,{SerializationService:()=>Py,SerializationServiceScope:()=>JQ,SerializedFormElementNode:()=>zs});var JQ,zs,Py,H2=L(()=>{"use strict";Xt();It();Tn();Ay();JQ="SerializationService",zs=class extends re{fetchNodeName(){return this.getNodeName()}enumerateProperties(){return this.getAllProperties()}enumerateChildren(){return this.getAllChildren()}},Py=class{langCode;constructor(t){this.langCode=t}serializeFormXmlNode(t){let r=zs.prototype.fetchNodeName.call(t);if(r.charAt(0)===Li.StartTag)return q.EscapeXml(r.substr(1),!1);if(t.isTransient&&!t.isDirty())return q.EmptyString;let n=zs.prototype.enumerateProperties.call(t),i=zs.prototype.enumerateChildren.call(t);if(!(t instanceof ma)){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 $y=v(js=>{"use strict";Object.defineProperty(js,"__esModule",{value:!0});js.completeRecordAsStored=js.completeLabelsAsStored=void 0;var Ry=uo(),YQ="E7A81278-8635-4D9E-8D4D-59480B391C5B",QQ=new Set(["tab","section","cell"]);function Pn(e){let t=[];for(let r=e.firstChild;r;r=r.nextSibling)r.nodeType===1&&t.push(r);return t}function Ao(e,t){return Pn(e).find(r=>r.tagName===t)}function J2(e,t){return e.length===t.length&&e.every((r,n)=>r.tagName===t[n].tagName)}function ky(e){let t=Ao(e,"control");return t?(t.getAttribute("datafieldname")||"")!==""?!0:(t.getAttribute("classid")||"").replace(/[{}]/g,"").toUpperCase()===YQ:!1}function Ly(e,t){var r,n;let i=((r=Ao(e,"control"))===null||r===void 0?void 0:r.getAttribute("id"))||"";return i!==""&&i===(((n=Ao(t,"control"))===null||n===void 0?void 0:n.getAttribute("id"))||"")}function XQ(e,t){if(Ao(e,"labels"))return;let r=Pn(e),n=Pn(t),i=n[0];if(!i||i.tagName!=="labels"||n.length!==r.length+1||!J2(r,n.slice(1)))return;let o=Pn(i);if(!(o.length===0||o.some(s=>s.tagName!=="label"||!s.hasAttribute("description")||!s.hasAttribute("languagecode"))||!(e.tagName==="cell"&&ky(e)&&Ly(e,t))&&o.some(s=>s.getAttribute("description")!=="")))return i}function ZQ(e,t){let r=eX(e.ownerDocument,t),n=Pn(e)[0];n?e.insertBefore(r,n):e.appendChild(r)}function eX(e,t){let r=e.createElement("labels");for(let n of Pn(t))r.appendChild(Y2(e,n));return r}function Y2(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 K2(e,t){let r=Ao(e,"labels");return r?Pn(r).find(n=>n.tagName==="label"&&n.getAttribute("languagecode")===String(t)):void 0}function tX(e,t,r){if(e.tagName!=="cell"||!ky(e)||!Ly(e,t))return!1;let n=K2(e,r),i=K2(t,r),o=i?.getAttribute("description")||"";return!n||!n.hasAttribute("description")||(n.getAttribute("description")||"")!==""||o===""?!1:(n.setAttribute("description",o),!0)}function rX(e,t){if(e.tagName!=="cell"||!ky(e)||!Ly(e,t))return;let r=Ao(e,"labels"),n=Ao(t,"labels");if(!r||!n)return;let i=Pn(r),o=Pn(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 Q2(e,t,r,n){if(e.tagName!==t.tagName)return;if(QQ.has(e.tagName)){let a=XQ(e,t);a&&(ZQ(e,a),n.changed=!0),tX(e,t,r)&&(n.changed=!0);let s=rX(e,t),l=Ao(e,"labels");if(s&&l){for(let{label:u,before:c}of s){let d=Y2(e.ownerDocument,u);c?l.insertBefore(d,c):l.appendChild(d)}n.changed=!0}}let i=Pn(e),o=Pn(t);J2(i,o)&&i.forEach((a,s)=>Q2(a,o[s],r,n))}function X2(e,t,r){if(e===t)return e;let n,i;try{n=(0,Ry.parseXmlRoot)(e,""),i=(0,Ry.parseXmlRoot)(t,"")}catch{return e}let o={changed:!1};return Q2(n,i,r,o),o.changed?(0,Ry.serializeNode)(n):e}js.completeLabelsAsStored=X2;function nX(e,t,r){let n=e?.formxml,i=t?.formxml;if(typeof n!="string"||typeof i!="string")return e;let o=X2(n,i,r);return o===n?e:{...e,formxml:o}}js.completeRecordAsStored=nX});var bk=v(ce=>{"use strict";Object.defineProperty(ce,"__esModule",{value:!0});ce.pcfReadIssues=ce.pcfBindingIssues=ce.commitPcfState=ce.mayCommitPcfState=ce.reconcilePcfDescriptions=ce.customControlNeeds=ce.mintPcfIdentity=ce.planPcfBinding=ce.projectPcfBindings=ce.supportsPcfFormType=ce.storedBindingOf=ce.hasCustomControl=ce.sameAsStored=ce.readPcfDescription=ce.newPcfDescription=ce.editorText=ce.nativeClassFor=ce.pcfEntryLayout=void 0;var iX=(bu(),Br(aT)),oX=Q(),Z2=pt(),V=Dd(),aX=Hh(),Ee=rn(),Ui=["web","phone","tablet"],Wu={web:"2",phone:"0",tablet:"1"},ik=new Map([["2","web"],["0","phone"],["1","tablet"]]),sX=["phone","web","tablet"];function qf(e){let t=new Set(e),r=sX.filter(n=>!t.has(n));return{defaults:r.length===0?[null]:r,named:Ui.filter(n=>t.has(n))}}ce.pcfEntryLayout=qf;function dr(e){return Array.isArray(e)?e:[]}function ut(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function zu(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Fy(e){return{n:`<${e}`,a:[],c:[]}}function ok(e){return typeof e?.n=="string"&&e.n.startsWith("<")}function ek(e){let t=dr(e.c);return t.length===1&&ok(t[0])&&(0,V.rawText)(e)!==""?(0,V.rawText)(e):void 0}function fn(e,t){return JSON.stringify(e)===JSON.stringify(t)}function ak(e){return`{${e.replace(/^\{|\}$/g,"").toUpperCase()}}`}function My(e){try{let t=(0,iX.mapFieldTypeToControl)(e.attributeTypeName,e.format);return t?ak(String(t)):void 0}catch{return}}ce.nativeClassFor=My;var Uy=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}]]),sk=new Set(["TwoOptions","Boolean"]),lk=new Set(["SingleLine.Text","SingleLine.TextArea","SingleLine.Email","SingleLine.Phone","SingleLine.URL","SingleLine.Ticker","Multiple"]),lX=new Map([...[...lk].map(e=>[e,100]),["SingleLine.TextArea",2e3],["Multiple",1048576]]),uX=/^[A-Za-z_][A-Za-z0-9_.-]*$/;function uk(e){return uX.test(e)&&e!=="__proto__"}function By(e){return e!==void 0&&(e==="Enum"||Uy.has(e)||sk.has(e)||lk.has(e))}function ck(e){return typeof e=="number"?e:e!==""&&!Number.isNaN(Number(e))?Number(e):void 0}function ju(e,t){let r=e!==void 0?Uy.get(e):void 0;if(r&&typeof t!="boolean"){let n=ck(t);if(n!==void 0)return n.toFixed(r.digits)}return typeof t=="boolean"?t?"true":"false":String(t)}ce.editorText=ju;function cX(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"&&zu(r,a)?s=ju(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:[Fy(s)]})}return i}function dk(e,t,r,n,i){var o,a;let s=(o=n.formFactors)!==null&&o!==void 0?o:Ui.filter(d=>qy(i).has(d)),l=qf(s),u=cX(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",Wu[d]]],c:[{n:"parameters",a:[],c:[{n:"datafieldname",a:[],c:[Fy(t)]}]}]})),...l.named.map(d=>({n:"customControl",a:[["name",n.name],["formFactor",Wu[d]]],c:[{n:"parameters",a:[],c:c(u)}]}))]}}ce.newPcfDescription=dk;function qy(e){return new Set(Ui.filter(t=>e.availableOn[t]))}function Bf(e){var t;let r=dr(e.c);if(r.length!==1||((t=r[0])===null||t===void 0?void 0:t.n)!=="parameters"||dr(r[0].a).length>0)return;let n=dr(r[0].c);return n.every(i=>ut(i)&&!ok(i))?n:void 0}function ga(e){let t=dr(e?.c);if(t.length===0||!t.every(p=>ut(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=dr(p.a),g=h.length===2?ik.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=qf(o);if(!fn(a.named,o)||i==="")return;let s=Bf(n[0]);if(!s||!n.every(p=>fn(Bf(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",Wu[h]]],b=Bf(l[p]),w=b?.length===1&&b[0].n==="datafieldname"&&dr(b[0].a).length===0?ek(b[0]):void 0;if(!u||!fn(dr(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=dr(p.a),g=ek(p),b=h.map(w=>w[0]);if(g===void 0||!uk(p.n)||zu(d,p.n)||p.n===m)return;if((0,V.rawAttr)(p,"static")===void 0){if(m!==void 0||g!==c||!(b.length===0||fn(b,["type"])))return;m=p.n;continue}if((0,V.rawAttr)(p,"static")!=="true"||!(fn(b,["static"])||fn(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===Ui.length?{}:{formFactors:o}},fieldName:c,nativeClass:u,parameterTypes:f,boundProperty:m}}ce.readPcfDescription=ga;function fk(e,t,r){return e===t?!0:typeof e!="string"&&(t===String(e)||t===ju(r,e))}function pk(e){let t=e.formFactors;return t===void 0?[...Ui]:Array.isArray(t)?Ui.filter(r=>t.includes(r)):[]}function xy(e,t){var r,n,i;if(e.name!==t.binding.name||!fn(pk(e),(r=t.binding.formFactors)!==null&&r!==void 0?r:Ui))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=>zu(a,l)&&fk(o[l],a[l],t.parameterTypes[l]))}ce.sameAsStored=xy;function yt(e){return ut(e)&&e.customControl!==void 0}ce.hasCustomControl=yt;function Mi(e,t){var r;return t?dr((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 Vy(e,t){let r=Mi(e.bag,(0,V.controlUniqueId)(t));return r.length===1?ga(r[0]):void 0}ce.storedBindingOf=Vy;function Gy(e){let t=(0,V.effectiveFormType)(e);return t==="Main"||t==="QuickCreate"}ce.supportsPcfFormType=Gy;function dX(e){if(!Gy(e))return;let t=(0,V.controlUniqueIds)(e);for(let{cell:r}of(0,V.typedCellSites)(e)){let n=r.control;if(!ut(n)||!n.fieldName||!Fi(n.classId)||t.get((0,V.controlUniqueId)(n))!==1)continue;let i=Vy(e,n);i&&i.fieldName===n.fieldName&&(n.customControl=JSON.parse(JSON.stringify(i.binding)))}}ce.projectPcfBindings=dX;function Fi(e){return typeof e=="string"&&e.replace(/^\{|\}$/g,"").toUpperCase()===V.CUSTOM_CONTROL_CLASS_ID}var dn=(e,t)=>({kind:"refused",rule:e,message:t});function fX(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)&&!Fi(e)}function tk(e,t,r){var n,i;let o=ga(r);if(!o)return dn("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 dn("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 dn("pcf-binding-control-swap",`the binding uses "${o.binding.name}": to use another control, remove customControl, push, then add it`);let a=ut(t.parameters)?t.parameters:{},s=(n=o.binding.parameters)!==null&&n!==void 0?n:{},l=Object.keys(a).sort();if(!fn(l,Object.keys(s).sort()))return dn("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=>!fk(a[g],s[g],o.parameterTypes[g])),c=u.find(g=>ju(o.parameterTypes[g],a[g]).trim()==="");if(c!==void 0)return dn("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=pk(t),f=(i=o.binding.formFactors)!==null&&i!==void 0?i:[...Ui],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=>!By(o.parameterTypes[g]));if(h!==void 0){let g=o.parameterTypes[h];return dn("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)&&!fX(o.nativeClass)?dn("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 pX(e,t){return t&&(0,V.typedCellSites)(e).find(({cell:n})=>yt(n.control)&&(0,V.controlUniqueId)(n.control)===t)?{descriptions:Mi(e.bag,t)}:void 0}function mk(e,t){let r=new Map,n=mX(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:yX(u),uid:(0,V.controlUniqueId)(c),bound:yt(c)});for(let{cell:u}of(0,V.typedCellSites)(e)){let c=u.control;ut(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(!ut(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&&rk(D.control)&&r.set(D.control,nk(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)&&rk(D.control)),O=f.filter(D=>m.includes(D));if(S.length===0||O.length===0&&b.length===0)continue;let k=[...O,...b],I=O.length===1&&S.length===1&&m.length===1?nk(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 ${k.map(D=>`{${D.uid}}`).join(", ")} no longer ${k.length===1?"names":"name"} a control: which control held ${k.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 mX(e){let t=(0,V.controlUniqueIds)(e),r=new Map;for(let{cell:i}of(0,V.typedCellSites)(e)){let o=ut(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||yt(a)||o>1)&&n.add(i)}return n}function rk(e){return yt(e)||e.genPage===void 0&&Fi((0,V.effectiveClassId)(e))}function hX(e,t){let r=o=>(0,V.typedCellSites)(o).flatMap(({cell:a,pointer:s})=>{let l=a.control;if(!ut(l)||yt(l)||l.genPage!==void 0||!Fi((0,V.effectiveClassId)(l)))return[];let u=(0,V.controlUniqueId)(l);return u===""||Mi(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 gX="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 nk(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 yX(e){let t=typeof e.id=="string"?e.id.trim():"";return(0,V.normGuid)(t)||t.toLowerCase()}function Hu(e,t,r,n){let i=t.customControl,o=(0,V.controlUniqueId)(t),a=Mi(e.bag,o),s=r?mk(e,r).get(t):void 0;if(s!==void 0)return dn("pcf-binding-unique-id",s);let l=r?pX(r,o):void 0;if(l){let c=l.descriptions,d=c.length===1?ga(c[0]):void 0;if(d&&d.fieldName!==t.fieldName)return dn("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&&fn(c[0],a[0]))return tk(t,i,a[0]);let f=a.length===1?ga(a[0]):void 0;return d&&f&&f.fieldName===t.fieldName&&xy(i,d)&&xy(i,f)?{kind:"unchanged"}:dn("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 dn("pcf-binding-other-control","the control already has a description the SDK cannot read as a binding; adding would replace it");let u=tk(t,i,a[0]);return n&&(u.kind==="edit"||u.kind==="unchanged")?u.kind==="unchanged"?u:dn("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}ce.planPcfBinding=Hu;function hk(e){return e.kind==="edit"&&(e.changed.length>0||e.added.length>0)}function bX(e){let t=n=>yt(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,Z2.newId)()),n.id||(n.id=(0,Z2.newId)()),(0,V.authoredUniqueId)(i)===void 0&&(0,V.setUniqueId)(i)}return r}ce.mintPcfIdentity=bX;function vX(e,t){let r=new Set,n=new Set;for(let{cell:i}of(0,V.typedCellSites)(e)){let o=i.control;if(!yt(o)||!ut(o.customControl))continue;let a=o.customControl.name;if(typeof a!="string"||a===""||typeof o.fieldName!="string"||!o.fieldName)continue;let s=Hu(e,o,t,!0);s.kind==="new"?(r.add(a),n.add(o.fieldName)):hk(s)&&r.add(a)}return{controls:[...r],columns:[...n],...n.size>0&&(0,V.effectiveFormType)(e)==="QuickCreate"?{requireCreateEligibility:!0}:{}}}ce.customControlNeeds=vX;function wX(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(!yt(p)||!ut(p.customControl))continue;let h=(0,V.controlUniqueId)(p);h&&Mi(u,h).length>0&&c.set(p,{plan:Hu(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=ut(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(!yt(g))continue;let b=(0,V.controlUniqueId)(g),w=Mi(t.bag,b),C=Mi(u,b);if(w.length!==1||C.length!==1||!fn(w[0],C[0])||!ga(C[0]))continue;let S=p.get(b);if(S&&!yt(S)){if(((n=f.get(b))!==null&&n!==void 0?n:0)>1)continue;let O=(o=(i=ga(C[0]))===null||i===void 0?void 0:i.nativeClass)!==null&&o!==void 0?o:"";S.classId=O.replace(/^\{|\}$/g,"").toUpperCase(),CX(S,"uniqueid"),m.add(b)}else!S&&!f.has(b)&&m.add(b)}m.size>0&&(d.node.c=dr(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(!yt(m)||!ut(m.customControl))continue;Fi(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 oX.ValidationError("form",e.id,[(0,Ee.issue)(h.pointer,h.plan.rule,h.plan.message)]);h.plan.kind==="edit"&&EX(h.plan,m.customControl);continue}let g=r?.control(m.customControl.name),b=r?.column(e.entityLogicalName,m.fieldName),w=b?.kind==="found"?My(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=dr((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(dk(S,m.fieldName,w,m.customControl,g.value))}}ce.reconcilePcfDescriptions=wX;function CX(e,t){ut(e.bag)&&(e.bag.a=dr(e.bag.a).filter(r=>r[0]!==t))}function EX(e,t){var r,n;let i=dr(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=Bf(g))!==null&&n!==void 0?n:[])e.changed.includes(b.n)&&(b.c=[Fy(ju(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=ik.get(w))!==null&&b!==void 0?b:null},d=(0,V.rawAttr)(a[0],"id"),f=(0,V.rawAttr)(s[0],"name"),m=qf(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",Wu[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",Wu[g]]],w});e.description.c=[...p,...h]}function AX(e){return(0,V.typedCellSites)(e).some(({cell:t})=>yt(t.control))}ce.mayCommitPcfState=AX;function SX(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(!yt(a))continue;let s=Vy(n,a);if(!s||s.fieldName!==a.fieldName)continue;let l=t(V.CUSTOM_CONTROL_CLASS_ID),u=dr((r=a.bag)===null||r===void 0?void 0:r.a).find(c=>c[0]==="classid");(!Fi(a.classId)||a.type!==l||u!==void 0&&!Fi(u[1])||!fn(a.customControl,s.binding))&&(Fi(a.classId)||(a.classId=V.CUSTOM_CONTROL_CLASS_ID),a.type=l,u&&!Fi(u[1])&&(u[1]=ak(V.CUSTOM_CONTROL_CLASS_ID)),a.customControl=JSON.parse(JSON.stringify(s.binding)),i=!0)}return i?n:e}ce.commitPcfState=SX;var NX=new Set(["name","parameters","formFactors"]);function _X(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;yt(s)&&DX(e,s,`${a}/control`,i,n,t,r?.atPush===!0)}return t&&IX(e,t,n),n}ce.pcfBindingIssues=_X;function TX(e,t,r){let n=r.length;if(!ut(e))return r.push((0,Ee.issue)(t,"pcf-binding-shape","customControl must be an object")),!1;for(let i of Object.keys(e))NX.has(i)||r.push((0,Ee.issue)(`${t}/${i}`,"pcf-binding-unknown-key",`customControl has no "${i}"`));if((typeof e.name!="string"||e.name.trim()==="")&&r.push((0,Ee.issue)(`${t}/name`,"pcf-binding-shape","name must be the control's non-empty customcontrols name")),e.parameters!==void 0)if(!ut(e.parameters))r.push((0,Ee.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,Ee.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"&&Ui.includes(a))&&new Set(i).size===i.length||r.push((0,Ee.issue)(`${t}/formFactors`,"pcf-binding-shape","formFactors must be distinct 'web', 'phone' and 'tablet', at least one"))}return r.length===n}function DX(e,t,r,n,i,o,a){var s;let l=`${r}/customControl`,u=TX(t.customControl,l,i);t.fieldName||i.push((0,Ee.issue)(l,"pcf-binding-unbound","a PCF binding needs a control bound to a column (fieldName)")),t.genPage!==void 0&&i.push((0,Ee.issue)(l,"pcf-binding-with-genpage","a control cannot embed a page and bind a PCF control")),Gy(e)||i.push((0,Ee.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,Ee.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,Ee.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,Ee.issue)(`${r}/bag`,"pcf-binding-unique-id","another control carries the same uniqueid")),!u)return;let f=Hu(e,t,o,a);f.kind==="refused"&&i.push((0,Ee.issue)(l,f.rule,f.message))}function IX(e,t,r){var n;let i=new Map,o=mk(e,t);for(let{cell:l,pointer:u}of(0,V.typedCellSites)(e)){let c=ut(l.control)?(0,V.controlUniqueId)(l.control):"";if(c&&!i.has(c)&&i.set(c,{control:l.control,pointer:`${u}/control`}),ut(l.control)&&!yt(l.control)){let d=o.get(l.control);d!==void 0&&r.push((0,Ee.issue)(`${u}/control`,"pcf-binding-unique-id",d))}}let a=(0,V.controlUniqueIds)(e);for(let{cell:l}of(0,V.typedCellSites)(t)){if(!yt(l.control))continue;let u=(0,V.controlUniqueId)(l.control),c=i.get(u);!c||yt(c.control)||(((n=a.get(u))!==null&&n!==void 0?n:0)>1?r.push((0,Ee.issue)(c.pointer,"pcf-binding-unique-id","another control carries this binding\u2019s uniqueid; removing the binding would delete its description too")):fn(Mi(t.bag,u),Mi(e.bag,u))?c.control.fieldName!==l.control.fieldName&&r.push((0,Ee.issue)(c.pointer,"pcf-binding-rebind","remove the binding, push, then bind the new column")):r.push((0,Ee.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 hX(e,t))s.has(l)||r.push((0,Ee.issue)(l,"pcf-binding-unique-id",gX))}var OX=new Set(["Form.Card"]),PX="MscrmControls.ModelForm.ModelFormControl";function gk(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=>!uk(s));if(o!==void 0)return`the property name "${o}" cannot be written as an element`;if(t===PX||n.some(s=>s.defaultType!==void 0&&OX.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"&&!By(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 RX(e){return e.ofType!==null?[e.ofType]:e.ofTypeGroup}function yk(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?Uy.get(r):void 0;if(n){let o=typeof t=="boolean"?void 0:ck(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&&sk.has(r))return t===!0||t===!1||t==="true"||t==="false"?void 0:"must be true or false";let i=r!==void 0?lX.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 kX(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(!yt(d)||!d.fieldName)continue;let f=d.customControl;if(!ut(f)||typeof f.name!="string")continue;let m=`${c}/control/customControl`,p=Hu(e,d,r,!0);if(p.kind==="edit"){hk(p)&&xX(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,Ee.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=gk(h.value,f.name);if(b){l.push((0,Ee.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,aX.manifestTypesForColumn)(C.attributeTypeName,C.format,C.formatName))!==null&&a!==void 0?a:[]:[];C!==void 0&&!C.isPrimaryId&&C.isValidForForm&&My(C)!==void 0&&RX(w).some(x=>S.includes(x))?(0,V.effectiveFormType)(e)==="QuickCreate"&&C?.isValidForCreate!==!0&&l.push((0,Ee.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,Ee.issue)(m,"pcf-binding-incompatible-column",`"${f.name}" cannot be bound to "${d.fieldName}"`));let k=new Map(h.value.properties.filter(x=>x.usage==="input").map(x=>[x.name,x])),I=ut(f.parameters)?f.parameters:{};for(let[x,K]of Object.entries(I)){let Oe=k.get(x);if(!Oe){l.push((0,Ee.issue)(`${m}/parameters/${x}`,"pcf-binding-unknown-parameter",`"${f.name}" has no input "${x}"`));continue}let Vt=yk(Oe,K);Vt&&l.push((0,Ee.issue)(`${m}/parameters/${x}`,"pcf-binding-parameter-value",`"${x}" ${Vt}`))}for(let x of k.values())x.required&&!zu(I,x.name)&&!x.defaultValue&&l.push((0,Ee.issue)(`${m}/parameters`,"pcf-binding-missing-parameter",`"${x.name}" is required`));let D=qy(h.value),P=Array.isArray(f.formFactors)?f.formFactors:void 0;(P?P.some(x=>!D.has(x)):D.size===0)&&l.push((0,Ee.issue)(`${m}/formFactors`,"pcf-binding-form-factor",`"${f.name}" is available on ${D.size===0?"no form factor":[...D].join(", ")}`))}return s}ce.pcfReadIssues=kX;function LX(e,t){return t===void 0||!By(t)?!1:e.ofType!==null?e.ofType===t:e.ofTypeGroup.includes(t)}function $X(e,t,r){var n,i;let o=gk(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&&!zu(s,d.name));return c?`it now requires "${c.name}", which the binding does not store`:void 0}function xX(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,Ee.issue)(`${r}/name`,"PCF_CONTROL_NOT_FOUND",`no single installed control is named "${t.name}" (${u.kind})`));return}let c=$X(u.value,t.name,e.stored);if(c){l.push((0,Ee.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];LX(d.get(h),g)||l.push((0,Ee.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=yk(d.get(h),m[h],e.stored.parameterTypes[h]);g&&l.push((0,Ee.issue)(`${r}/parameters/${h}`,"pcf-binding-parameter-value",`"${h}" ${g}`))}let p=qy(u.value);e.added.some(h=>!p.has(h))&&l.push((0,Ee.issue)(`${r}/formFactors`,"pcf-binding-form-factor",`"${t.name}" is available on ${p.size===0?"no form factor":[...p].join(", ")}`))}});var Lk=v(kr=>{"use strict";Object.defineProperty(kr,"__esModule",{value:!0});kr.classIdForAttributeType=kr.QUICK_VIEW_CLASS_ID=kr.NOTES_CLASS_ID=kr.SUBGRID_CLASS_ID=kr.formRegistration=kr.FormAdapter=void 0;var Bi=(ht(),Br(C_)),vk=(st(),Br(E_)),FX=(It(),Br(S_)),bt=(ue(),Br(A_)),rt=(oa(),Br(N_)),MX=(wy(),Br(z2)),UX=(H2(),Br(j2)),vt=so(),wk=Qr(),Rr=rn(),BX=_g(),Ks=pt(),qX=$y(),er=Dd(),ii=bk(),Hs=Q(),Jy=le(),Wy=lo(),_k=Jo(),VX={[bt.FormType.Main]:"Main",[bt.FormType.QuickCreate]:"QuickCreate",[bt.FormType.QuickViewForm]:"QuickView",[bt.FormType.Card]:"Card"},Vf={Main:bt.FormType.Main,QuickCreate:bt.FormType.QuickCreate,QuickView:bt.FormType.QuickViewForm,Card:bt.FormType.Card},GX=new Map(Object.entries(rt.ControlClassId).map(([e,t])=>[String(t).toUpperCase(),e]));function Yy(e){var t;return e&&(t=GX.get(e.toUpperCase()))!==null&&t!==void 0?t:"Unknown"}function Ku(e){return e.getAllProperties().map(t=>[t.key,t.value])}function ya(e){let t=new Map;for(let r of e.getAllProperties())t.has(r.key)||t.set(r.key,r.value);return t}function Tk(e,t){return e.getAllChildren().find(r=>r.getNodeName()===t)}function Qy(e,t){var r,n;let i=Tk(e,"labels");if(!i)return"";let o=i.getAllChildren().filter(s=>s.getNodeName()==="label"),a=(r=o.find(s=>ya(s).get("languagecode")===String(t)))!==null&&r!==void 0?r:o[0];return a&&(n=ya(a).get("description"))!==null&&n!==void 0?n:""}function WX(e){let t=Tk(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 Dk(e){return/^1+$/.test(e)&&e.length>=1&&e.length<=4?e.length:1}function zy(e){let t=Math.min(Math.max(Math.trunc(e),1),4);return"1".repeat(t)}function Ju(e){return String(e??"").replace(/[{}]/g,"")}function jy(e){return`{${Ju(e)}}`}function Hy(e,t){if(e===void 0||e==="")return t;let r=Number(e);return Number.isNaN(r)?t:r}function Wf(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,vt.rawFromNode)(u)})}),i<0)return{modeled:[],bag:{a:Ku(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,vt.rawFromNode)(u)})}),{modeled:s,bag:{a:Ku(e),c:o,w:{n:a.getNodeName(),a:Ku(a),c:l}}}}function Ik(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,vt.rawFromNode)(o)})}),{modeled:n,bag:{a:Ku(e),c:i}}}function Ck(e,t){let{modeled:r,bag:n}=Wf(e,"tabs","tab");return{tabs:r.map(i=>zX(i,t)),bag:n}}function zX(e,t){var r,n;let i=ya(e),{modeled:o,bag:a}=Wf(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:Qy(e,t),expanded:i.get("expanded")==="true",visible:i.has("visible")?i.get("visible")==="true":!0,columns:o.map(s=>jX(s,t)),bag:a}}function jX(e,t){let r=ya(e),{modeled:n,bag:i}=Wf(e,"sections","section");return{width:r.get("width"),sections:n.map(o=>HX(o,t)),bag:i}}function HX(e,t){var r,n,i;let o=ya(e),{modeled:a,bag:s}=Wf(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:Qy(e,t),visible:o.has("visible")?o.get("visible")==="true":!0,showLabel:o.get("showlabel")==="true",columns:Dk((i=o.get("columns"))!==null&&i!==void 0?i:"1"),rows:a.map(l=>KX(l,t)),bag:s}}function KX(e,t){let{modeled:r,bag:n}=Ik(e,"cell",!1);return{cells:r.map(i=>JX(i,t)),bag:n}}function JX(e,t){var r;let n=ya(e),{modeled:i,bag:o}=Ik(e,"control",!0),a=Qy(e,t),s=n.get("showlabel")==="true",l=i[0]?YX(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:Hy(n.get("colspan"),1),rowspan:Hy(n.get("rowspan"),1),control:l,bag:o}}function YX(e,t,r){var n,i;let o=ya(e),a=Ju((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:Yy(a),isRequired:o.get("isrequired")==="true",isReadOnly:o.get("disabled")==="true",label:t,showLabel:r,parameters:WX(e),bag:{a:Ku(e),c:e.getAllChildren().map((l,u)=>({i:u,node:(0,vt.rawFromNode)(l)}))}}}function _o(e){return e.a.length===0&&e.c.length===0&&!e.w}function Ok(e,t){let r=e.a.find(n=>n[0]===t);return r?r[1]:void 0}function ba(e,t){var r;let n=new Set(e.a.map(a=>a[0])),i=_o(e),o=[];for(let a of t)if(n.has(a.key)){let s=(r=Ok(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,vt.mergeAttrs)(e.a,o)}var So=(e,t)=>({key:e,matches:r=>r===t,render:()=>t,absentDefault:""}),No=(e,t,r=!1)=>({key:e,matches:n=>n==="true"===t,render:()=>String(t),absentDefault:String(r)}),Ek=(e,t,r=1)=>({key:e,matches:n=>Hy(n,r)===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 Ky(e){return{n:"parameters",a:[],c:Object.keys(e).map(t=>{var r;return{n:(0,Jy.assertXmlName)(t,"Form control parameter name"),a:[],c:[{n:`<${(r=e[t])!==null&&r!==void 0?r:""}`,a:[],c:[]}]}})}}function QX(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 XX(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 Zy(e,t,r){let n=e.c.findIndex(o=>o.node.n==="labels");if(n<0){if(!t||_o(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(QX(e.c[n].node,r)===t)return e;let i=XX(e.c[n].node,t,r);return{...e,c:e.c.map((o,a)=>a===n?{...o,node:i}:o)}}function ZX(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 eZ(e,t){let r=Object.keys(e),n=Object.keys(t);return r.length===n.length&&r.every(i=>e[i]===t[i])}function tZ(e,t){return e.a.some(r=>r[0]===t)?{...e,a:e.a.filter(r=>r[0]!==t)}:e}function rZ(e,t){let r=e.c.findIndex(i=>i.node.n==="parameters");if(r<0){if(Object.keys(t).length===0||_o(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:Ky(t)}]}}if(eZ(ZX(e.c[r].node),t))return e;let n=Ky(t);return{...e,c:e.c.map((i,o)=>o===r?{...i,node:n}:i)}}function zf(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,vt.spliceChildren)(e.w.c,r)};return(0,vt.spliceChildren)(e.c,[a])}let i=n(),o={n:t,a:[],c:r};return e.c.length===0?[...i,o]:(0,vt.spliceChildren)(e.c,[...i,o])}function nZ(e,t){let r=e.tabs.map(n=>iZ(n,t));return{n:"form",a:ba(e.bag,[]),c:e.tabs.length===0&&_o(e.bag)?[]:zf(e.bag,"tabs",r,()=>[])}}function Pk(e,t,r){return t&&!e.c.some(n=>n.node.n==="labels")?[Xy(t,r)]:[]}function iZ(e,t){let r=[So("id",e.id),So("name",e.name),No("expanded",e.expanded),No("visible",e.visible,!0)],n=e.columns.map(o=>oZ(o,t)),i=Zy(e.bag,e.label,t);return{n:"tab",a:ba(i,r),c:zf(i,"columns",n,()=>Pk(i,e.label,t))}}function oZ(e,t){let r=e.width!==void 0?[So("width",e.width)]:[],n=e.sections.map(i=>aZ(i,t));return{n:"column",a:ba(e.bag,r),c:zf(e.bag,"sections",n,()=>[])}}function aZ(e,t){let r=[So("id",e.id),So("name",e.name),No("showlabel",e.showLabel),No("visible",e.visible,!0),{key:"columns",matches:o=>Dk(o)===e.columns,render:()=>zy(e.columns),absentDefault:zy(1)}],n=e.rows.map(o=>sZ(o,t)),i=Zy(e.bag,e.label,t);return{n:"section",a:ba(i,r),c:zf(i,"rows",n,()=>Pk(i,e.label,t))}}function sZ(e,t){let r=e.cells.map(n=>lZ(n,t));return{n:"row",a:ba(e.bag,[]),c:_o(e.bag)?r:(0,vt.assembleChildren)(e.bag,r)}}function lZ(e,t){let r=e.control?e.control.showLabel:Ok(e.bag,"showlabel")==="true",n=[So("id",e.id),No("showlabel",r),No("visible",e.visible,!0),Ek("colspan",e.colspan),Ek("rowspan",e.rowspan)],i=e.control?[uZ(e.control)]:[],o;if(_o(e.bag))o=[...e.control&&e.control.label?[Xy(e.control.label,t)]:[],...i];else{let a=e.control?Zy(e.bag,e.control.label,t):e.bag;o=(0,vt.assembleChildren)(a,i)}return{n:"cell",a:ba(e.bag,n),c:o}}function uZ(e){let t=[So("id",e.id),{key:"classid",matches:i=>Ju(i)===e.classId,render:()=>jy(e.classId||String(rt.ControlClassId.TextboxControl)),absentDefault:""}];e.fieldName!==null&&t.push(So("datafieldname",e.fieldName)),t.push(No("disabled",e.isReadOnly)),t.push(No("isrequired",e.isRequired));let r=e.fieldName===null?tZ(e.bag,"datafieldname"):e.bag,n;return _o(r)?n=Object.keys(e.parameters).length>0?[Ky(e.parameters)]:[]:n=(0,vt.assembleChildren)(rZ(r,e.parameters),[]),{n:"control",a:ba(r,t),c:n}}var cZ={make:(e,t)=>new FX.FormElementNode(e,t),setProp:(e,t,r)=>e.setProperty(t,r),addChild:(e,t)=>e.addChild(t)};function Ak(e,t,r,n){(0,Wy.installDomShim)();let i=fZ(e,r);(0,er.reconcileEmbedDescriptions)(i,n),(0,ii.reconcilePcfDescriptions)(i,n,r?.pcf);let o=(0,vt.rebuildRaw)(nZ(i,t),cZ,null);return new UX.SerializationService(t).serializeFormXmlNode(o)}function dZ(e){return JSON.parse(JSON.stringify(e))}function fZ(e,t){let r=dZ(e);r.bag||(r.bag=(0,vt.emptyBag)()),r.tabs||(r.tabs=[]),wZ(r.bag),t&&pZ(r,t);for(let n of r.tabs)mZ(n);return r}function pZ(e,t){var r;let n=(r=e.entityLogicalName)!==null&&r!==void 0?r:"";eb(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=kk(s.attributeType)))})}function Sk(e){let t=[];return eb(e,r=>t.push(r)),t}function eb(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 mZ(e){e.id||(e.id=Bi.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)hZ(t);e.bag||(e.bag=(0,vt.emptyBag)())}function hZ(e){e.sections||(e.sections=[]);for(let t of e.sections)gZ(t);e.bag||(e.bag=(0,vt.emptyBag)()),e.width===void 0&&_o(e.bag)&&(e.width="100%")}function gZ(e){e.id||(e.id=Bi.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)yZ(t);e.bag||(e.bag=(0,vt.emptyBag)())}function yZ(e){e.cells||(e.cells=[]);for(let t of e.cells)bZ(t);e.bag||(e.bag=(0,vt.emptyBag)())}function bZ(e){(0,er.hasGenPage)(e.control)&&(0,er.applyEmbedCellDefaults)(e),e.id||(e.id=Bi.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&&vZ(e.control),e.bag||(e.bag=(0,vt.emptyBag)())}function vZ(e){var t;(0,er.hasGenPage)(e)&&(0,er.applyEmbedControlDefaults)(e),e.id||(e.id=Bi.Guid.NewGuid()),(e.classId===void 0||e.classId===null)&&(e.classId=String(rt.ControlClassId.TextboxControl)),e.fieldName===void 0&&(e.fieldName=null),e.type===void 0&&(e.type=e.fieldName?"Field":Yy(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,Jy.assertXmlName)(r,"Form control parameter name");e.bag||(e.bag=(0,vt.emptyBag)())}function wZ(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"&&!Nk(o,"handlerUniqueId")&&o.a.push(["handlerUniqueId",jy(Bi.Guid.NewGuid())])}}else if(r.n==="formLibraries")for(let n of r.c)n.n==="Library"&&!Nk(n,"libraryUniqueId")&&n.a.push(["libraryUniqueId",jy(Bi.Guid.NewGuid())])}}var Gf=class{constructor(t=_k.DEFAULT_LCID){this.lcid=t}toArtifact(t,r){var n,i,o;let{tabs:a,bag:s}=Ck(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=VX[t.formType])!==null&&o!==void 0?o:"Main",status:this.readActivationStatus(t),...r!==void 0&&r!==""?{description:r}:{},tabs:a,bag:s};return(0,er.projectGenPageEmbeds)(l),(0,ii.projectPcfBindings)(l),l}fromArtifact(t){var r;return this.deserialize({formxml:Ak(t,this.lcid),formid:t.id||(0,Ks.newId)(),objecttypecode:t.entityLogicalName,type:Vf[t.formType],name:t.name,uniquename:t.name,description:(r=t.description)!==null&&r!==void 0?r:"",formpresentation:bt.FormPresentation.AirForm,formactivationstate:t.status==="Active"?bt.FormActivationState.Active:bt.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,Ks.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,Wy.installDomShim)();let f=vk.ScriptUtilities.ParseXml(c),m=CZ(f),p=this.deserializeDocument(d,f);return EZ(this.toArtifact(p,(l=u.description)!==null&&l!==void 0?l:void 0),m)}toApiPayload(t,r,n){let i=(0,er.genPageEmbedIssues)(t);if(i.length>0)throw new Hs.ValidationError("form",t.id,i);let o=(0,ii.pcfBindingIssues)(t,r,{atPush:!0});if(o.length>0)throw new Hs.ValidationError("form",t.id,o);let a=(0,ii.pcfReadIssues)(t,n?.pcf,r);if(a.unavailable)throw(0,Hs.attachCause)(new Hs.SdkError(a.unavailable.code,a.unavailable.message),a.unavailable.cause);if(a.issues.length>0)throw new Hs.ValidationError("form",t.id,a.issues);return{formxml:Ak(t,this.lcid,n,r),name:t.name,type:Vf[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 eb(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,ii.customControlNeeds)(t,r)}}createDefault(t){var r,n,i,o,a,s,l,u,c,d,f,m;let p=[...(0,er.genPageEmbedIssues)(t),...(0,ii.pcfBindingIssues)(t)];if(p.length>0)throw new Hs.ValidationError("form",t.id||"(new)",p);let h=t.tabs&&t.tabs.length>0?void 0:RZ(this.lcid),g=h!==void 0?h:t.tabs.map(C=>AZ(C,this.lcid)).join(""),b=this.deserialize({formxml:`<form><tabs>${g}</tabs></form>`,formid:t.id||(0,Ks.newId)(),objecttypecode:(r=t.entityLogicalName)!==null&&r!==void 0?r:"",type:Vf[(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:bt.FormPresentation.AirForm,formactivationstate:((s=t.status)!==null&&s!==void 0?s:"Active")==="Active"?bt.FormActivationState.Active:bt.FormActivationState.InActive});(l=b.displayCondition)===null||l===void 0||l.removeProperty(bt.ElementProperties.Order);let w=this.toArtifact(b,t.description);if(t.tabs&&t.tabs.length>0){let C=Sk(t);Sk(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,Ks.assignMissingIds)(t)}completeAsStored(t,r){return(0,qX.completeRecordAsStored)(t,r,this.lcid)}normalize(t){return(0,ii.mintPcfIdentity)((0,er.mintEmbedIdentity)(t))}committed(t,r){var n,i,o,a,s,l;let u=r?.formxml;if(typeof u!="string"||!((0,er.mayCommitEmbedState)(t)||(0,ii.mayCommitPcfState)(t)))return{artifact:t,baseline:t};let c=this.deserialize({formxml:u,formid:t.id||(0,Ks.newId)(),objecttypecode:(n=t.entityLogicalName)!==null&&n!==void 0?n:"",type:Vf[(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:bt.FormPresentation.AirForm,formactivationstate:bt.FormActivationState.Active}),{bag:d}=Ck(c,this.lcid),f=(0,ii.commitPcfState)((0,er.commitEmbedState)(t,(l=(0,er.descriptionsRegion)(d))===null||l===void 0?void 0:l.node),Yy);return{artifact:f,baseline:f}}validate(t){return qZ(t)}deserialize(t){return(0,Wy.installDomShim)(),this.deserializeDocument(t,vk.ScriptUtilities.ParseXml(t.formxml))}deserializeDocument(t,r){let n=new MX.DeserializationService(this.lcid).deSerializeFormXml(r,new Bi.Guid(t.formid),t.objecttypecode,bt.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===bt.FormActivationState.InActive?"Inactive":"Active"}};kr.FormAdapter=Gf;var Rk=["header","footer","DisplayConditions"];function CZ(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&&Rk.includes(i.nodeName)&&n.add(i.nodeName);return n}function EZ(e,t){var r;if(!(!((r=e.bag)===null||r===void 0)&&r.c))return e;let n=Rk.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 Rn(e){return String(e??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function tb(e,t){return e?`<labels><label description="${Rn(e)}" languagecode="${t}" /></labels>`:""}function rb(e){return e&&e.length>0?Ju(e):(0,Ks.newId)()}function AZ(e,t){var r,n,i,o;let a=(r=e.columns)!==null&&r!==void 0?r:[],s=(a.length>0?a:[PZ()]).map(l=>SZ(l,t)).join("");return`<tab id="{${Rn(rb(e.id))}}" name="${Rn((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}">${tb(e.label,t)}<columns>${s}</columns></tab>`}function SZ(e,t){var r,n;let i=((r=e.sections)!==null&&r!==void 0?r:[]).map(o=>NZ(o,t)).join("");return`<column width="${Rn((n=e.width)!==null&&n!==void 0?n:"100%")}"><sections>${i}</sections></column>`}function NZ(e,t){var r,n,i,o,a;let s=((r=e.rows)!==null&&r!==void 0?r:[]).map(l=>_Z(l,t)).join("");return`<section id="{${Rn(rb(e.id))}}" name="${Rn((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="${zy((a=e.columns)!==null&&a!==void 0?a:1)}">${tb(e.label,t)}<rows>${s}</rows></section>`}function _Z(e,t){var r;return`<row>${((r=e.cells)!==null&&r!==void 0?r:[]).map(n=>TZ(n,t)).join("")}</row>`}function TZ(e,t){var r,n,i,o,a;let s=DZ(e),l=s.control,u=l?tb((r=l.label)!==null&&r!==void 0?r:"",t):"",c=l?IZ(l):"";return`<cell id="{${Rn(rb(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 DZ(e){if(!(0,er.hasGenPage)(e.control))return e;let t={...e.control};(0,er.applyEmbedControlDefaults)(t);let r={...e,control:t};return(0,er.applyEmbedCellDefaults)(r),r}function IZ(e){var t,r,n;let i=e.fieldName?` datafieldname="${Rn(e.fieldName)}"`:"",o=OZ(e.parameters),a=e.classId?Ju(e.classId):String(rt.ControlClassId.TextboxControl);return`<control id="${Rn((t=e.id)!==null&&t!==void 0?t:"")}" classid="{${Rn(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 OZ(e){let t=Object.keys(e??{});return t.length===0?"":(t.forEach(n=>(0,Jy.assertXmlName)(n,"Form control parameter name")),`<parameters>${t.map(n=>`<${n}>${Rn(e[n])}</${n}>`).join("")}</parameters>`)}function PZ(){return{width:"100%",sections:[],bag:{a:[],c:[]}}}function RZ(e){return`<tab id="{${Bi.Guid.NewGuid()}}" name="tab_general" expanded="true" visible="true"><labels><label description="General" languagecode="${e}" /></labels><columns><column width="100%"><sections><section id="{${Bi.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 kZ(e=_k.DEFAULT_LCID){return{adapter:new Gf(e),api:BX.formApi,languageSensitive:!0,publish:(t,r,n)=>(0,wk.publishBoundEntity)(t,n),publishScope:(t,r)=>(0,wk.boundEntityPublishScope)(r),rebaselineAfterPublish:"bracket"}}kr.formRegistration=kZ;var LZ=new Set(["id","name","label","expanded","visible","columns","bag"]),$Z=new Set(["id","width","sections","bag"]),xZ=new Set(["id","name","label","visible","showLabel","columns","rows","bag"]),FZ=new Set(["id","cells","bag"]),MZ=new Set(["id","visible","colspan","rowspan","control","bag"]),UZ=new Set(["id","classId","fieldName","type","isRequired","isReadOnly","label","showLabel","parameters","genPage","customControl","bag"]),BZ={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 qZ(e){let t=[];return(0,Rr.childObjects)(e,"tabs","","tab",t).forEach(({node:n,index:i})=>{let o=`/tabs/${i}`;(0,Rr.rejectUnknownKeys)(n,LZ,o,"tab",t),(0,Rr.childObjects)(n,"columns",o,"column",t).forEach(({node:s,index:l})=>{let u=`${o}/columns/${l}`;(0,Rr.rejectUnknownKeys)(s,$Z,u,"column",t),(0,Rr.childObjects)(s,"sections",u,"section",t).forEach(({node:d,index:f})=>{let m=`${u}/sections/${f}`;(0,Rr.rejectUnknownKeys)(d,xZ,m,"section",t),(0,Rr.childObjects)(d,"rows",m,"row",t).forEach(({node:h,index:g})=>{let b=`${m}/rows/${g}`;(0,Rr.rejectUnknownKeys)(h,FZ,b,"row",t),(0,Rr.childObjects)(h,"cells",b,"cell",t).forEach(({node:C,index:S})=>{let O=`${b}/cells/${S}`;(0,Rr.rejectUnknownKeys)(C,MZ,O,"cell",t,BZ);let k=C.control;k!=null&&!(0,Rr.isJsonObject)(k)?t.push((0,Rr.issue)(`${O}/control`,"control-must-be-object-or-null",`a cell control must be a JSON object or null, got ${typeof k}`)):(0,Rr.isJsonObject)(k)&&(0,Rr.rejectUnknownKeys)(k,UZ,`${O}/control`,"control",t)})})})})}),t.push(...(0,er.genPageEmbedIssues)(e)),t.push(...(0,ii.pcfBindingIssues)(e)),t}kr.SUBGRID_CLASS_ID=rt.ControlClassId.SubgridControl;kr.NOTES_CLASS_ID=rt.ControlClassId.TimelineControl;kr.QUICK_VIEW_CLASS_ID=rt.ControlClassId.QuickViewControl;var VZ={Lookup:String(rt.ControlClassId.LookupControl),Customer:String(rt.ControlClassId.LookupControl),Owner:String(rt.ControlClassId.LookupControl),PartyList:String(rt.ControlClassId.PartyListControl),Boolean:String(rt.ControlClassId.BooleanControl),DateTime:String(rt.ControlClassId.DateTimeControl),Decimal:String(rt.ControlClassId.DecimalControl),Double:String(rt.ControlClassId.FloatingNumberControl),Money:String(rt.ControlClassId.CurrencyControl),Integer:String(rt.ControlClassId.IntegerControl),BigInt:String(rt.ControlClassId.IntegerControl),Memo:String(rt.ControlClassId.TextAreaControl),String:String(rt.ControlClassId.TextboxControl)},GZ="3EF39988-22BB-4F0B-BBBE-64B5A3748AEE";function kk(e){return e==="Picklist"||e==="State"||e==="Status"?GZ:e&&VZ[e]||String(rt.ControlClassId.TextboxControl)}kr.classIdForAttributeType=kk;function Nk(e,t){let r=e.a.find(n=>n[0]===t);return r?r[1]:void 0}});var nb=v(Js=>{"use strict";Object.defineProperty(Js,"__esModule",{value:!0});Js.viewApi=Js.findDefaultViews=void 0;var Mk=Lt(),fr=ye(),kn=le(),WZ=ns(),$k="savedqueryid,name,description,fetchxml,layoutxml,querytype,returnedtypecode,isdefault",zZ="savedqueryid,name,returnedtypecode,querytype,isdefault",jZ=60*1e3;function jf(e){return(e.localName||e.nodeName).toLowerCase()}function Yu(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 HZ(e){if(!e)return;let t=!0,r=()=>{t=!1},n=new WZ.DOMParser({errorHandler:{warning:r,error:r,fatalError:r}}).parseFromString(e,"text/xml").documentElement;return t&&n&&jf(n)==="fetch"?n:void 0}function KZ(e){for(let t=e.parentNode;t;t=t.parentNode)if(jf(t)==="link-entity")return!0;return!1}function xk(e,t){var r,n,i;if(((r=e.canbedeleted)===null||r===void 0?void 0:r.Value)!==!1)return!1;let o=HZ(e.fetchxml);if(!o)return!1;let a=Array.from(o.getElementsByTagName("*")),s=a.filter(u=>jf(u)==="condition"),l=s.length===1?s[0]:void 0;return l!==void 0&&a.filter(u=>jf(u)==="link-entity").every(u=>{var c;return((c=Yu(u,"link-type"))===null||c===void 0?void 0:c.toLowerCase())==="outer"})&&!KZ(l)&&Yu(l,"entityname")===void 0&&((n=Yu(l,"attribute"))===null||n===void 0?void 0:n.toLowerCase())==="statecode"&&((i=Yu(l,"operator"))===null||i===void 0?void 0:i.toLowerCase())==="eq"&&Yu(l,"value")===String(t)}function JZ(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 YZ(e){var t,r;let n=e.filter(a=>xk(a,0)),i=e.filter(a=>xk(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:"")))<=jZ&&JZ(a.name,s.name)&&o.push({active:a,inactive:s});return o.length===1?o[0]:void 0}async function QZ(e,t,r={}){var n;let i=new Set(((n=r.excludeViewIds)!==null&&n!==void 0?n:[]).filter(Boolean)),o=`returnedtypecode eq '${(0,kn.odataLiteral)(t)}' and querytype eq 0`,a=`/savedqueries${(0,kn.odataQuery)([["$select","savedqueryid,name,canbedeleted,fetchxml,createdon"],["$filter",o]])}`,s=await(0,Mk.collectPages)(e,a,`findDefaultViews('${t}')`),l=YZ(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:"")}})}Js.findDefaultViews=QZ;async function XZ(e,t){var r;let n=`/EntityDefinitions(LogicalName='${(0,kn.odataPathLiteral)(t)}')${(0,kn.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 Fk(e,t,r){if(!r||!/<grid\b/.test(t)||/<grid[^>]*\bobject=/.test(t))return t;let n=await XZ(e,r);return n===void 0?t:t.replace(/<grid\b/,`<grid object="${n}"`)}Js.viewApi={async get(e,t){let r=(0,kn.normalizeGuid)(t,"id"),n=await(0,fr.readRowEtag)(e,"savedqueries","savedqueryid",r),i=`/savedqueries(${r})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,kn.odataQuery)([["$select",$k]]);return{raw:(0,fr.ensureSuccess)(await e.get(i),e.apiUrl(i)).body,etag:n}},async readContentThenToken(e,t){let r=(0,kn.normalizeGuid)(t,"id"),n=`/savedqueries(${r})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,kn.odataQuery)([["$select",$k]]),i=(0,fr.ensureSuccess)(await e.get(n),e.apiUrl(n)),o=await(0,fr.readRowEtag)(e,"savedqueries","savedqueryid",r);return{raw:i.body,etag:o}},async list(e,t){let r=`/savedqueries${(0,kn.odataQuery)([["$select",zZ],["$filter",t?.entityLogicalName?`returnedtypecode eq '${(0,kn.odataLiteral)(t.entityLogicalName)}'`:void 0]])}`;return(await(0,Mk.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,fr.echoWrite)("savedqueryid"),o=`/savedqueries${i.query}`,a=await Fk(e,n.layoutxml,n.returnedtypecode),s=Object.freeze((0,fr.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,fr.ensureSuccess)(await(0,fr.resendDeadlockVictim)(()=>e.post(o,{...s},i.options)),e.apiUrl(o));return{id:(0,fr.resolveCreatedId)(l,"savedqueryid","view",r),etag:(0,fr.readEtag)(l)}},async update(e,t,r,n){let i=r,o=(0,kn.normalizeGuid)(t,"id"),a=(0,fr.echoWrite)("savedqueryid",{"If-Match":(0,fr.requireEtag)(n,"view",o)}),s=`/savedqueries(${o})${a.query}`,l=await Fk(e,i.layoutxml,i.returnedtypecode),u=(0,fr.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,fr.readEtag)(u)}},delete(e,t){return(0,fr.deleteRecord)(e,"savedqueries",t)}}});var eL=v(Ys=>{"use strict";Object.defineProperty(Ys,"__esModule",{value:!0});Ys.viewRegistration=Ys.ViewAdapter=void 0;var zk=Q(),jr=rn(),ib=so(),va=uo(),Uk=Qr(),ZZ=nb(),ob=lo(),eee=pt(),jk=100,Kf=class{toArtifact(t){var r,n,i,o,a,s,l,u;(0,ob.installDomShim)();let c=(r=t.fetchxml)!==null&&r!==void 0?r:"",d=(n=t.layoutxml)!==null&&n!==void 0?n:"",f=(0,va.parseXmlRoot)(c,"<fetch/>"),m=(0,va.parseXmlRoot)(d,"<grid/>"),p=Kk(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:ree(f),queryType:(l=t.querytype)!==null&&l!==void 0?l:0,isDefault:(u=t.isdefault)!==null&&u!==void 0?u:!1,columns:Hk(m,f),filters:Yk(f),sort:Jk(f),...p.length>0?{linkEntities:p}:{},fetchBag:c?(0,va.projectElementBag)(f):void 0,layoutBag:d?(0,va.projectElementBag)(m):void 0}}fromArtifact(t){(0,ob.installDomShim)();let{fetchxml:r,layoutxml:n}=Bk(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,ob.installDomShim)();let{fetchxml:s,layoutxml:l}=Bk(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,eee.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,jr.childObjects)(n,"columns","","column",r),(0,jr.childObjects)(n,"sort","","sort",r),(0,jr.childObjects)(n,"linkEntities","","linkEntity",r),tee(n.linkEntities,r);let i=n.filters;return i!=null&&((0,jr.isJsonObject)(i)?ab(i,"/filters",r):r.push((0,jr.issue)("/filters","filters-must-be-object",`filters must be a JSON object, got ${typeof i}`))),r}};Ys.ViewAdapter=Kf;function tee(e,t){Array.isArray(e)&&e.forEach((r,n)=>{if(!(0,jr.isJsonObject)(r))return;for(let o of["name","from","to"]){let a=r[o];(typeof a!="string"||a.trim()==="")&&t.push((0,jr.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,jr.isJsonObject)(i)?ab(i,`/linkEntities/${n}/filters`,t):t.push((0,jr.issue)(`/linkEntities/${n}/filters`,"filters-must-be-object",`filters must be a JSON object, got ${typeof i}`)))})}function ab(e,t,r){(0,jr.childObjects)(e,"conditions",t,"condition",r),(0,jr.childObjects)(e,"groups",t,"filterGroup",r).forEach(({node:i,index:o})=>ab(i,`${t}/groups/${o}`,r))}function ree(e){var t;let r=e.getElementsByTagName("entity")[0];return(t=r?.getAttribute("name"))!==null&&t!==void 0?t:""}function Hk(e,t){var r;let n=Jf(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)?jk: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 Jf(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 Kk(e){let t=e.getElementsByTagName("entity")[0];if(!t)return[];let r=[];for(let n of Mt(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=Mt(n,"filter").find(c=>!Yf(c));r.push({name:i,from:o,to:a,...s?{alias:s}:{},...l==="inner"||l==="outer"?{linkType:l}:{},...u?{filters:sb(u)}:{}})}return r}function Jk(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=Mt(t,"filter").filter(i=>!Yf(i)).map(sb);return n.length===0?r:n.length===1?n[0]:{type:"and",conditions:[],groups:n}}function Yf(e){if(e.getAttribute("isquickfindfields")==="1"||Qk(e))return!0;if(Mt(e,"filter").length>0)return!1;let t=Mt(e,"condition");return t.length===0?!1:t.some(r=>r.getAttribute("isquickfindfields")==="1"||Mt(r,"value").length>0||iee(r))}function Qk(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"?Qk(n):n.tagName!=="condition"))return!0}return!1}var nee=new Set(["attribute","operator","value","entityname","uiname","uitype"]);function iee(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&&!nee.has(i))return!0}return!1}function sb(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(sb(l))}return{type:n,conditions:i,groups:o}}function Mt(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 lb=e=>{var t,r;return`${(t=e.relatedEntity)!==null&&t!==void 0?t:""}::${(r=e.sourceAttribute)!==null&&r!==void 0?r:e.name}`};function oee(e,t){let r=Jf(e),n=new Map;for(let i of t){if(!i.relatedEntity)continue;let o=r.get(i.name);if(o){let a=lb(i),s=n.get(a);s?s.push(o.link):n.set(a,[o.link])}}return n}function aee(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(lb(s));return!!l&&l.some(u=>!i.has(u))});if(a.length!==0)throw new zk.ValidationError("view",e.id,a.map(s=>(0,jr.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 Bk(e){var t,r;let n=see(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(!qk(e.fetchBag)||!qk(e.layoutBag))return{fetchxml:wee({...e,columns:n,sort:i,filters:o}),layoutxml:Cee({...e,columns:n},`${e.entityLogicalName}id`)};let a=new DOMParser().parseFromString("<root/>","text/xml"),s=Vk(e.fetchBag,"fetch",a),l=Vk(e.layoutBag,"grid",a),u=Hk(l,s),c=!Hf(n,u),d=!Hf(i,Jk(s)),f=!Hf(o,Yk(s)),m=e.linkEntities,p=m!==void 0&&!Hf(m,Kk(s)),h=p?oee(s,u):void 0;return p&&yee(a,s,m),p&&(vee(e,s,n,h),aee(e,s,n,h)),c?(Gk(a,s,n,u),fee(a,l,n)):p&&Gk(a,s,n,u),d&&hee(a,s,i),f&&gee(a,s,o),{fetchxml:(0,va.serializeNode)(s),layoutxml:(0,va.serializeNode)(l)}}function see(e){return(e??[]).map((t,r)=>{var n,i;return{name:String(t.name).toLowerCase(),width:(n=t.width)!==null&&n!==void 0?n:jk,order:(i=t.order)!==null&&i!==void 0?i:r,...t.relatedEntity?{relatedEntity:t.relatedEntity}:{},...t.sourceAttribute?{sourceAttribute:String(t.sourceAttribute).toLowerCase()}:{}}})}function qk(e){return!!e&&(e.c.length>0||e.a.length>0)}function Vk(e,t,r){let n={n:t,a:(0,ib.mergeAttrs)(e.a,[]),c:(0,ib.spliceChildren)(e.c,[])};return(0,ib.rebuildRaw)(n,(0,va.domEngine)(r),null)}function Gk(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=Jf(t);for(let p of n)u.has(l(p))||(uee(s,p),p.relatedEntity&&c.has(p.name)&&lee((i=d.get(p.name))===null||i===void 0?void 0:i.link,p.name));let f=Jf(t),m=new Set(Mt(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||!Zk(s,p.relatedEntity)))continue;let g=cee(e,s,p.relatedEntity),b=e.createElement("attribute");Xk(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),dee(s,h),m.add(p.name)}}function Xk(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 lee(e,t){if(e){for(let r of Mt(e,"attribute"))if((r.getAttribute("alias")||r.getAttribute("name"))===t){e.removeChild(r);return}}}function uee(e,t){if(t.relatedEntity){for(let r of Mt(e,"link-entity"))if(!(r.getAttribute("alias")!==t.relatedEntity&&r.getAttribute("name")!==t.relatedEntity)){for(let n of Mt(r,"attribute"))if((n.getAttribute("alias")||n.getAttribute("name"))===t.name){r.removeChild(n);return}}return}for(let r of Mt(e,"attribute"))if(r.getAttribute("name")===t.name){e.removeChild(r);return}}function Zk(e,t,r=!1){let n=o=>o.getAttribute("alias")===t||o.getAttribute("name")===t;for(let o of Mt(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 cee(e,t,r){let n=Zk(t,r);if(n)return n;let i=e.createElement("link-entity");return i.setAttribute("name",r),t.appendChild(i),i}function dee(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 fee(e,t,r){let n=t.getElementsByTagName("row")[0];if(!n)return;let i=[...r].sort((s,l)=>s.order-l.order),o=pee(n);if(mee(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 pee(e){return Mt(e,"cell").filter(t=>!!t.getAttribute("name")&&t.getAttribute("ishidden")!=="1")}function mee(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 hee(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 Mt(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 gee(e,t,r){let n=t.getElementsByTagName("entity")[0];if(n){for(let i of Mt(n,"filter"))Yf(i)||n.removeChild(i);(r.conditions.length>0||r.groups.length>0)&&n.appendChild(Qu(e,r))}}function Hf(e,t){return JSON.stringify(e)===JSON.stringify(t)}function yee(e,t,r){var n;let i=t.getElementsByTagName("entity")[0];if(!i)return;let o=Mt(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){Wk(e,g,p);return}let b=e.createElement("link-entity");Wk(e,b,p),i.appendChild(b)});for(let p of o)l.has(p)||i.removeChild(p)}var bee=new Set(["inner","outer"]);function vee(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(lb(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 zk.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,jr.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 Wk(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):bee.has(t.getAttribute("link-type")||"")&&t.removeAttribute("link-type");let n=Mt(t,"filter").find(o=>!Yf(o)),i=r.filters&&(r.filters.conditions.length>0||r.filters.groups.length>0)?Qu(e,r.filters):null;n&&i?t.replaceChild(i,n):n?t.removeChild(n):i&&t.appendChild(i)}function wee(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(Qu(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){Xk(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(Qu(r,e.filters)),new XMLSerializer().serializeToString(r)}function Qu(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(Qu(e,n));return r}function Cee(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 Eee(){return{adapter:new Kf,api:ZZ.viewApi,publish:(e,t,r)=>(0,Uk.publishBoundEntity)(e,r),publishScope:(e,t)=>(0,Uk.boundEntityPublishScope)(t),rebaselineAfterPublish:"bracket"}}Ys.viewRegistration=Eee});function Qf(e,t){return e==="SetFieldValue"&&t!==void 0&&Aee.has(t.attributeType)&&(t.requiredLevel==="None"||t.requiredLevel==="Recommended")}var Aee,ub=L(()=>{"use strict";Aee=new Set(["Integer","Double","Decimal","Money","String","Memo","DateTime","Picklist","Lookup"])});function tL(e){return e!=="Entity"&&e!=="AllForms"&&typeof e=="string"&&e.trim()!==""}function cb(e){return e==="AllForms"||tL(e)?1:2}function db(e){return tL(e)?e:null}function rL(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:Qs.WorkflowCategory.BusinessRule,type:Qs.WorkflowTypeCode.Definition,mode:1,scope:Qs.WorkflowScope.Organization,primaryentity:e.entityLogicalName,iscrmuiworkflow:!0,processtriggerscope:cb(e.scope),processtriggerformid:db(e.scope)}}var Qs,nL=L(()=>{"use strict";Qs=Ae(Qi());});function iL(e,t=0){return(Ut[e[t+0]]+Ut[e[t+1]]+Ut[e[t+2]]+Ut[e[t+3]]+"-"+Ut[e[t+4]]+Ut[e[t+5]]+"-"+Ut[e[t+6]]+Ut[e[t+7]]+"-"+Ut[e[t+8]]+Ut[e[t+9]]+"-"+Ut[e[t+10]]+Ut[e[t+11]]+Ut[e[t+12]]+Ut[e[t+13]]+Ut[e[t+14]]+Ut[e[t+15]]).toLowerCase()}var Ut,oL=L(()=>{Ut=[];for(let e=0;e<256;++e)Ut.push((e+256).toString(16).slice(1))});function fb(){return Xf>Zf.length-16&&((0,aL.randomFillSync)(Zf),Xf=0),Zf.slice(Xf,Xf+=16)}var aL,Zf,Xf,sL=L(()=>{aL=require("crypto"),Zf=new Uint8Array(256),Xf=Zf.length});var lL,pb,uL=L(()=>{lL=require("crypto"),pb={randomUUID:lL.randomUUID}});function See(e,t,r){if(pb.randomUUID&&!t&&!e)return pb.randomUUID();e=e||{};let n=e.random??e.rng?.()??fb();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 iL(n)}var pr,cL=L(()=>{uL();sL();oL();pr=See});var mb=L(()=>{cL()});var dL=L(()=>{"use strict";});function fL(e){return e!=null&&Nee.has(e)}function ep(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 Nee,hb=L(()=>{"use strict";Nee=new Set(["Picklist","State","Status"])});var tp=v(pn=>{"use strict";Object.defineProperty(pn,"__esModule",{value:!0});pn.WorkflowConditionOperator=pn.WorkflowAttributeType=pn.SystemStep=pn.FieldRequiredLevelTypes=pn.AttributeDateTimeBehavior=void 0;pn.AttributeDateTimeBehavior={None:0,Dynamic:1,DateOnly:2,StaticTimeZoneInvariant:3,UserLocal:4};pn.FieldRequiredLevelTypes={None:"0",Required:"1",Recommended:"2"};pn.SystemStep={IdentifyContact:"IdentifyContact",IdentifyAccount:"IdentifyAccount",IdentifyCustomer:"IdentifyCustomer",IdentifyCase:"IdentifyCase",Solution:"Solution",Resolve:"Resolve"};pn.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"};pn.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 rp(e){return e!=null&&mL.includes(e)}function gb(e){return e===oe.WorkflowAttributeType.Integer}function yb(e,t){return t===oe.WorkflowConditionOperator.Equal||t===oe.WorkflowConditionOperator.NotEqual?e:_ee.includes(t)?mL.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 hL(e){let t=e.leftWorkflowType??e.valueWorkflowType??oe.WorkflowAttributeType.String,r=Xu[e.operator]??oe.WorkflowConditionOperator.Equal;return yb(t,r)}function gL(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||!pL.test(o)||!pL.test(a)||o.length>1&&o.startsWith("0")||o.length>Tee?!1:t!==oe.WorkflowAttributeType.Integer||i.length===1}var oe,Xu,mL,_ee,pL,Tee,bb=L(()=>{"use strict";oe=Ae(tp());Xu={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},mL=[oe.WorkflowAttributeType.Decimal,oe.WorkflowAttributeType.Float,oe.WorkflowAttributeType.Integer,oe.WorkflowAttributeType.Money],_ee=[oe.WorkflowConditionOperator.GreaterThan,oe.WorkflowConditionOperator.GreaterThanOrEqual,oe.WorkflowConditionOperator.LessThan,oe.WorkflowConditionOperator.LessThanOrEqual];pL=/^\d*$/,Tee=28});var yL=L(()=>{"use strict";});function Ln(e){return!Dee.has(e)}function vb(e){return e==="Equals"||e==="DoesNotEqual"}function np(e){return vL.has(e)?Iee:Lee.has(e)?Oee:wL.has(e)?Pee:xee.has(e)?kee:Ree}function CL(e){return np(e)[0]}function EL(e,t){return np(t).includes(e)}function bL(e){return vL.has(e)?"string":e==="Money"?"money":e==="Integer"||e==="BigInt"?"integer":e==="Decimal"||e==="Double"?"decimal":wL.has(e)?"date":$ee.has(e)?"boolean":"other"}function ip(e,t){let r=bL(e),n=bL(t);return r==="other"||n==="other"?e===t:r===n}var Dee,Iee,Oee,Pee,Ree,kee,vL,Lee,wL,$ee,xee,op=L(()=>{"use strict";yL();Dee=new Set(["ContainsData","DoesNotContainData"]);Iee=["Equals","DoesNotEqual","Contains","DoesNotContain","BeginsWith","DoesNotBeginWith","EndsWith","DoesNotEndWith","ContainsData","DoesNotContainData"],Oee=["Equals","DoesNotEqual","IsGreaterThan","IsGreaterThanEqualTo","IsLessThan","IsLessThanEqualTo","ContainsData","DoesNotContainData"],Pee=["On","NotOn","Equals","DoesNotEqual","IsGreaterThan","IsGreaterThanEqualTo","IsLessThan","IsLessThanEqualTo","ContainsData","DoesNotContainData"],Ree=["Equals","DoesNotEqual","ContainsData","DoesNotContainData"],kee=["Equals","DoesNotEqual","Contains","DoesNotContain","BeginsWith","DoesNotBeginWith","EndsWith","DoesNotEndWith","ContainsData","DoesNotContainData"],vL=new Set(["String","Memo","EntityName"]),Lee=new Set(["Integer","BigInt","Money","Decimal","Double"]),wL=new Set(["DateTime"]),$ee=new Set(["Boolean"]),xee=new Set(["Lookup","Owner","Customer"])});function _L(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 kL(e){return e&&e!==Fe.WorkflowAttributeType.String?e:void 0}function Uee(e){return{__class:RL,parameterName:"primaryEntity",entityName:e}}function AL(e){return{__class:Cb,type:wb,typeSet:!1,behavior:Fe.AttributeDateTimeBehavior.None,method:TL,parameters:[e]}}function SL(e,t,r=Fe.WorkflowAttributeType.String){return{__class:IL,type:r,behavior:Fe.AttributeDateTimeBehavior.None,typeSet:!1,entity:Uee(t),attributeName:e}}function Bee(e,t=Fe.WorkflowAttributeType.String){return{__class:OL,type:t,behavior:Fe.AttributeDateTimeBehavior.None,typeSet:!1,primitiveValue:e}}function qee(e){return{__class:PL,type:wb,typeSet:!1,behavior:Fe.AttributeDateTimeBehavior.None,days:e,hours:"0",minutes:"0",months:"0",years:"0"}}function LL(e,t){let r=Fee[e.operator],n=AL(SL(e.leftField,t,e.leftWorkflowType)),i;e.dateArithmetic?i=qee(e.right.value??"0"):e.right.kind==="field"?i=SL(e.right.field??"",t,e.right.workflowType):i=Bee(e.right.value??"",e.right.workflowType??e.leftWorkflowType);let o=AL(i);return{__class:Cb,type:wb,typeSet:!1,behavior:Fe.AttributeDateTimeBehavior.None,method:DL,parameters:[r,n,o]}}function $L(e){return typeof e=="object"&&e.__class===Cb}function Vee(e){return typeof e=="object"&&e.__class===PL}function ap(e){return $L(e)&&e.method===TL&&e.parameters.length>0?ap(e.parameters[0]):e}function NL(e){if(typeof e!="object"||e.__class!==IL)return null;let t=e.entity;if(t&&t.__class&&t.__class!==RL)return null;let r=e.attributeName;return r?{field:r,workflowType:kL(e.type)}:null}function xL(e){if(!e)return null;let t=ap(e);if(!$L(t)||t.method!==DL||t.parameters.length!==3)return null;let r=t.parameters[0],n=Mee[String(r)];if(!n)return null;let i=NL(ap(t.parameters[1]));if(!i)return null;let o=ap(t.parameters[2]);if(Vee(o))return n!=="+"&&n!=="-"?null:{leftField:i.field,leftWorkflowType:i.workflowType,operator:n,right:{kind:"value",value:String(o.days??"")},dateArithmetic:!0};let a=NL(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===OL){let s=o.primitiveValue;return{leftField:i.field,leftWorkflowType:i.workflowType,operator:n,right:{kind:"value",value:s!=null?String(s):"",workflowType:kL(o.type)}}}return null}function Ab(e){let t=(e??"").trim();if(!/^\d+$/.test(t))return!1;let r=Number(t);return Number.isSafeInteger(r)&&r>=Eb&&r<=Xs}function wa(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&&!Ab(t)?"invalidDayCount":null}function Zs(e){return wa(e)===null}var Fe,TL,DL,wb,IL,OL,Cb,PL,RL,Fee,Mee,Eb,Xs,Zu=L(()=>{"use strict";Fe=Ae(tp());op();TL="0",DL="3",wb="0",IL="EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions",OL="PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions",Cb="MethodCallExpression:#Microsoft.Crm.Workflow.Expressions",PL="TimeSpanExpression:#Microsoft.Crm.Workflow.Expressions",RL="PrimaryEntity:#Microsoft.Crm.Workflow.Expressions";Fee={"+":0,"-":1,"*":2,"/":3},Mee={0:"+",1:"-",2:"*",3:"/"};Eb=0,Xs=2147483647});function Wee(e){return e.startsWith("__")&&!Gee.has(e)}function zee(e){let t=Object.create(null);return Object.keys(e).forEach(r=>{Wee(r)&&(t[r]=e[r])}),Object.keys(t).length>0?t:void 0}function YL(e){return e.__class==="BinaryExpression:#Microsoft.Crm.Workflow.Expressions"}function Ea(e){return e.__class==="UnaryExpression:#Microsoft.Crm.Workflow.Expressions"}function sp(e){return YL(e)||Ea(e)}function jee(e){return e.__class==="ConditionBranchStep:#Microsoft.Crm.Workflow.ObjectModel"}function ec(){return{list:[]}}function Sb(e,t,r){return e&&e.list.length>0?{list:[{...e.list[0],description:t},...e.list.slice(1)]}:{list:[{labelId:pr(),languageCode:r,description:t}]}}function _b(e){return{__class:"PrimaryEntity:#Microsoft.Crm.Workflow.Expressions",parameterName:"primaryEntity",entityName:e}}function dp(e,t,r,n=j.AttributeDateTimeBehavior.None){return{__class:"EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions",type:r,behavior:n,typeSet:!1,entity:_b(t),attributeName:e}}function Ca(e,t,r=j.AttributeDateTimeBehavior.None){return{__class:"PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions",type:t,behavior:r,typeSet:!1,primitiveValue:e}}function Jee(e){return e.bpfField==="StageCategory"?e.stageType==="SelectedStage"?ZL:XL:QL}function e1(e){return e.bpfField==="StageCategory"?j.WorkflowAttributeType.BpfStageCategory:j.WorkflowAttributeType.BpfProcess}function Yee(e,t){let r=e1(e),n=e.bpfField==="StageCategory"?{__class:"EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions",type:r,behavior:j.AttributeDateTimeBehavior.None,typeSet:!1,entity:{__class:"RelatedEntity:#Microsoft.Crm.Workflow.Expressions",parameterName:`related_${ML}_${FL}`,entityName:FL,relatedAttributeName:ML},attributeName:Kee}:dp(Hee,t,r);return{__class:"MethodCallExpression:#Microsoft.Crm.Workflow.Expressions",type:r,behavior:j.AttributeDateTimeBehavior.None,typeSet:!1,method:Ib,parameters:[Jee(e),n]}}function t1(e){let t=e;if(t.__class!=="MethodCallExpression:#Microsoft.Crm.Workflow.Expressions"||String(t.method)!==Ib)return null;let r=(t.parameters??[])[0];if(typeof r!="string")return null;let n=r.replace(/^"+|"+$/g,"");return n===XL?{bpfField:"StageCategory",stageType:"ActiveStage"}:n===ZL?{bpfField:"StageCategory",stageType:"SelectedStage"}:n===QL?{bpfField:"ProcessName"}:null}function lp(e){if(!e)return!1;let t=e;if(t.__class==="MethodCallExpression:#Microsoft.Crm.Workflow.Expressions"&&String(t.method)===Ib){let r=(t.parameters??[])[0];if(typeof r=="string"&&Qee.has(r.replace(/^"+|"+$/g,"")))return!0}return Ea(e)?lp(e.operand):YL(e)?lp(e.left)||(e.right??[]).some(lp):!1}function r1(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 Xee(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 UL(e){if(!e)return!1;switch(e.__class){case"EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions":return r1(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 Zee(e){let t=Db[e.conditionOperatoroperator];if(!t)return!1;let r=t==="ContainsData"||t==="DoesNotContainData";if(Ea(e))return r&&BL(e.operand,!0);let n=e.right??[];return n.length!==(r?0:1)?!1:BL(e.left,r,n[0])}function BL(e,t,r){return t1(e)||r1(e)?t||UL(r):!1}function Tb(e){if(!e||!sp(e))return!1;let t=e.conditionOperatoroperator;if(!Ea(e)&&(t===j.WorkflowConditionOperator.LogicalAnd||t===j.WorkflowConditionOperator.LogicalOr)){let r=e.right??[];return r.length>0&&Tb(e.left)&&r.every(Tb)}return Zee(e)}function qL(e){return!e||Xee(e)?!1:lp(e)||!Tb(e)}function n1(e){return{__class:"LookupExpression:#Microsoft.Crm.Workflow.Expressions",type:e.workflowType??j.WorkflowAttributeType.Lookup,behavior:j.AttributeDateTimeBehavior.None,typeSet:!1,entityType:e.entityType,label:e.label??"",staticValue:Ca(e.id.replace(/[{}]/g,""),j.WorkflowAttributeType.UniqueIdentifier)}}function tte(e){return e===j.WorkflowAttributeType.DateTime?j.AttributeDateTimeBehavior.DateOnly:j.AttributeDateTimeBehavior.None}function rte(e,t){if(t!==j.WorkflowAttributeType.DateTime)return j.AttributeDateTimeBehavior.None;let r=e.leftDateTimeBehavior;return r!==void 0&&r!==j.AttributeDateTimeBehavior.None?r:tte(t)}function nte(e,t,r){if(t!==j.WorkflowAttributeType.DateTime)return j.AttributeDateTimeBehavior.None;let n=e.valueFieldDateTimeBehavior;return n!==void 0&&n!==j.AttributeDateTimeBehavior.None?n:r}function ote(e){let t=e.trim().toLowerCase();if(t==="true"||t==="1")return"1";if(t==="false"||t==="0")return"0"}function pte(e){let t=fte.exec(e);if(t)return`${t[1]}T${t[2]}`;let r=dte.exec(e);if(!r)return;let[,n,i,o,a,s,l]=r,u=cte.indexOf(i.toLowerCase());if(u<0)return;let c=String(u+1).padStart(2,"0");return`${o}-${c}-${n}T${a}:${s}:${l}`}function mte(e){let t=pte(e.trim());return t!==void 0&&i1(t)?t:e}function i1(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(!ate.test(i)||o.length>0&&!ste.test(o)&&!lte.test(o)&&!ute.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 hte(e,t){let r={value:e,type:j.WorkflowAttributeType.String};if(t===j.WorkflowAttributeType.String||ite.includes(t)||e.trim().length===0)return r;if(t===j.WorkflowAttributeType.Boolean){let n=ote(e);return n==null?r:{value:n,type:t}}return ete.includes(t)?ep(e)?{value:e.trim(),type:t}:r:rp(t)?{value:e.trim(),type:t}:t===j.WorkflowAttributeType.DateTime&&i1(e)?{value:e.trim(),type:t}:r}function VL(e){return e==="ContainsData"||e==="DoesNotContainData"}function GL(e){return gte.has(e)}function WL(e,t){return{__class:"UnaryExpression:#Microsoft.Crm.Workflow.Expressions",type:j.WorkflowAttributeType.Boolean,behavior:j.AttributeDateTimeBehavior.None,typeSet:!1,conditionOperatoroperator:t,operand:e}}function zL(e,t){let r=e.leftWorkflowType??e.valueWorkflowType??j.WorkflowAttributeType.String,n=Xu[e.operator]??j.WorkflowConditionOperator.Equal,i=rte(e,r),o=yb(r,n);if(e.source==="BusinessProcess"){let l=Yee(e,t);if(VL(e.operator))return WL(l,n);let u=e1(e);return{__class:"BinaryExpression:#Microsoft.Crm.Workflow.Expressions",type:j.WorkflowAttributeType.Boolean,behavior:j.AttributeDateTimeBehavior.None,typeSet:!1,conditionOperatoroperator:n,left:l,right:[Ca(e.value??"",u)]}}let a=dp(e.field,t,r,i);if(VL(e.operator))return WL(a,n);let s;if(e.valueType==="Field"&&e.valueField){let l=GL(o)&&GL(e.valueFieldWorkflowType??"")?e.valueFieldWorkflowType:o;s=[dp(e.valueField,t,l,nte(e,l,i))]}else if(e.valueType==="Lookup"){if(!e.lookupValue)throw new Error("Lookup condition is missing its record value.");s=[n1(e.lookupValue)]}else if(e.valueType==="Clear")s=[Ca(null,j.WorkflowAttributeType.String,i)];else if(e.valueType==="Expression")s=[cp(e.valueType,e.value,e.valueField,t,e.expression,e.rawExpression)];else{let l=hte(e.value??"",o);s=[Ca(l.value,l.type,i)]}return{__class:"BinaryExpression:#Microsoft.Crm.Workflow.Expressions",type:j.WorkflowAttributeType.Boolean,behavior:j.AttributeDateTimeBehavior.None,typeSet:!1,conditionOperatoroperator:n,left:a,right:s}}function yte(){return Ca(!0,j.WorkflowAttributeType.Boolean)}function bte(e,t,r){if(e.length===0)return null;let n=zL(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:j.WorkflowAttributeType.Boolean,behavior:j.AttributeDateTimeBehavior.None,typeSet:!1,conditionOperatoroperator:o==="AND"?j.WorkflowConditionOperator.LogicalAnd:j.WorkflowConditionOperator.LogicalOr,left:n,right:[zL(e[i],r)]}}return n}function up(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===j.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===j.WorkflowAttributeType.DateTime?{valueType:"Value",value:mte(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!==j.WorkflowAttributeType.Lookup?{workflowType:e.type}:{}}}}if(e.__class==="MethodCallExpression:#Microsoft.Crm.Workflow.Expressions"){let t=xL(e);return t?{valueType:"Expression",expression:t}:{valueType:"Expression",rawExpression:e}}return{valueType:"Value",value:""}}function vte(e){let t=Db[e.conditionOperatoroperator]??"Equals",r=t==="ContainsData"||t==="DoesNotContainData",n=Ea(e)?e.operand:e.left,i=Ea(e)?[]:e.right??[],o=t1(n);if(o){let g=i[0];return{id:pr(),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"}:up(i[0]),c=l,d=a&&n.type===j.WorkflowAttributeType.DateTime&&n.behavior!==j.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===j.WorkflowAttributeType.DateTime&&m.behavior!==j.AttributeDateTimeBehavior.None?m.behavior:void 0;return{id:pr(),field:s,fieldDisplayName:s,operator:t,...u,...f?{valueWorkflowType:f}:{},...c?{leftWorkflowType:c}:{},...d!==void 0?{leftDateTimeBehavior:d}:{},...h!==void 0?{valueFieldDateTimeBehavior:h}:{}}}function jL(e){if(!e||!sp(e))return{clauses:[],logic:"AND"};let t=[],r=(o,a)=>{let s=o.conditionOperatoroperator;if(Ea(o)||s!==j.WorkflowConditionOperator.LogicalAnd&&s!==j.WorkflowConditionOperator.LogicalOr){t.push({...vte(o),...a?{connector:a}:{}});return}let l=s===j.WorkflowConditionOperator.LogicalAnd?"AND":"OR";sp(o.left)&&r(o.left,a),(o.right??[]).filter(sp).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 cp(e,t,r,n,i,o,a,s){if(e==="Field"&&r)return dp(r,n,j.WorkflowAttributeType.String);if(e==="Expression"){if(i)return LL(i,n);if(o!=null)return o}return e==="Lookup"&&a?n1(a):e==="Clear"?Ca(null,s??j.WorkflowAttributeType.String):Ca(t??"",j.WorkflowAttributeType.String)}function Nb(e,t){return{propertyName:e,propertyValueExpr:t}}function el(e){return`Step_${e.value++}`}function mn(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 HL(e,t,r){return e&&!r.used.has(e)?(r.used.add(e),e):mn(t,r)}function wte(e){return e===JL.StateCode.Activated?"Active":"Draft"}function Cte(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 Ete(e,t){let r=e.processtriggerscope,n=e.processtriggerformid;return r===1?n&&n.trim()!==""?n:"AllForms":r===2?"Entity":t??"Entity"}function o1(e,t=1033){return new tl({languageCode:t}).serialize(e)}function a1(e){return new tl().deserialize(e)}var JL,j,Gee,Db,Ib,QL,XL,ZL,Hee,Kee,FL,ML,Qee,ete,ite,ate,ste,lte,ute,cte,dte,fte,gte,Ob,tl,Pb=L(()=>{"use strict";mb();JL=Ae(Qi());dL();hb();bb();Zu();j=Ae(tp());Gee=new Set(["__class"]);Db={};for(let e of Object.keys(Xu))Db[Xu[e]]=e;Ib="23",QL="BpfProcess",XL="ActiveStageCategory",ZL="SelectedStageCategory",Hee="processid",Kee="stagecategory",FL="processstage",ML="stageid";Qee=new Set(["ActiveStage","SelectedStage","Stage"]);ete=[j.WorkflowAttributeType.Picklist,j.WorkflowAttributeType.State,j.WorkflowAttributeType.Status];ite=[j.WorkflowAttributeType.Lookup,j.WorkflowAttributeType.Customer,j.WorkflowAttributeType.Owner];ate=/^\d{4}-\d{2}-\d{2}$/,ste=/^\d{2}:\d{2}$/,lte=/^\d{2}:\d{2}:\d{2}$/,ute=/^\d{2}:\d{2}:\d{2}\.\d{1,7}$/,cte=["jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"],dte=/^[A-Za-z]{3}, (\d{2}) ([A-Za-z]{3}) (\d{4}) (\d{2}):(\d{2}):(\d{2}) GMT$/,fte=/^(\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$/;gte=new Set([j.WorkflowAttributeType.Lookup,j.WorkflowAttributeType.Owner,j.WorkflowAttributeType.Customer]);Ob={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"};tl=class{resolveLabel;languageCode;entityName="";stepCounter={value:0};idCounter={counts:{},used:new Set};constructor(t={}){this.resolveLabel=t.resolveLabel??(r=>Ob[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??pr(),name:r?.name??"Step_0",description:r!==void 0?r.description:t.description||null,stepLabels:ec(),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:mn("SetAttributeValueStep",this.idCounter),description:t.displayName||"New Action",name:t.stepName??el(this.stepCounter),stepLabels:{list:[]},specification:Nb(t.field,cp(t.valueType,t.value,t.valueField,this.entityName,t.expression,t.rawExpression,t.lookupValue,t.valueWorkflowType)),entity:_b(this.entityName)}}makeRecommendationActionStep(t,r,n){let i=r.map(l=>this.makeApplyActionStep(l)),o=t??"",a=n?.stepLabels,s=Sb(a,o,this.languageCode);return{__class:"ActionStep:#Microsoft.Crm.Workflow.ObjectModel",id:HL(n?.id,"ActionStep",this.idCounter),name:n?.name??el(this.stepCounter),description:n?.description??"Action step",stepLabels:s,steps:{list:i},actionId:null,actionType:n?.actionType??"4",processId:n?.processId??pr(),uniqueName:n?.uniqueName??`id_${pr().replace(/-/g,"")}ActionStep`}}serializeAction(t){let r=_b(this.entityName),n=t.stepName??el(this.stepCounter),i=t.stepLabels??ec(),o={name:n,stepLabels:i,description:t.displayName},a=t.type;switch(a){case"SetFieldValue":return{...o,id:mn("SetAttributeValueStep",this.idCounter),__class:"SetAttributeValueStep:#Microsoft.Crm.Workflow.ObjectModel",entity:r,specification:Nb(t.field,cp(t.valueType,t.value,t.valueField,this.entityName,t.expression,t.rawExpression,t.lookupValue,t.valueWorkflowType))};case"SetDefaultValue":return{...o,id:mn("SetDefaultValueStep",this.idCounter),__class:"SetDefaultValueStep:#Microsoft.Crm.Workflow.ObjectModel",entity:r,specification:Nb(t.field,cp(t.valueType,t.value,t.valueField,this.entityName,t.expression,t.rawExpression,t.lookupValue,t.valueWorkflowType))};case"LockUnlock":return{...o,id:mn("SetDisplayModeStep",this.idCounter),__class:"SetDisplayModeStep:#Microsoft.Crm.Workflow.ObjectModel",controlId:t.field,controlType:"standard",isReadOnly:t.lock,entity:r};case"SetBusinessRequired":return{...o,id:mn("SetFieldRequiredLevelStep",this.idCounter),__class:"SetFieldRequiredLevelStep:#Microsoft.Crm.Workflow.ObjectModel",controlId:t.field,controlType:"standard",requiredLevel:t.required?j.FieldRequiredLevelTypes.Required:j.FieldRequiredLevelTypes.None,entity:r};case"SetVisibility":return{...o,id:mn("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=Sb(t.stepLabels,s,this.languageCode);return{...o,id:mn("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=Sb(t.stepLabels,s,this.languageCode),u={list:[this.makeRecommendationActionStep(t.acceptanceText,t.applyActions??[],t.recommendationActionStepMeta)]};return{...o,id:mn("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??el(this.stepCounter),n=mn("ConditionStep",this.idCounter),i=[],o=t,a=!0;for(;o;){let s=o.rawConditionExpression??bte(o.clauses,o.logic,this.entityName),l=a?o.branchName??el(this.stepCounter):el(this.stepCounter),c={__class:"ConditionBranchStep:#Microsoft.Crm.Workflow.ObjectModel",id:a?HL(o.branchId,"ConditionBranchStep",this.idCounter):mn("ConditionBranchStep",this.idCounter),name:l,description:o.displayName,stepLabels:ec(),conditionExpression:s??(a?yte():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:ec(),containsElsebranch:i.length>1,steps:{list:i}}}makeTerminalElseBranch(t){return{__class:"ConditionBranchStep:#Microsoft.Crm.Workflow.ObjectModel",id:mn("ConditionBranchStep",this.idCounter),name:"Else",description:null,stepLabels:ec(),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??pr():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:zee(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:Ete(r,i?.formId),status:wte(t.statecode),rootCondition:n,wfomRoot:i,...Cte(t)}}deserializeConditionStep(t){let r=(t.steps?.list??[]).filter(jee);return this.buildConditionNodeFromBranches(r,t,!0)}buildConditionNodeFromBranches(t,r,n){let[i,...o]=t,{clauses:a,logic:s}=jL(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)??pr(),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,...qL(i?.conditionExpression)?{rawConditionExpression:i?.conditionExpression}:{}}}deserializeElseChain(t,r){if(t.length===0)return[];let[n]=t,{clauses:i}=jL(n.conditionExpression);return i.length===0&&!qL(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||pr(),field:u?.propertyName??"",stepName:l.name??void 0,displayName:l.description??void 0,...up(u?.propertyValueExpr)}}),meta:i,acceptanceText:a}}deserializeAction(t){switch(t.__class){case"SetAttributeValueStep:#Microsoft.Crm.Workflow.ObjectModel":{let r=up(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=up(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!==j.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 s1=L(()=>{"use strict";});function Tte(e){return typeof e=="object"&&e!==null?e:null}function rl(e){let t=Tte(e);if(!t)return!1;if(t.__class===Nte){let r=t;return String(r.method)===_te?!0:Array.isArray(r.parameters)&&r.parameters.some(rl)}if(t.__class===Ste)return rl(t.operand);if(t.__class===Ate){let r=t;return rl(r.left)||Array.isArray(r.right)&&r.right.some(rl)}return!1}var Ate,Ste,Nte,_te,l1=L(()=>{"use strict";s1();Ate="BinaryExpression:#Microsoft.Crm.Workflow.Expressions",Ste="UnaryExpression:#Microsoft.Crm.Workflow.Expressions",Nte="MethodCallExpression:#Microsoft.Crm.Workflow.Expressions",_te="23"});function $b(e){return Dte.has(e.type)}function Rb(e,t,r,n,i,o,a){let s=i.get(r);!s||!d1.has(s.attributeType)||n!=="Value"||a?.operator&&!vb(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 Ite(e,t){let r=t.get(e.field);return!!r&&d1.has(r.attributeType)&&vb(e.operator)}function kb(e){return!!(e?.entityType?.trim()&&e.id?.trim())}function Lb(e,t,r){return{nodeId:e,kind:"INVALID_DAY_COUNT",message:`Please enter a whole number of days between 0 and ${Xs}.`,target:t,itemId:r,messageKey:"Validation.InvalidDayCount",messageParams:{max:Xs}}}function u1(e,t,r,n,i,o,a,s){if(i!=="Clear")return;let l=o.get(n);Qf(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 pp(e){if(!e)return!1;for(let t of[...e.trueBranch,...e.falseBranch])if(t.kind==="action"){if($b(t))return!0}else if(pp(t))return!0;return!1}function xb(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=xb(r,t);if(n)return n}}return null}function Ote(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 Pte(e){return e.clauses.length===0&&(e.rawConditionExpression===void 0||Ote(e.rawConditionExpression))}function kte(e){return!!e.clauses?.some(t=>t.source==="BusinessProcess")||rl(e.rawConditionExpression)}function nl(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=nl(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=nl(n,t);if(i)return i}}return null}function Fb(e,t){return{...e,trueBranch:c1(e.trueBranch,t),falseBranch:c1(e.falseBranch,t)}}function c1(e,t){return e.filter(r=>r.id!==t).map(r=>r.kind==="condition"?Fb(r,t):r)}function To(e,t,r){return e.id===t?r(e):{...e,trueBranch:e.trueBranch.map(n=>n.kind==="condition"?To(n,t,r):n),falseBranch:e.falseBranch.map(n=>n.kind==="condition"?To(n,t,r):n)}}function fp(e,t,r){return{...e,trueBranch:e.trueBranch.map(n=>n.kind==="action"&&n.id===t?r(n):n.kind==="condition"?fp(n,t,r):n),falseBranch:e.falseBranch.map(n=>n.kind==="action"&&n.id===t?r(n):n.kind==="condition"?fp(n,t,r):n)}}function f1(e,t,r,n){return To(e,t,i=>({...i,trueBranch:r==="true"?[...i.trueBranch,n]:i.trueBranch,falseBranch:r==="false"?[...i.falseBranch,n]:i.falseBranch}))}function Mb(e){return e.length===1&&e[0].kind==="condition"}function $te(e){let t=0,r=e??void 0;for(;r;){t+=1;let{falseBranch:n}=r;if(Mb(n)){r=n[0];continue}n.length>0&&(t+=1),r=void 0}return t}function xte(e){return!!e&&$te(e)<Lte}function Fte(e,t){if(!e)return;let r=(n,i)=>{if(n.id===t)return i;let o=[];if(Mb(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 p1(e,t,r){let n=Fte(e,t);return!n||!xte(n)?e:To(e,t,i=>m1(i,r))}function m1(e,t){if(Mb(e.falseBranch))return{...e,falseBranch:[m1(e.falseBranch[0],t)]};let r=Ub(t);return r.falseBranch=e.falseBranch,{...e,falseBranch:[r]}}function h1(e,t){let r=nl(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 To(e,r.node.id,o=>({...o,falseBranch:i}))}function g1(e,t,r){let n=nl(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 To(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 Ub(e){return{kind:"condition",id:pr(),displayName:e??"New Condition",clauses:[],logic:"AND",trueBranch:[],falseBranch:[],isCollapsed:!1}}function y1(e,t){let r={kind:"action",id:pr(),type:e,displayName:t??`New ${e}`};switch(e){case"Recommendation":return{...r,type:"Recommendation",field:"",recommendationTitle:"",messageText:"",applyActions:[{id:pr(),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 b1(e){if(!e)return[];let t=[];return v1(e,t),[...new Set(t)]}function v1(e,t){e.clauses.forEach(r=>{r.field&&t.push(r.field)}),[...e.trueBranch,...e.falseBranch].forEach(r=>{r.kind==="condition"?v1(r,t):"field"in r&&r.field&&t.push(r.field)})}function w1(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 E1(e,n,i,!0),r==="Entity"&&C1(e,n),pp(e)||n.push({nodeId:"root",kind:"NO_ACTION",message:"A business rule must include at least one action step.",target:"node"}),n}function C1(e,t){kte(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"&&C1(r,t)})}function E1(e,t,r,n=!1){let i=n&&Pte(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?wa(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(Ln(a.operator)&&a.valueType==="Value"&&!a.value&&!Ite(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(Ln(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 Ln(a.operator)&&a.valueType==="Expression"&&!a.rawExpression&&!Zs(a.expression)?t.push(s==="invalidDayCount"?Lb(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"}):Ln(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"});Ln(a.operator)&&a.valueType==="Value"&&a.value&&fL(r.get(a.field)?.attributeType)&&!ep(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=hL(a);Ln(a.operator)&&a.valueType==="Value"&&a.value&&rp(l)&&!gL(a.value,l)&&t.push({nodeId:e.id,kind:"INVALID_CLAUSE_NUMERIC_VALUE",message:gb(l)?"Please enter a whole number for this clause.":"Please enter a valid number for this clause.",target:"clauseValue",itemId:a.id,messageKey:gb(l)?"Validation.InvalidClauseWholeNumberValue":"Validation.InvalidClauseNumericValue"}),Ln(a.operator)&&a.valueType==="Lookup"&&(kb(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"})),Ln(a.operator)&&Rb(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"&&Rte.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")E1(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&&!ip(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:wa(a.expression);!a.rawExpression&&!Zs(a.expression)&&t.push(s==="invalidDayCount"?Lb(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"&&!kb(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&&(Rb(a.id,a.type,a.field,a.valueType,r,t,{target:"actionValue"}),u1(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:wa(l.expression);!l.rawExpression&&!Zs(l.expression)&&t.push(u==="invalidDayCount"?Lb(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"?kb(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&&(Rb(a.id,"Recommendation",l.field,l.valueType,r,t,{target:"applyActionValue",itemId:l.id}),u1(a.id,"Recommendation","SetFieldValue",l.field,l.valueType,r,t,{target:"applyActionValue",itemId:l.id}))})}}})}var Dte,d1,Rte,Lte,Bb=L(()=>{"use strict";mb();ub();op();Zu();l1();bb();hb();Dte=new Set(["LockUnlock","ShowErrorMessage","Recommendation","SetFieldValue","SetDefaultValue","SetBusinessRequired","SetVisibility"]);d1=new Set(["Lookup","Customer","Owner"]);Rte=new Set(["SetFieldValue","ShowErrorMessage","Recommendation"]);Lte=10});var A1={};Jr(A1,{DAY_COUNT_MAX:()=>Xs,DAY_COUNT_MIN:()=>Eb,DEFAULT_DESERIALIZE_LABELS:()=>Ob,WorkflowJsonMapper:()=>tl,addElseIfInTree:()=>p1,appendToBranch:()=>f1,areFieldKindsCompatible:()=>ip,attributeTypeToWorkflowType:()=>_L,buildWorkflowEntity:()=>rL,collectUsedFields:()=>b1,createEmptyAction:()=>y1,createEmptyCondition:()=>Ub,deserializeWorkflowJson:()=>a1,findNode:()=>xb,findParent:()=>nl,getDefaultOperatorForFieldType:()=>CL,getExpressionModelIssue:()=>wa,getOperatorsForFieldType:()=>np,hasAnyTriggerGeneratingAction:()=>pp,isDayCountValid:()=>Ab,isExpressionModelComplete:()=>Zs,isOperatorCompatible:()=>EL,isTriggerGeneratingAction:()=>$b,moveBranchItemInTree:()=>g1,operatorNeedsValue:()=>Ln,processTriggerFormIdFromScope:()=>db,processTriggerScopeFromScope:()=>cb,removeElseIfInTree:()=>h1,removeNodeFromTree:()=>Fb,serializeToWorkflowJson:()=>o1,supportsClearForActionType:()=>Qf,updateActionInTree:()=>fp,updateConditionInTree:()=>To,validateBusinessRule:()=>w1});var S1=L(()=>{"use strict";ub();nL();Pb();Pb();Bb();Bb();op();Zu();Zu();});var qb=v(mp=>{"use strict";Object.defineProperty(mp,"__esModule",{value:!0});mp.cloneJson=void 0;function Mte(e){return JSON.parse(JSON.stringify(e))}mp.cloneJson=Mte});var x1=v(Do=>{"use strict";Object.defineProperty(Do,"__esModule",{value:!0});Do.BUSINESS_RULE_NULL_GUID=Do.businessRuleRegistration=Do.BusinessRuleAdapter=void 0;var N1=pt(),tc=(S1(),Br(A1)),_1=Qr(),T1=Q(),Ute=qb(),oi=rn(),Bte=Fm(),qte=pt(),Vte=Jo(),Gte=new Set(["ShowErrorMessage","Recommendation"]);function P1(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)?P1(n):Gte.has(String(n.type))):!1}function Wte(e){return R1((0,Ute.cloneJson)(e))}function R1(e){var t,r;let n=i=>(i??[]).map(o=>zte(o)?R1(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 zte(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 jte(e){var t;if(e===null||typeof e!="object"||Array.isArray(e))throw new T1.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 T1.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 Hte="00000000-0000-0000-0000-000000000000";Do.BUSINESS_RULE_NULL_GUID=Hte;var Kte=new Set(["Recommendation","LockUnlock","ShowErrorMessage","SetFieldValue","SetDefaultValue","SetBusinessRequired","SetVisibility"]),Jte=["ruleId","name","description","entityLogicalName","scope","status","rootCondition"],Yte=["kind","id","displayName","logic","clauses","trueBranch","falseBranch"],Qte=["id","field","fieldDisplayName","operator","valueType","value","valueField","lookupValue","expression","rawExpression","valueWorkflowType"];function $n(e,t){return e===void 0?t:{...e,...t}}var Aa=["kind","id","type","displayName","field","stepName","stepLabels"],D1=["valueType","valueWorkflowType","value","valueField","lookupValue","expression","rawExpression"],Xte={Recommendation:[...Aa,"recommendationTitle","messageText","acceptanceText","applyActions","recommendationActionStepMeta"],LockUnlock:[...Aa,"lock"],ShowErrorMessage:[...Aa,"errorMessage","messageLevel","messageActionSteps"],SetFieldValue:[...Aa,...D1],SetDefaultValue:[...Aa,...D1],SetBusinessRequired:[...Aa,"required"],SetVisibility:[...Aa,"visible"]};function ne(e,t){return t===void 0?{}:{[e]:t}}function k1(e){var t;return e==null?void 0:{...e,label:(t=e.label)!==null&&t!==void 0?t:""}}function Vb(e){return{valueType:e.valueType,...ne("valueWorkflowType",e.valueWorkflowType),...ne("value",e.value),...ne("valueField",e.valueField),...ne("lookupValue",k1(e.lookupValue)),...ne("expression",e.expression),...ne("rawExpression",e.rawExpression)}}function L1(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 Zte=["id","field","valueType","valueWorkflowType","value","valueField","lookupValue","expression","rawExpression","stepName","displayName"];function ere(e){return $n(e.bag,{id:e.id,field:e.field,...Vb(e),...ne("stepName",e.stepName),...ne("displayName",e.displayName)})}function tre(e){let t=L1(e,Zte);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 I1(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 O1(e){throw new Error(`Unsupported business-rule action type: ${e.type}`)}var rre=new Set(["INVALID_CLEAR_FOR_FIELD","INVALID_VALUE_TYPE_FOR_FIELD","CLAUSE_VALUE_TOO_LONG","ACTION_VALUE_TOO_LONG"]),nre=new Set,ire="INVALID_CLEAR_FOR_FIELD";function ore(e){let t=n=>{var i;return(0,oi.isJsonObject)(n)&&(n.label===""||n.label===void 0)?{...n,label:String((i=n.id)!==null&&i!==void 0?i:"")}:n},r=n=>{if(!(0,oi.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 hp=class{toArtifact(t){let r=this.residualBag(t,Jte),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 $n(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,tc.deserializeWorkflowJson)(i);return this.toArtifact(o)}needsBaseLanguage(t){return P1(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,tc.serializeToWorkflowJson)(a,(i=n?.baseLanguageCode)!==null&&i!==void 0?i:Vte.DEFAULT_LCID),l=(o=a.ruleId)!==null&&o!==void 0?o:(0,N1.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,tc.createEmptyCondition)():t.rootCondition===null?null:this.conditionFromJson(Wte(jte(t.rootCondition)))},u=this.toArtifact(l);return u.id||(u.id=(0,N1.newId)()),u}assignMissingIds(t){return(0,qte.assignMissingIds)(t)}validate(t){let r=[],n=t.rootCondition;return n==null?r:(0,oi.isJsonObject)(n)?($1(n,"/rootCondition",r),r):(r.push((0,oi.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,oi.issue)("/rootCondition","rule-not-representable",a instanceof Error?a.message:String(a))]}let i=n.rootCondition===null?null:ore(n.rootCondition),o;return r.length===0?o=rre:r.some(a=>a.requiredLevel!==void 0)?o=nre:o=new Set([ire]),(0,tc.validateBusinessRule)(i,r).filter(a=>!o.has(a.kind)).map(a=>(0,oi.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 L1(t,r)}buildWorkflowEntity(t,r){return(0,tc.buildWorkflowEntity)(t,r)}conditionToJson(t){let r=this.residualBag(t,Yte),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,Qte),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,Xte[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(tre),...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",...I1(t)};case"SetDefaultValue":return{...n,type:"SetDefaultValue",...I1(t)};case"SetBusinessRequired":return{...n,type:"SetBusinessRequired",required:t.required};case"SetVisibility":return{...n,type:"SetVisibility",visible:t.visible};default:return O1(t)}}conditionFromJson(t){var r;let n=(r=t.bag)!==null&&r!==void 0?r:{};return $n(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 $n(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",k1(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(!Kte.has(t.type))throw new Error(`Unsupported business-rule action type: ${t.type}`);sre(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 $n(t.bag,{...r,type:"Recommendation",recommendationTitle:t.recommendationTitle,messageText:t.messageText,...ne("acceptanceText",t.acceptanceText),applyActions:t.applyActions.map(ere),...ne("recommendationActionStepMeta",t.recommendationActionStepMeta)});case"LockUnlock":return $n(t.bag,{...r,type:"LockUnlock",lock:t.lock});case"ShowErrorMessage":return $n(t.bag,{...r,type:"ShowErrorMessage",errorMessage:t.errorMessage,...ne("messageLevel",t.messageLevel),...ne("messageActionSteps",t.messageActionSteps)});case"SetFieldValue":return $n(t.bag,{...r,type:"SetFieldValue",...Vb(t)});case"SetDefaultValue":return $n(t.bag,{...r,type:"SetDefaultValue",...Vb(t)});case"SetBusinessRequired":return $n(t.bag,{...r,type:"SetBusinessRequired",required:t.required});case"SetVisibility":return $n(t.bag,{...r,type:"SetVisibility",visible:t.visible});default:return O1(t)}}isConditionJson(t){return Object.prototype.hasOwnProperty.call(t,"clauses")&&Object.prototype.hasOwnProperty.call(t,"logic")&&!Object.prototype.hasOwnProperty.call(t,"type")}};Do.BusinessRuleAdapter=hp;function $1(e,t,r){(0,oi.optionalEnum)(e,"logic",["AND","OR"],t,"condition-logic-invalid",r),(0,oi.childObjects)(e,"clauses",t,"clause",r);for(let n of["trueBranch","falseBranch"])(0,oi.childObjects)(e,n,t,"branchItem",r).forEach(({node:o,index:a})=>{"clauses"in o||"trueBranch"in o||"falseBranch"in o?$1(o,`${t}/${n}/${a}`,r):are(o,`${t}/${n}/${a}`,r)})}function are(e,t,r){e.type==="SetDefaultValue"&&e.valueType==="Clear"&&r.push((0,oi.issue)(`${t}/valueType`,"clear-only-set-field-value","Clear is only supported for SetFieldValue actions."))}function sre(e){if(e.type==="SetDefaultValue"&&e.valueType==="Clear")throw new Error("Clear is only supported for SetFieldValue actions.")}function lre(){return{adapter:new hp,api:Bte.businessRuleApi,publish:(e,t,r)=>(0,_1.publishBoundEntity)(e,r),publishScope:(e,t)=>(0,_1.boundEntityPublishScope)(t)}}Do.businessRuleRegistration=lre});var e$=v(Io=>{"use strict";Object.defineProperty(Io,"__esModule",{value:!0});Io.appRegistration=Io.AppAdapter=Io.HEADER_NAV_BOOLEAN_RULE=void 0;var qi=rn(),Ot=so(),ic=uo(),ure=Qr(),j1=zd(),Gb=Fd(),Wb=lo(),cre=pt(),dre=le(),H1=Jo(),K1=Q(),J1=Ud();Object.defineProperty(Io,"HEADER_NAV_BOOLEAN_RULE",{enumerable:!0,get:function(){return J1.HEADER_NAV_BOOLEAN_RULE}});var vp="7.0.0.0",F1=`<SiteMap IntroducedVersion="${vp}"></SiteMap>`,M1="/_imgs/imagestrips/transparent_spacer.gif",U1="/_imgs/TableIconsFluentV9/document_one_page_sparkle.svg",Y1=["Entity","Url","DefaultDashboard","Page","GenPageId"],rc="sitemapId",B1="sitemapName",zb="sitemapNameUnique",q1="aiDescription",V1="[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}",fre=new RegExp(`^(?:\\{${V1}\\}|${V1})$`);function G1(e,t){if(!fre.test(e.trim()))throw new K1.ValidationError("app",t,[{pointer:"/sitemapId",rule:"app-sitemapid-guid",message:`sitemapId must be a GUID; received '${e}'.`}]);return e.trim()}function W1(e,t,r){if(e===void 0)return r;if(typeof e!="boolean")throw new K1.ValidationError("app",t,[Q1(e)]);return e}function Q1(e){return(0,qi.issue)("/headerAndNavigationRefresh",J1.HEADER_NAV_BOOLEAN_RULE,`headerAndNavigationRefresh must be a boolean, got ${typeof e}`)}function pre(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,dre.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 mre(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 wp=class{constructor(t=H1.DEFAULT_LCID){this.lcid=t}toArtifact(t){let{bag:r,modeledEls:n}=gp(t,"Area");return{id:"",name:"",uniqueName:"",description:"",siteMap:{areas:n.map(i=>this.areaToJson(i)),bag:r},bag:(0,Ot.emptyBag)()}}fromArtifact(t){(0,Wb.installDomShim)();let r=this.assignMissingIds(JSON.parse(JSON.stringify(t))),n=new DOMParser().parseFromString("<root/>","text/xml"),i=this.rootToRaw(r);return(0,Ot.rebuildRaw)(i,(0,ic.domEngine)(n),null)}fromApiResponse(t){var r,n,i,o,a,s,l,u,c,d,f;(0,Wb.installDomShim)();let m=t??{},p=(r=m.$sitemap)!==null&&r!==void 0?r:m,h=(0,ic.parseXmlRoot)((n=p.sitemapxml)!==null&&n!==void 0?n:F1,F1),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:[[rc,(u=(l=p.sitemapid)!==null&&l!==void 0?l:m._sitemapid_value)!==null&&u!==void 0?u:""],[B1,(c=p.sitemapname)!==null&&c!==void 0?c:""],[zb,(d=p.sitemapnameunique)!==null&&d!==void 0?d:""],[q1,(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,Wb.installDomShim)();let w=(0,ic.serializeNode)(this.fromArtifact(t)),C=[],S=[];for(let k of(i=(n=t.siteMap)===null||n===void 0?void 0:n.areas)!==null&&i!==void 0?i:[])for(let I of(o=k.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,Ot.emptyBag)();return{sitemapId:nc(O,rc)||(t.sitemapId?G1(t.sitemapId,t.id):""),sitemapxml:w,sitemapname:nc(O,B1)||t.name,...nc(O,zb)?{sitemapNameUnique:nc(O,zb)}:{},appModuleId:t.id,appModuleName:t.name,appModuleDescription:t.description,...t.aiDescription!==void 0&&t.aiDescription!==(r?r.aiDescription:nc(O,q1))?{appModuleAiDescription:t.aiDescription}:{},appModuleUniqueName:t.uniqueName,...t.iconWebResourceId?{iconWebResourceId:t.iconWebResourceId}:{},...t.headerAndNavigationRefresh===void 0?{}:{appSettings:{[Gb.HEADER_AND_NAVIGATION_REFRESH]:W1(t.headerAndNavigationRefresh,(l=t.id)!==null&&l!==void 0?l:"(unknown)",!0)?Gb.APP_SETTING_ON:Gb.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,cre.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:G1(t.sitemapId,u)}:{},...t.iconWebResourceId?{iconWebResourceId:t.iconWebResourceId}:{},headerAndNavigationRefresh:W1(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(Kb):Array.isArray(r.areas)?r.areas.forEach(Kb):Array.isArray(r.groups)?Kb(r):Array.isArray(r.subAreas)?Z1(r):"type"in r&&Cp(r,"subarea"),t}validate(t){let r=[],n=t.published;n!==void 0&&typeof n!="boolean"&&r.push((0,qi.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(Q1(o)),i==null)return r;if(!(0,qi.isJsonObject)(i))return r.push((0,qi.issue)("/siteMap","sitemap-must-be-object",`siteMap must be a JSON object, got ${typeof i}`)),r;let a=(0,qi.childObjects)(i,"areas","/siteMap","area",r),s=new Map;return a.forEach(({node:l,index:u})=>{let c=`/siteMap/areas/${u}`;(0,qi.childObjects)(l,"groups",c,"group",r).forEach(({node:f,index:m})=>{let p=`${c}/groups/${m}`;(0,qi.childObjects)(f,"subAreas",p,"subArea",r).forEach(({node:g,index:b})=>{let w=`${p}/subAreas/${b}`;(0,qi.optionalEnum)(g,"type",["Entity","URL","DashBoard","CustomPage","GenPage"],w,"subarea-type-invalid",r);let C=pre(g);if(!C)return;let S=s.get(C);if(S===void 0){s.set(C,w);return}r.push((0,qi.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,j1.mainFormSetShapeIssues)((r=t.components)===null||r===void 0?void 0:r.mainFormsByTable,mre(t))}applyServerIdentity(t,r){let n=r[rc];if(!n)return;t.bag||(t.bag=(0,Ot.emptyBag)());let i=t.bag.a.find(o=>o[0]===rc);i?i[1]=n:t.bag.a.push([rc,n])}areaToJson(t){var r;let{bag:n,modeledEls:i}=gp(t,"Group"),o={id:(r=t.getAttribute("Id"))!==null&&r!==void 0?r:"",title:jb(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}=gp(t,"SubArea");return{id:(r=t.getAttribute("Id"))!==null&&r!==void 0?r:"",title:jb(t,this.lcid),subAreas:i.map(o=>this.subAreaToJson(o)),bag:n}}subAreaToJson(t){var r;let{bag:n}=gp(t,null),i=hre(t),o={id:(r=t.getAttribute("Id"))!==null&&r!==void 0?r:"",type:i,title:jb(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!==M1&&(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,Ot.emptyBag)(),l=yp(a)?[["IntroducedVersion",vp]]:[],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,Ot.mergeAttrs)(a.a,l),c:(0,Ot.spliceChildren)(a.c,u)}}areaToRaw(t){var r,n;let i=(r=t.bag)!==null&&r!==void 0?r:(0,Ot.emptyBag)(),o=yp(i),a=[],s=[];t.id&&a.push(["Id",t.id]),o&&a.push(["ShowGroups","true"],["ResourceId","SitemapDesigner.NewTitle"],["DescriptionResourceId","SitemapDesigner.NewTitle"],["IntroducedVersion",vp]),t.icon!==void 0?a.push(["Icon",t.icon]):bp(i.a,"Icon")&&s.push("Icon"),t.vectorIcon!==void 0?a.push(["VectorIcon",t.vectorIcon]):bp(i.a,"VectorIcon")&&s.push("VectorIcon");let l=((n=t.groups)!==null&&n!==void 0?n:[]).map(c=>this.groupToRaw(c)),u=Hb((0,Ot.spliceChildren)(i.c,l),t.title,o,this.lcid);return{n:"Area",a:(0,Ot.mergeAttrs)(i.a,a,s),c:u}}groupToRaw(t){var r,n;let i=(r=t.bag)!==null&&r!==void 0?r:(0,Ot.emptyBag)(),o=yp(i),a=[];t.id&&a.push(["Id",t.id]),o&&a.push(["ResourceId","SitemapDesigner.NewGroup"],["DescriptionResourceId","SitemapDesigner.NewGroup"],["ToolTipResourseId","SitemapDesigner.Unknown"],["IntroducedVersion",vp],["IsProfile","false"]);let s=((n=t.subAreas)!==null&&n!==void 0?n:[]).map(u=>this.subAreaToRaw(u)),l=Hb((0,Ot.spliceChildren)(i.c,s),t.title,o,this.lcid);return{n:"Group",a:(0,Ot.mergeAttrs)(i.a,a),c:l}}subAreaToRaw(t){var r;let n=(r=t.bag)!==null&&r!==void 0?r:(0,Ot.emptyBag)(),i=yp(n),o=yre(n.a,t.type),a=[],s=[];t.id&&a.push(["Id",t.id]);let l=!i&&!n.a.some(([c])=>Y1.includes(c));vre(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]):bp(o,"Icon",M1)&&s.push("Icon"),t.vectorIcon!==void 0?a.push(["VectorIcon",t.vectorIcon]):bp(o,"VectorIcon")?t.type==="GenPage"?a.push(["VectorIcon",U1]):s.push("VectorIcon"):t.type==="GenPage"&&!gre(o,"VectorIcon")&&a.push(["VectorIcon",U1]);let u=Hb((0,Ot.spliceChildren)(n.c,[]),t.title,i,this.lcid);return{n:"SubArea",a:(0,Ot.mergeAttrs)(o,a,s),c:u}}};Io.AppAdapter=wp;function gp(e,t){let r=(0,ic.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,Ot.rawFromNode)((0,ic.nodeLikeFromDom)(l))}),a+=1)}return{bag:{a:r,c:n},modeledEls:i}}function z1(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 jb(e,t){var r;let n=z1(e,"Titles")[0];if(!n)return"";let o=z1(n,"Title").find(a=>a.getAttribute("LCID")===String(t));return o&&(r=o.getAttribute("Title"))!==null&&r!==void 0?r:""}function hre(e){return e.getAttribute("GenPageId")?"GenPage":e.getAttribute("Entity")?"Entity":e.getAttribute("Page")?"CustomPage":e.getAttribute("DefaultDashboard")?"DashBoard":"URL"}function yp(e){return e.a.length===0&&e.c.length===0}function gre(e,t){return e.some(([r])=>r===t)}function bp(e,t,r){let n=e.find(([o])=>o===t),i=n?.[1];return!!i&&i!==r}function nc(e,t){let r=e.a.find(([n])=>n===t);return r?r[1]:void 0}function yre(e,t){let r=bre(t);return e.filter(([n])=>!Y1.includes(n)||r.has(n)).map(n=>[n[0],n[1]])}function bre(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 vre(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 Hb(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]=wre(e[i],t,n),o}return r?[Cre(t,n),...e]:e}function wre(e,t,r){let n=!1,i=e.c.map(o=>!n&&o.n==="Title"&&Ere(o,"LCID")===String(r)?(n=!0,{n:o.n,a:(0,Ot.mergeAttrs)(o.a,[["Title",t]]),c:o.c}):o);return n||i.unshift(X1(t,r)),{n:e.n,a:e.a.map(o=>[o[0],o[1]]),c:i}}function Cre(e,t){return{n:"Titles",a:[],c:[X1(e,t)]}}function X1(e,t){return{n:"Title",a:[["LCID",String(t)],["Title",e]],c:[]}}function Ere(e,t){let r=e.a.find(([n])=>n===t);return r?r[1]:void 0}function Are(e){let t="0123456789abcdef",r="";for(let n=0;n<e;n+=1)r+=t[Math.floor(Math.random()*t.length)];return r}function Cp(e,t){e&&(typeof e.id!="string"||e.id.length===0)&&(e.id=`${t}_${Are(8)}`)}function Kb(e){var t;Cp(e,"area");for(let r of(t=e.groups)!==null&&t!==void 0?t:[])Z1(r)}function Z1(e){var t;Cp(e,"group");for(let r of(t=e.subAreas)!==null&&t!==void 0?t:[])Cp(r,"subarea")}function Sre(e=H1.DEFAULT_LCID){return{adapter:new wp(e),api:j1.appApi,languageSensitive:!0,publish:(t,r)=>(0,ure.publishAppModule)(t,r),publishScope:t=>({envelope:"appmodule",targetIds:[t]}),rebaselineAfterPublish:"bracket"}}Io.appRegistration=Sre});var t$={};Jr(t$,{ActionType:()=>Yb,AppActionOrigin:()=>iv,AppActionVisibilityType:()=>nv,ButtonType:()=>Xb,CannotUpdateAppActionColumns:()=>Nre,Context:()=>ev,IconType:()=>Qb,Location:()=>Zb,OnClickEventType:()=>rv,Scope:()=>tv,VisibilityType:()=>Jb});var Jb,Yb,Qb,Xb,Zb,ev,tv,rv,nv,iv,Nre,r$=L(()=>{"use strict";(function(e){e[e.NotSupported=0]="NotSupported",e[e.Show=1]="Show",e[e.ClassicRules=2]="ClassicRules",e[e.Expression=3]="Expression"})(Jb||(Jb={}));(function(e){e[e.NotSupported=0]="NotSupported",e[e.None=1]="None",e[e.JavaScript=2]="JavaScript",e[e.Expression=3]="Expression"})(Yb||(Yb={}));(function(e){e[e.NoIcon=0]="NoIcon",e[e.UseIcon=1]="UseIcon",e[e.UseWebResource=2]="UseWebResource"})(Qb||(Qb={}));(function(e){e[e.Standard=0]="Standard",e[e.Dropdown=1]="Dropdown",e[e.Split=2]="Split",e[e.Group=3]="Group"})(Xb||(Xb={}));(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"})(Zb||(Zb={}));(function(e){e[e.All=0]="All",e[e.Entity=1]="Entity"})(ev||(ev={}));(function(e){e[e.App=0]="App",e[e.Entity=1]="Entity",e[e.Global=2]="Global"})(tv||(tv={}));(function(e){e[e.None=0]="None",e[e.Formula=1]="Formula",e[e.JavaScript=2]="JavaScript"})(rv||(rv={}));(function(e){e[e.None=0]="None",e[e.Formula=1]="Formula",e[e.ClassicRules=2]="ClassicRules"})(nv||(nv={}));(function(e){e[e.Default=0]="Default",e[e.Migrated=1]="Migrated",e[e.MigratedClone=2]="MigratedClone"})(iv||(iv={}));Nre=["appactionid","appmoduleid","context","contextvalue","location","name","type","uniquename","isdisabled","origin"]});var u$=v(Pt=>{"use strict";Object.defineProperty(Pt,"__esModule",{value:!0});Pt.assertOneWritePerRow=Pt.commandApi=Pt.COMMAND_DUPLICATE_ROW_CODE=Pt.COMMAND_ROW_NOT_IN_BAR_CODE=Pt.COMMAND_TABLE_MISMATCH_CODE=void 0;var ov=Lt(),Lr=ye(),Vi=Q(),$r=le();Pt.COMMAND_TABLE_MISMATCH_CODE="COMMAND_TABLE_MISMATCH";Pt.COMMAND_ROW_NOT_IN_BAR_CODE="COMMAND_ROW_NOT_IN_BAR";Pt.COMMAND_DUPLICATE_ROW_CODE="COMMAND_DUPLICATE_ROW";var _re="OnClickEventJavaScriptWebResourceId($select=name,webresourceid),IconWebResourceId($select=name,webresourceid)";async function av(e,t){let r=`/EntityDefinitions(LogicalName='${(0,$r.odataPathLiteral)(t)}')${(0,$r.odataQuery)([["$select","MetadataId"]])}`,i=(0,Lr.ensureSuccess)(await e.get(r),e.apiUrl(r)).body,o=i?.MetadataId;return o?(0,$r.normalizeGuid)(o,"entityMetadataId"):""}function sv(e,t){return t?`_contextentity_value eq ${t}`:`contextvalue eq '${(0,$r.odataLiteral)(e)}'`}function oc(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 n$(e,t){let r=e.entityLogicalName;if(t===void 0)return r;if(typeof r!="string"||r.toLowerCase()!==t.toLowerCase())throw new Vi.SdkError(Pt.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 i$(e,t,r){let n=await av(e,t);if(r){let i=(0,$r.normalizeGuid)(r,"entityMetadataId");if(i!==n)throw new Vi.SdkError(Pt.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. `+oc(t))}return n}Pt.commandApi={async get(e,t){let r=t,n=await av(e,r),i=sv(r,n),o=`/appactions${(0,$r.odataQuery)([["$expand",_re],["$filter",i]])}`,a,s=await(0,ov.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,$r.normalizeGuid)(d,"appactionid")]=typeof f=="string"?f:null}}return{raw:l,etag:a?(0,Lr.readEtag)(a):null,memberEtags:u}},async list(e,t){let r=t?.entityLogicalName;return r?[{type:"command",id:r,name:`${r} commands`,entityLogicalName:r,isDirty:!1}]:[]},async create(e,t,r){let n=t,i=n$(n,r),o=await i$(e,i,n.entityMetadataId);return o$(e,i,{...n,entityMetadataId:o},!1)},async update(e,t,r,n,i){let o=r,a=n$(o,t),s=await i$(e,a,o.entityMetadataId);return o$(e,a,{...o,entityMetadataId:s},!0,i)},async delete(e,t){let r=await av(e,t),n=`/appactions${(0,$r.odataQuery)([["$select","appactionid"],["$filter",sv(t,r)]])}`,i=await(0,ov.collectPages)(e,n,"deleteArtifact('command')");for(let o of i)o.appactionid&&await(0,Lr.deleteRecord)(e,"appactions",o.appactionid)}};async function o$(e,t,r,n,i){let o=r.entityMetadataId?(0,$r.normalizeGuid)(r.entityMetadataId,"entityMetadataId"):"",a=await Dre(e,t,r,o,n,i),s={};try{await Ore(e,a,o,s)}catch(l){throw(0,Vi.withPartialTokens)(l,{memberEtags:s})}return{id:r.entityLogicalName,etag:null,memberEtags:s}}function lv(e){return e.replace(/[{}]/g,"").toLowerCase()}function l$(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=lv(o),l=n.get(s);if(l===void 0){n.set(s,a);continue}throw new Vi.SdkError(Pt.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.`)}}Pt.assertOneWritePerRow=l$;var Tre={entities:/^\/entities\(([^()]+)\)$/,appactions:/^\/appactions\(([^()]+)\)$/};function a$(e,t){let r=Tre[t].exec(e);return r?lv(r[1]):void 0}async function Dre(e,t,r,n,i,o){var a,s;l$(t,r);let l=Pre(r.rows),u=new Set(l.map(f=>lv(f.appactionid))),c={writes:[],deletes:[]};for(let f of l){let m=f.body["[email protected]"];if(m!==void 0&&!(typeof m=="string"&&n!==""&&a$(m,"entities")===n))throw new Vi.SdkError(Pt.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"}). `+oc(t));let p=f.body["[email protected]"];if(typeof p=="string"){let h=a$(p,"appactions");if(h===void 0||!u.has(h))throw new Vi.SdkError(Pt.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. `+oc(t))}if(i&&f.exists){let h=(0,$r.normalizeGuid)(f.appactionid,"id"),g=(a=o?.[h])!==null&&a!==void 0?a:f.etag;if(!(0,Lr.isVersionToken)(g))throw s$(t,h,"update",g);c.writes.push({kind:"patch",row:f,id:h,token:g})}else{if(m===void 0&&!n)throw new Vi.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,$r.normalizeGuid)(f,"id"),p=o?.[m];if(!(0,Lr.isVersionToken)(p))throw s$(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 Ire(e,t,n),m=d.find(p=>!f.has(p.id));if(m)throw new Vi.SdkError(Pt.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. `+oc(t))}return c}function s$(e,t,r,n){return new Vi.SdkError(Lr.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. `+oc(e))}async function Ire(e,t,r){let n=`/appactions${(0,$r.odataQuery)([["$select","appactionid"],["$filter",sv(t,r)]])}`,i=await(0,ov.collectPages)(e,n,"pushArtifact('command') bar membership"),o=new Set;for(let a of i)typeof a.appactionid=="string"&&o.add((0,$r.normalizeGuid)(a.appactionid,"appactionid"));return o}async function Ore(e,t,r,n){for(let i of t.writes)if(i.kind==="patch"){let o=(0,Lr.echoWrite)("appactionid",{"If-Match":i.token}),a=`/appactions(${i.id})${o.query}`,s=(0,Lr.ensureSuccess)(await e.patch(a,i.row.body,o.options),e.apiUrl(a));n[i.id]=(0,Lr.readEtag)(s)}else{let o=(0,Lr.echoWrite)("appactionid"),a=`/appactions${o.query}`,s={...i.row.body};s["[email protected]"]===void 0&&(s["[email protected]"]=`/entities(${r})`);let l=(0,Lr.ensureSuccess)(await e.post(a,s,o.options),e.apiUrl(a)),u=(0,Lr.readCreatedId)(l,"appactionid");u&&(n[(0,$r.normalizeGuid)(u,"appactionid")]=(0,Lr.readEtag)(l))}for(let{id:i,token:o}of[...t.deletes].reverse())await(0,Lr.deleteRecord)(e,"appactions",i,o),delete n[i]}function Pre(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 N$=v(il=>{"use strict";Object.defineProperty(il,"__esModule",{value:!0});il.commandRegistration=il.CommandAdapter=void 0;var ct=(r$(),Br(t$)),c$=Qr(),wt=rn(),p$=u$(),m$=pt(),ol=le(),h$=Q(),dv="$ClientSvg:",fv=".svg",Rre=2,kre=1,Lre=1,g$="entityMetadataId",$re=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"]),Ep=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 h$.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=Bre(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:Fre(g,f,w$(h),c)});return{id:c,entityLogicalName:c,commandBars:Ure(p),bag:{a:[[g$,(l=t.entityMetadataId)!==null&&l!==void 0?l:""]]}}}fromArtifact(t){return{entityLogicalName:t.entityLogicalName,entityMetadataId:mv(t),appActions:uv(t).map(r=>r.row)}}fromApiResponse(t){return this.toArtifact(t??{})}toApiPayload(t,r){let n=new Set(r?uv(r).map(l=>l.appactionid):[]),i=uv(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?Zre(l.row):S$(l.row)}}),s=[...n].filter(l=>!o.has(l));return(0,p$.assertOneWritePerRow)(t.entityLogicalName,{rows:a,deletedRowIds:s}),{entityLogicalName:t.entityLogicalName,entityMetadataId:mv(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,m$.assignMissingIds)(t)}normalize(t){let r=Wre(t),n=!1,i=(Array.isArray(t.commandBars)?t.commandBars:[]).map(o=>{let a=(0,wt.isJsonObject)(o)&&Array.isArray(o.groups)?o.groups:void 0;if(!a)return o;let s=!1,l=a.map(u=>{let c=(0,wt.isJsonObject)(u)&&Array.isArray(u.controls)?u.controls:void 0;if(!c)return u;let d=c.map(f=>E$(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,wt.childObjects)(t,"commandBars","","commandBar",r).forEach(({node:i,index:o})=>{let a=`/commandBars/${o}`;(0,wt.optionalEnum)(i,"location",["MainTab","ContextualTab","HomeTab"],a,"bar-location-invalid",r),(0,wt.childObjects)(i,"groups",a,"group",r).forEach(({node:l,index:u})=>{let c=`${a}/groups/${u}`;Np(l.bag)||((0,wt.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."})),y$((0,wt.childObjects)(l,"controls",c,"control",r),`${c}/controls`,r)})}),r}};il.CommandAdapter=Ep;function Np(e){let t=e?.a;return Array.isArray(t)&&t.length>0}function y$(e,t,r){e.forEach(({node:n,index:i})=>{let o=`${t}/${i}`;Np(n.bag)||(0,wt.optionalGuidId)(n,"id",o,"control-id-invalid",r),(0,wt.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,wt.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,wt.isJsonObject)(n.action)?(0,wt.optionalEnum)(n.action,"type",["javascript"],`${o}/action`,"action-type-invalid",r):r.push((0,wt.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,wt.childObjects)(n,"children",o,"control",r);s.length>0&&y$(s,`${o}/children`,r)})}function pv(e){return{a:Object.entries(e)}}function xre(e){return Object.fromEntries(e.a)}function ac(e,t){if(e){for(let[r,n]of e.a)if(r===t)return n}}function mv(e){let t=ac(e.bag,g$);return typeof t=="string"?t:""}function Fre(e,t,r,n){var i,o;let a=[],s=[];for(let l of Sp(e))l.type===ct.ButtonType.Group?a.push({id:v$(l.name,n),title:typeof l.grouptitle=="string"?l.grouptitle:"",controls:Sp((o=t.get((i=l.appactionid)!==null&&i!==void 0?i:""))!==null&&o!==void 0?o:[]).map(u=>Ap(u,t,r,n)),bag:pv(l)}):s.push(Ap(l,t,r,n));return s.length>0&&a.unshift({id:Xre(n,r),title:"",controls:s}),a}function hv(e){let t=e.bag?ac(e.bag,"appactionid"):void 0;return typeof t=="string"&&t.trim()!==""?t:e.id}function Ap(e,t,r,n){var i,o,a,s,l;let u=v$(e.name,n),c={id:u,type:qre(e.type),label:typeof e.buttonlabeltext=="string"?e.buttonlabeltext:"",command:typeof e.appactionid=="string"?e.appactionid:u,bag:pv(e)},d=b$(e);d&&(c.icon=d);let f=Mre(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 Sp(m))if(g.type===ct.ButtonType.Group){let b=(o=g.appactionid)!==null&&o!==void 0?o:"",w=pv(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 Sp((l=t.get((s=g.appactionid)!==null&&s!==void 0?s:""))!==null&&l!==void 0?l:[])){let O=Ap(S,t,r,n);p.push(O),C.push(hv(O))}h.push({id:b,bag:w,childIds:C})}else p.push(Ap(g,t,r,n));c.children=p,h.length>1&&(c.flyoutGroups=h)}return c}function b$(e){var t;if(!((t=e.IconWebResourceId)===null||t===void 0)&&t.name)return e.IconWebResourceId.name;if(e.fonticon)return e.fonticon.startsWith(dv)?e.fonticon.slice(dv.length)+fv:e.fonticon}function Mre(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 d$(e){return typeof e.sequence=="number"?e.sequence:typeof e.buttonsequencepriority=="number"?e.buttonsequencepriority:0}function Sp(e){return[...e].sort((t,r)=>d$(t)-d$(r))}function Ure(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 v$(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 Bre(e){switch(e){case ct.Location.Form:case ct.Location.QuickForm:return"MainTab";case ct.Location.HomePageGrid:case ct.Location.Dashboard:return"HomeTab";default:return"ContextualTab"}}function w$(e){switch(e){case"MainTab":return ct.Location.Form;case"HomeTab":return ct.Location.HomePageGrid;default:return ct.Location.SubGridStandard}}function qre(e){switch(e){case ct.ButtonType.Dropdown:return"FlyoutAnchor";case ct.ButtonType.Split:return"SplitButton";default:return"Button"}}function Vre(e){switch(e){case"FlyoutAnchor":return ct.ButtonType.Dropdown;case"SplitButton":return ct.ButtonType.Split;default:return ct.ButtonType.Standard}}function Gre(e){var t;return e.bag&&e.bag.a.length>0?!0:((t=e.title)!==null&&t!==void 0?t:"").length>0}function C$(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 uv(e,t=new Set){var r,n,i,o;let a=[],s=mv(e);for(let l of(r=e.commandBars)!==null&&r!==void 0?r:[]){let u=w$(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=>!C$(m,t)),f=0;for(let m of(i=l.groups)!==null&&i!==void 0?i:[]){let p;if(Gre(m)){let h=jre(m,u,void 0,e,s);a.push(h),p=h.appactionid}for(let h of(o=m.controls)!==null&&o!==void 0?o:[])A$(h,u,p,e,s,a,d?f:void 0,t),f+=1}}return a}function E$(e,t){if(!(0,wt.isJsonObject)(e))return e;let r=e.children,n=r,i=!1;Array.isArray(r)&&(n=r.map(s=>E$(s,t)),i=n.some((s,l)=>s!==r[l]));let o=!Np(e.bag)&&(typeof e.id!="string"||e.id.trim()==="");if(!o&&!i)return e;let a;if(o){do a=(0,m$.newId)();while(t.has(a));t.add(a)}return{...e,...a!==void 0?{id:a}:{},...i?{children:n}:{}}}function Wre(e){let t=new Set,r=(o,...a)=>{if((0,wt.isJsonObject)(o))for(let s of[...a.map(l=>o[l]),Np(o.bag)?ac(o.bag,"appactionid"):void 0])typeof s=="string"&&s.trim()!==""&&t.add(s.toLowerCase())},n=o=>{(0,wt.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,wt.isJsonObject)(o)?o.groups:void 0;(Array.isArray(a)?a:[]).forEach(s=>{r(s,"id");let l=(0,wt.isJsonObject)(s)?s.controls:void 0;(Array.isArray(l)?l:[]).forEach(n)})}),t}function A$(e,t,r,n,i,o,a,s=new Set){var l;let u=zre(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=>!C$(h,s)),f=(h,g,b)=>{A$(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=>[hv(S),S])),g=new Set,b=0,w;for(let[S,O]of m.entries()){let k=O.id||(S===0?cv(u.appactionid):yv("flyout-group",`${u.appactionid}#${S}`)),I=f$(k,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??cv(u.appactionid);for(let S of c){let O=hv(S);g.has(O)||(g.add(O),f(S,C,b),b+=1)}return}let p=e.flyoutGroupId||cv(u.appactionid);o.push(f$(p,t,u.appactionid,n,i,e.flyoutGroupBag));for(let[h,g]of c.entries())f(g,p,h)}function zre(e,t,r,n,i,o){let a=gv(e,t,r,n,i),s=a.row;o!==void 0&&typeof s.sequence!="number"&&(s.sequence=o);let l=b$(s);return e.location!==void 0&&(s.location=e.location),s.type=Vre(e.type),s.buttonlabeltext=e.label,Kre(s,e.icon,l),Yre(s,e.action),Jre(s),e.hidden!==void 0&&(s.hidden=e.hidden),e.disabled!==void 0&&(s.isdisabled=e.disabled),{...a,row:s}}function jre(e,t,r,n,i){let o=gv(e,t,r,n,i);return o.row.type=ct.ButtonType.Group,o.row.grouptitle=e.title,o}function f$(e,t,r,n,i,o){let a=gv({id:e,bag:o},t,r,n,i),s=a.row;return s["[email protected]"]=`/appactions(${(0,ol.normalizeGuid)(r,"Command flyout group id")})`,s.type=ct.ButtonType.Group,s.grouptitle===void 0&&(s.grouptitle=""),s.isgrouptitlehidden===void 0&&(s.isgrouptitlehidden=!0),a}function gv(e,t,r,n,i){let o,a,s,l;if(e.bag&&e.bag.a.length>0){o=xre(e.bag),a=!0;let u=ac(e.bag,"@odata.etag");s=typeof u=="string"?u:null;let c=ac(e.bag,"appactionid");l=typeof c=="string"&&c?c:e.id}else{if(typeof e.id!="string"||e.id.trim()==="")throw new h$.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=Hre(l,t,n,i),a=!1,s=null}return r?o["[email protected]"]=`/appactions(${(0,ol.normalizeGuid)(r,"Command parent appaction id")})`:a&&typeof o._parentappactionid_value=="string"&&o._parentappactionid_value&&o.type!==ct.ButtonType.Group&&(o["[email protected]"]=null),delete o._parentappactionid_value,{appactionid:l,exists:a,etag:s,row:o}}function Hre(e,t,r,n){let i={appactionid:e,name:`${e}!${e.replace(/-/g,"").slice(0,32)}`,uniquename:"",location:t,context:ct.Context.Entity,contextvalue:r.entityLogicalName,scope:ct.Scope.Entity};return n&&(i["[email protected]"]=`/entities(${(0,ol.normalizeGuid)(n,"Command context entity metadata id")})`),i}function Kre(e,t,r){if(t===r){let n=e._iconwebresourceid_value;typeof n=="string"&&n&&!e.fonticon&&(e["[email protected]"]=`/webresourceset(${(0,ol.normalizeGuid)(n,"Command icon web resource id")})`);return}if(t===void 0){e.fonticon="",e.IconWebResourceId=null;return}e.fonticon=t.toLowerCase().endsWith(fv)?dv+t.slice(0,t.length-fv.length):t,e.IconWebResourceId=null}function Jre(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,ol.normalizeGuid)(o,`Command ${i}`);e[`${i}@odata.bind`]=`/canvasapps(${a})`};e.onclickeventtype===kre&&t("_onclickeventformulacomponentlibraryid_value","OnClickEventFormulaComponentLibraryId");let r=e.visibilitytype;(!r||r===Lre)&&t("_visibilityformulacomponentlibraryid_value","VisibilityFormulaComponentLibraryId")}function Yre(e,t){if(!(!t||t.type!=="javascript")){if(e.onclickeventtype=Rre,t.webResourceId){let r=(0,ol.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 Qre(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 yv(e,t){let r="";for(let n=0;n<4;n+=1)r+=Qre(`${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 cv(e){return yv("flyout-group",e)}function Xre(e,t){return yv("loose-group",`${e}|${t}`)}function S$(e){let t={...e};for(let r of $re)delete t[r];return t}function Zre(e){let t=S$(e);for(let r of ct.CannotUpdateAppActionColumns)delete t[r];return t}function ene(){return{adapter:new Ep,api:p$.commandApi,publish:(e,t,r)=>(0,c$.publishBoundEntity)(e,r),publishScope:(e,t)=>(0,c$.boundEntityPublishScope)(t)}}il.commandRegistration=ene});var T$=v(_p=>{"use strict";Object.defineProperty(_p,"__esModule",{value:!0});_p.chartApi=void 0;var tne=Lt(),xr=ye(),Sa=le(),_$="savedqueryvisualizationid,name,description,primaryentitytypecode,datadescription,presentationdescription,charttype,type,isdefault",rne="savedqueryvisualizationid,name,primaryentitytypecode,charttype,isdefault";_p.chartApi={async get(e,t){let r=(0,Sa.normalizeGuid)(t,"id"),n=await(0,xr.readRowEtag)(e,"savedqueryvisualizations","savedqueryvisualizationid",r),i=`/savedqueryvisualizations(${r})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,Sa.odataQuery)([["$select",_$]]);return{raw:(0,xr.ensureSuccess)(await e.get(i),e.apiUrl(i)).body,etag:n}},async readContentThenToken(e,t){let r=(0,Sa.normalizeGuid)(t,"id"),n=`/savedqueryvisualizations(${r})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,Sa.odataQuery)([["$select",_$]]),i=(0,xr.ensureSuccess)(await e.get(n),e.apiUrl(n)),o=await(0,xr.readRowEtag)(e,"savedqueryvisualizations","savedqueryvisualizationid",r);return{raw:i.body,etag:o}},async list(e,t){let r=`/savedqueryvisualizations${(0,Sa.odataQuery)([["$select",rne],["$filter",t?.entityLogicalName?`primaryentitytypecode eq '${(0,Sa.odataLiteral)(t.entityLogicalName)}'`:void 0]])}`;return(await(0,tne.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,xr.echoWrite)("savedqueryvisualizationid"),o=`/savedqueryvisualizations${i.query}`,a=(0,xr.ensureSuccess)(await e.post(o,(0,xr.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,xr.resolveCreatedId)(a,"savedqueryvisualizationid","chart",r),etag:(0,xr.readEtag)(a)}},async update(e,t,r,n){let i=r,o=(0,Sa.normalizeGuid)(t,"id"),a=(0,xr.echoWrite)("savedqueryvisualizationid",{"If-Match":(0,xr.requireEtag)(n,"chart",o)}),s=`/savedqueryvisualizations(${o})${a.query}`,l=(0,xr.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,xr.readEtag)(l)}},delete(e,t){return(0,xr.deleteRecord)(e,"savedqueryvisualizations",t)}}});var W$=v(sl=>{"use strict";Object.defineProperty(sl,"__esModule",{value:!0});sl.chartRegistration=sl.ChartAdapter=void 0;var bv=so(),D$=rn(),ai=uo(),I$=Qr(),nne=T$(),vv=lo(),ine=pt(),one=["Column","StackedColumn","StackedColumn100","Bar","StackedBar","StackedBar100","Area","StackedArea","StackedArea100","Line","Pie","Doughnut","Funnel","Tag"],ane=new Map(one.map(e=>[e.toLowerCase(),e]));function L$(e){var t;return e&&(t=ane.get(e.toLowerCase()))!==null&&t!==void 0?t:"Column"}function sne(){return'<Chart Palette="BrightPastel"><Series><Series ChartType="Column" ChartArea="Default" /></Series><ChartAreas><ChartArea Name="Default" /></ChartAreas><Legends><Legend Name="Default" /></Legends></Chart>'}function lne(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 Tp=class{toArtifact(t){var r,n,i,o,a,s,l;(0,vv.installDomShim)();let u=(r=t.datadescription)!==null&&r!==void 0?r:"",c=(n=t.presentationdescription)!==null&&n!==void 0?n:"",d=(0,ai.parseXmlRoot)(u,"<datadefinition/>"),f=(0,ai.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:Dp(f),isDefault:(l=t.isdefault)!==null&&l!==void 0?l:!1,series:F$(d),categories:M$(d),presentation:$$(f),dataBag:u?(0,ai.projectElementBag)(d):void 0,presentationBag:c?(0,ai.projectElementBag)(f):void 0,rowBag:une(t.charttype,t.type)}}fromArtifact(t){(0,vv.installDomShim)();let{datadescription:r,presentationdescription:n}=cne(t);return{savedqueryvisualizationid:t.id,name:t.name,description:t.description,primaryentitytypecode:t.entityLogicalName,datadescription:r,presentationdescription:n,charttype:O$(t.rowBag,"charttype"),type:O$(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,vv.installDomShim)();let u=(r=t.entityLogicalName)!==null&&r!==void 0?r:"";return{id:(n=t.id)!==null&&n!==void 0?n:(0,ine.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,D$.childObjects)(n,"series","","series",r),(0,D$.childObjects)(n,"categories","","category",r),r}};sl.ChartAdapter=Tp;function une(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 O$(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 Dp(e){let t=e.getElementsByTagName("Series");for(let r=0;r<t.length;r+=1)if(t[r].getAttribute("ChartType"))return L$(t[r].getAttribute("ChartType"));return"Column"}function $$(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 Ip(e){return e.getElementsByTagName("fetch")[0]}function x$(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 F$(e){let t=Ip(e);if(!t)return[];let r=x$(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=L$(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 M$(e){var t;let r=Ip(e);if(!r)return[];let n=x$(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 cne(e){var t,r;let n=(t=e.series)!==null&&t!==void 0?t:[],i=(r=e.categories)!==null&&r!==void 0?r:[];if(!P$(e.dataBag)||!P$(e.presentationBag)){let c=lne({...e,series:n,categories:i});return{datadescription:c,presentationdescription:Ine(e,c)}}let o=new DOMParser().parseFromString("<root/>","text/xml"),a=R$(e.dataBag,"datadefinition",o),s=R$(e.presentationBag,"Chart",o),l=e.chartType||Dp(s),u=F$(a);if(!wv(n,u)){let c=Cv(a);dne(o,a,n);let d=Cv(a),f=d.length>0?d:n.map(()=>"");U$(o,s,f,c,l)}return wv(i,M$(a))||fne(o,a,i),e.chartType&&e.chartType!==Dp(s)&&V$(s,e.chartType),e.presentation&&!wv(e.presentation,$$(s))&&G$(s,e.presentation),{datadescription:(0,ai.serializeNode)(a),presentationdescription:(0,ai.serializeNode)(s)}}function P$(e){return!!e&&(e.c.length>0||e.a.length>0)}function U$(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 Cv(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 R$(e,t,r){let n={n:t,a:(0,bv.mergeAttrs)(e.a,[]),c:(0,bv.spliceChildren)(e.c,[])};return(0,bv.rebuildRaw)(n,(0,ai.domEngine)(r),null)}function dne(e,t,r){let n=Ip(t),i=n?.getElementsByTagName("entity")[0];!n||!i||B$(e,t,i,vne(n),r,Cne,{aliasPrefix:"aggregate_column",addRef:hne,removeRef:bne})}function fne(e,t,r){let n=Ip(t),i=n?.getElementsByTagName("entity")[0];!n||!i||B$(e,t,i,wne(n),r,Ene,{aliasPrefix:"groupby_column",addRef:gne,removeRef:yne})}function B$(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=Ane(r,m),b=p.relatedEntity;(g??void 0)!==(b??void 0)&&((h=m.parentNode)===null||h===void 0||h.removeChild(m),k$(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||mne(t,a.aliasPrefix);p.setAttribute("alias",h),o(p,m),k$(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),Nne(m)}}function pne(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 mne(e,t){let r=pne(e);if(!r.has(t))return t;for(let n=2;;n+=1){let i=`${t}_${n}`;if(!r.has(i))return i}}function q$(e,t){let r=t.getElementsByTagName("categorycollection")[0];if(r)return r;let n=e.createElement("categorycollection");return t.appendChild(n),n}function hne(e,t,r){let n=q$(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 gne(e,t,r){let n=q$(e,t),i=e.createElement("category");i.setAttribute("alias",r),n.appendChild(i)}function yne(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 bne(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"&&!Tne(a)&&((r=a.parentNode)===null||r===void 0||r.removeChild(a))}}function vne(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 wne(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 Cne(e,t){e.setAttribute("name",t.attribute),e.setAttribute("aggregate",t.aggregate),t.seriesType&&e.setAttribute("charttype",t.seriesType)}function Ene(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 Ane(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 k$(e,t,r,n){n?Sne(e,t,n).appendChild(r):t.appendChild(r)}function Sne(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 Nne(e){let t=e.parentNode;if(t&&(t.removeChild(e),t.tagName==="link-entity"&&!_ne(t))){let r=t.parentNode;r&&r.removeChild(t)}}function _ne(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 Tne(e){let t=e.childNodes;for(let r=0;r<t.length;r+=1)if(t[r].nodeType===1)return!0;return!1}function V$(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(!Dne(r[i])){r[i].setAttribute("ChartType",t);return}}}function Dne(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 G$(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 Ine(e,t){let r=(0,ai.parseXmlRoot)(sne(),"<Chart/>"),n=e.chartType||Dp(r);V$(r,n),e.presentation&&G$(r,e.presentation);let i=Cv((0,ai.parseXmlRoot)(t,"<datadefinition/>"));return i.length>0&&U$(r.ownerDocument,r,i,i.slice(0,1),n),(0,ai.serializeNode)(r)}function wv(e,t){return JSON.stringify(e)===JSON.stringify(t)}function al(e){return String(e??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function One(){return{adapter:new Tp,api:nne.chartApi,publish:(e,t,r)=>(0,I$.publishBoundEntity)(e,r),publishScope:(e,t)=>(0,I$.boundEntityPublishScope)(t),rebaselineAfterPublish:"bracket"}}sl.chartRegistration=One});var K$=v(Na=>{"use strict";Object.defineProperty(Na,"__esModule",{value:!0});Na.dashboardApi=Na.dashboardEntity=void 0;var Pne=Lt(),Oo=ye(),ll=le(),Rne=Cg(),z$=ru();function j$(e){return e&&e.toLowerCase()!=="none"?e:void 0}Na.dashboardEntity=j$;var H$="formid,name,description,formxml,type,objecttypecode,istabletenabled,iscustomizable,componentstate,versionnumber",kne={select:H$,required:["name","type","objecttypecode","istabletenabled"]},Lne="formid,name,type,objecttypecode",$ne=0,xne=10;Na.dashboardApi={async get(e,t){let r=(0,ll.normalizeGuid)(t,"id"),n=`/systemforms(${r})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,ll.odataQuery)([["$select",H$]]),i=(0,Oo.ensureSuccess)(await e.get(n),e.apiUrl(n));return(0,z$.assertSystemFormRecordKind)(i.body,r,"dashboard","fetch"),{raw:i.body,etag:(0,Oo.readEtag)(i)}},async list(e,t){let r=[`(type eq ${$ne} or type eq ${xne})`];t?.entityLogicalName&&r.push(`objecttypecode eq '${(0,ll.odataLiteral)(t.entityLogicalName)}'`);let n=`/systemforms${(0,ll.odataQuery)([["$select",Lne],["$filter",r.join(" and ")]])}`;return(await(0,Pne.collectPages)(e,n,"listArtifacts('dashboard')")).map(o=>{var a,s;let l=j$(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,Oo.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,Oo.ensureSuccess)(await e.post(o,(0,Oo.withClientMintedId)(a,"formid",r),i.options),e.apiUrl(o));return{id:(0,Oo.resolveCreatedId)(s,"formid","dashboard",r),etag:(0,Oo.readEtag)(s)}},async update(e,t,r,n){let i=r;return(0,Rne.patchSystemForm)(e,(0,ll.normalizeGuid)(t,"id"),"dashboard",{name:i.name,description:i.description,formxml:i.formxml,istabletenabled:i.istabletenabled},n,kne)},readContentThenToken(e,t){return Na.dashboardApi.get(e,t)},async delete(e,t){let r=(0,ll.normalizeGuid)(t,"id");return await(0,z$.assertSystemFormKind)(e,r,"dashboard"),(0,Oo.deleteRecord)(e,"systemforms",r)}}});var sx=v(si=>{"use strict";Object.defineProperty(si,"__esModule",{value:!0});si.dashboardRegistration=si.TILE_CLASS_ID=si.DashboardAdapter=void 0;var lc=so(),hn=uo(),Ev=Qr(),sc=rn(),ex=K$(),Av=lo(),_a=pt(),tx=le(),rx=Jo(),Fne=$y(),J$="0",Sv="10",Mne=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"]]),Une="{3FF9A528-DD50-4ACA-8F10-2E5ED73513AD}",Pp=class{constructor(t=rx.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,hn.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:Bne(t.type),entityLogicalName:(a=(0,ex.dashboardEntity)(t.objecttypecode))!==null&&a!==void 0?a:null,enabledForMobile:!!t.istabletenabled,layoutType:qne(l),components:Y$(l,this.lcid),bag:(0,hn.projectElementBag)(l)}}fromArtifact(t){var r;return(0,Av.installDomShim)(),{formid:t.id,name:t.name,description:t.description,type:t.dashboardType==="Interactive"?Sv:J$,objecttypecode:(r=t.entityLogicalName)!==null&&r!==void 0?r:"",istabletenabled:t.enabledForMobile,formxml:Q$(t,this.lcid)}}fromApiResponse(t){return this.toArtifact(t??{})}completeAsStored(t,r){return(0,Fne.completeRecordAsStored)(t,r,this.lcid)}toApiPayload(t){return{name:t.name,description:t.description,formxml:Q$(t,this.lcid),istabletenabled:t.enabledForMobile,type:t.dashboardType==="Interactive"?Sv:J$,objecttypecode:t.entityLogicalName}}createDefault(t){var r,n,i,o,a,s,l,u;(0,Av.installDomShim)();let c=(0,hn.parseXmlRoot)(eie(),"<form/>");return{id:(r=t.id)!==null&&r!==void 0?r:(0,_a.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:Y$(c,this.lcid),bag:(0,hn.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,_a.newId)())}return t}validate(t){let r=[],n=(0,sc.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,sc.isJsonObject)(u)&&r.push((0,sc.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,sc.isJsonObject)(o.position)){let l=uc(o.position);i.has(l)?r.push((0,sc.issue)(`${s}/position`,"component-position-collision",`two components occupy the same dashboard position (${l}); move one to a free cell`)):i.add(l)}}),r}};si.DashboardAdapter=Pp;function Bne(e){return String(e??"")===Sv?"Interactive":"Standard"}function qne(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 Y$(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)=>{Vne(c,{tabIndex:o,columnIndex:l,sectionIndex:d},r,t)})})}),r}function Vne(e,t,r,n){ae(e,"rows").flatMap(o=>ae(o,"row")).forEach((o,a)=>{ae(o,"cell").forEach((s,l)=>{let u=Gne(s,{...t,rowIndex:a,cellIndex:l},n);u&&r.push(u)})})}function Gne(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=jne(a),u=Hne(s,l,a),c=Wne(a);return{id:a.getAttribute("id")||o,type:u,name:ix(e,r),classId:s,position:t,colspan:Rp(e,"colspan",1),rowspan:Rp(e,"rowspan",1),parameters:l,bag:(0,hn.projectElementBag)(e),...c?{icProperties:c}:{}}}function nx(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 Wne(e){let t=nx(e);return t?(0,hn.serializeNode)(t):void 0}function zne(e,t,r){let n=nx(t);if(!r){n&&t.removeChild(n);return}let i=new DOMParser().parseFromString(r,"text/xml").documentElement,o=(0,lc.rebuildRaw)((0,lc.rawFromNode)((0,hn.nodeLikeFromDom)(i)),(0,hn.domEngine)(e),null);n&&(0,hn.serializeNode)(n)===(0,hn.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 jne(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 Hne(e,t,r){var n;let i=Mne.get(e.toUpperCase());return i?i==="chart"?t.ChartGridMode==="Chart"?"chart":"list":i==="assistant"?((n=r.getAttribute("uniqueid"))!==null&&n!==void 0?n:"").toUpperCase()===Une?"assistant":t.ChartGridMode!==void 0||r.getAttribute("indicationOfSubgrid")==="true"?t.ChartGridMode==="Chart"?"chart":"list":"unknown":i:"unknown"}function Rp(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 Kne(e,t){let r={n:"form",a:(0,lc.mergeAttrs)(e.bag.a,[]),c:(0,lc.spliceChildren)(e.bag.c,[])};return(0,lc.rebuildRaw)(r,(0,hn.domEngine)(t),null)}function Q$(e,t){let r=new DOMParser().parseFromString("<root/>","text/xml"),n=Kne(e,r);return Qne(r,n,e.components,t),Jne(r,n,e.components,t),(0,hn.serializeNode)(n)}function Jne(e,t,r,n){let i=ax(t);for(let o of r)i.has(uc(o.position))||Yne(e,t,o,n)}function Yne(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=tie(t,e,l);for(let x of ae(u,"row"))ae(x,"cell").some(K=>ae(K,"control").length>0)||u.removeChild(x);let c=r.classId||si.TILE_CLASS_ID[r.type]||si.TILE_CLASS_ID.iframe,d=r.rowspan&&r.rowspan>0?r.rowspan:4,f=r.bag&&X$(r.bag,"id")?String(X$(r.bag,"id")):Op((0,_a.newId)()),m=r.id?Op(r.id):Op((0,_a.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=ae(u,"row"),w=b[b.length-1],C=w?ae(w,"cell").reduce((x,K)=>x+Rp(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"),k=e.createElement("label");k.setAttribute("description",(a=r.name)!==null&&a!==void 0?a:""),k.setAttribute("languagecode",String(n)),O.appendChild(k),S.appendChild(O);let I=e.createElement("control");I.setAttribute("id",m),I.setAttribute("classid",Op(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,tx.createSafeXmlElement)(e,x,"dashboard tile parameter");K.textContent=P[x],D.appendChild(K)}I.appendChild(D),S.appendChild(I),w.appendChild(S)}function X$(e,t){if(!e)return;let r=e.a.find(n=>n[0]===t);return r?r[1]:void 0}function Qne(e,t,r,n){var i;let o=ax(t),a=new Set(r.map(s=>uc(s.position)));for(let s of r){let l=o.get(uc(s.position));if(!l)continue;let u=ae(l,"control")[0];u&&(Xne(e,l,s.name,n),Zne(e,u,s.parameters),Z$(l,"colspan",s.colspan),Z$(l,"rowspan",s.rowspan),s.icProperties!==void 0&&zne(e,u,s.icProperties))}for(let[s,l]of o)a.has(s)||(i=l.parentNode)===null||i===void 0||i.removeChild(l)}function ax(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,m)=>{ae(f,"cell").forEach((p,h)=>{var g;ox((g=p.getAttribute("id"))!==null&&g!==void 0?g:"").toLowerCase().startsWith("spacer")||ae(p,"control")[0]&&t.set(uc({tabIndex:i,columnIndex:s,sectionIndex:c,rowIndex:m,cellIndex:h}),p)})})})})}),t}function uc(e){let t=e??{};return`${t.tabIndex}.${t.columnIndex}.${t.sectionIndex}.${t.rowIndex}.${t.cellIndex}`}function Xne(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 Zne(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,tx.createSafeXmlElement)(e,l,"dashboard component parameter");d.textContent=u,o.appendChild(d)}}}function Z$(e,t,r){Rp(e,t,1)!==r&&e.setAttribute(t,String(r))}function eie(e=2){let t=`{${(0,_a.newId)()}}`,r=`{${(0,_a.newId)()}}`,n=`{${(0,_a.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>`}si.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 Op(e){return`{${e.replace(/[{}]/g,"")}}`}function tie(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 rie(e=rx.DEFAULT_LCID){return{adapter:new Pp(e),api:ex.dashboardApi,languageSensitive:!0,publish:(t,r,n)=>n?.entityLogicalName?(0,Ev.publishBoundEntity)(t,n):(0,Ev.publishDashboardById)(t,r),publishScope:(t,r)=>r?.entityLogicalName?(0,Ev.boundEntityPublishScope)(r):{envelope:"dashboard",targetIds:[t]},rebaselineAfterPublish:"bracket"}}si.dashboardRegistration=rie});var _v=v(Fr=>{"use strict";Object.defineProperty(Fr,"__esModule",{value:!0});Fr.readEveryInOrder=Fr.readInOrder=Fr.plainRead=Fr.resolveReadConcurrency=Fr.MAX_READ_CONCURRENCY=void 0;var lx=Q();Fr.MAX_READ_CONCURRENCY=8;function nie(e){if(e===void 0)return 1;if(typeof e!="number"||!Number.isInteger(e)||e<1||e>Fr.MAX_READ_CONCURRENCY)throw new lx.InvalidArgumentError(`readConcurrency must be a whole number from 1 to ${Fr.MAX_READ_CONCURRENCY} (got ${typeof e=="string"?`'${e}'`:String(e)})`);return e}Fr.resolveReadConcurrency=nie;var iie=e=>({ok:!0,value:e}),Nv=e=>({ok:!1,error:e});function oie(e){let t=(async()=>e())().then(iie,Nv);return{outcome:t,finish:async r=>{await r()},discard:async()=>{await t}}}Fr.plainRead=oie;async function ux(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 m=await r(e[f],f),p=m.outcome.catch(Nv);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:Nv(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 aie(e,t,r,n){return ux(e,t,r,(i,o,a)=>n(i.value,o,a),"stop")}Fr.readInOrder=aie;function sie(e,t,r,n){return ux(e,t,r,n,"continue")}Fr.readEveryInOrder=sie});var _x=v(Lp=>{"use strict";Object.defineProperty(Lp,"__esModule",{value:!0});Lp.genPageApi=void 0;var kp=Lt(),Cx=Kl(),Be=ye(),ve=le(),xn=xd(),Je=Q(),Ex=pt(),cx=_v();function lie(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 li="uxagentprojects",Da="uxagentprojectfiles",fc="agentconversationmessages",pc="uxagentprojectid",Bt="uxagentprojectfileid",Ia="agentconversationmessageid",cc=`${pc},name`,uie=`${Bt},filename,filetype`,Ax=2e8,Sx=200000001,Oa={"MSCRM.IncludeUnpublished":"true"},Tv={};function Ta(e,t){return{"MSCRM.VersioningChangeset":e,...Oa,...t}}async function Ov(e,t,r,n){var i;let o=`/${t}(${r})`+(0,ve.odataQuery)([["$select",n]]),a=(0,Be.ensureSuccess)(await e.get(o,{headers:{...Oa}}),e.apiUrl(o));return{row:(i=a.body)!==null&&i!==void 0?i:{},etag:(0,Be.readEtag)(a)}}async function mc(e,t,r=Oa){let n=`/${Da}(${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=lie(o);if(a)return{status:"available",data:(0,xn.bytesToBase64)(a)};if(typeof o=="string")return{status:"available",data:(0,xn.utf8ToBase64)(o)};throw new Je.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 Nx(e){let t=e.lastIndexOf("/");return t>=0?e.slice(t+1):e}async function cie(e,t,r,n,i,o){if(!e.supportsBinaryPatch)throw new Je.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=`/${Da}(${t})/filecontent`,s=(0,xn.base64ToBytes)(n);(0,ve.assertNoControlChars)(r,"generative-page file name"),(0,Be.ensureSuccess)(await e.patchRaw(a,s,{headers:Ta(i,{"Content-Type":"application/octet-stream","Content-Length":String(s.byteLength),"x-ms-file-name":Nx(r),...o?{"If-Match":"*"}:{}})}),e.apiUrl(a))}async function dc(e,t,r=Oa){let n=`/${Da}`+(0,ve.odataQuery)([["$select",uie],["$filter",`_${pc}_value eq ${t}`]]);return(await(0,kp.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 Dv(e,t){let r=`/${fc}`+(0,ve.odataQuery)([["$select",`${Ia},message,messagesender,createdon`],["$filter",`_regardingobjectid_value eq ${t}`],["$orderby","createdon asc,versionnumber asc"]]);return(0,kp.collectPages)(e,r,"fetchArtifact('genPage')",void 0,{headers:{...Oa}})}async function dx(e,t){var r,n,i;let{row:o,etag:a}=await Ov(e,li,t,cc),s=new Map;for(let{row:l,etag:u}of await dc(e,t))s.set((0,ve.normalizeGuid)(String((r=l[Bt])!==null&&r!==void 0?r:""),Bt),{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,ve.normalizeGuid)(c.id,"file id");u.add(d);let f=r?.rows.get(d);if(c.content.status==="retain"){if(!r)throw new Je.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 Je.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 Pv(e){let t=(0,xn.base64ToUtf8)(e);return(0,xn.utf8ToBase64)(t)===(0,xn.bytesToBase64)((0,xn.base64ToBytes)(e))?t:void 0}function die(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?{[Ia]:(0,ve.normalizeGuid)(t.id,"message id")}:{},"[email protected]":`/${li}(${e})`,message:t.message,messagecontext:JSON.stringify(f),messagesender:t.sender==="user"?Ax:Sx}}async function fie(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,ve.normalizeGuid)(f,"message id"));if(s.length===0)return r;let l=`/${fc}`+(0,ve.odataQuery)([["$select",`${Ia},message,messagesender,_regardingobjectid_value`],["$filter",s.map(f=>`${Ia} eq ${f}`).join(" or ")]]),u=await(0,kp.collectPages)(e,l,"pushArtifact('genPage')",void 0,{headers:{...Oa}});if(u.length===0)return r;let c=new Map(u.map(f=>{var m;return[String((m=f[Ia])!==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,ve.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"?Ax:Sx)&&String((a=m._regardingobjectid_value)!==null&&a!==void 0?a:"").toLowerCase()===t))throw new Je.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 Iv(e,t,r,n){switch(t.kind){case"createProject":return{method:"POST",path:`/${li}`,body:(0,Be.withClientMintedId)({name:t.name},pc,e),headers:Ta(n)};case"createRow":return{method:"POST",path:`/${Da}`,body:(0,Be.withClientMintedId)({filename:t.file.name,filetype:t.file.fileType,[`${pc}@odata.bind`]:`/${li}(${e})`},Bt,(0,ve.normalizeGuid)(t.file.id,"file id")),headers:Ta(n)};case"renameRow":return{method:"PATCH",path:`/${Da}(${(0,ve.normalizeGuid)(t.file.id,"file id")})`,body:{filename:t.file.name,filetype:t.file.fileType},headers:Ta(n,{"If-Match":"*"})};case"content":{let i=Pv(t.data);if(i===void 0)throw new Je.SdkError("GENPAGE_CONTENT_NOT_TEXT",`File '${t.file.name}' is not UTF-8 text and cannot ride in a change set.`);return(0,ve.assertNoControlChars)(t.file.name,"generative-page file name"),{method:"PATCH",path:`/${Da}(${(0,ve.normalizeGuid)(t.file.id,"file id")})/filecontent`,rawBody:i,contentType:"application/octet-stream; charset=utf-8",headers:Ta(n,{"x-ms-file-name":Nx(t.file.name),...t.existing?{"If-Match":"*"}:{}})}}case"deleteRow":return{method:"DELETE",path:`/${Da}(${t.fileId})`,headers:Ta(n,{"If-Match":"*"})};case"patchProject":return{method:"PATCH",path:`/${li}(${e})`,body:{name:t.name},headers:Ta(n,{"If-Match":"*"})};case"message":return{method:"POST",path:`/${fc}`,body:die(e,t.turn,r,n)};default:{let i=t;throw new Je.SdkError("GENPAGE_WRITE_UNKNOWN",`Unknown generative-page write: ${JSON.stringify(i)}`)}}}function px(e,t){return e.supportsAtomicBatch&&t.every(r=>r.kind!=="content"||Pv(r.data)!==void 0)}async function mx(e,t,r,n,i){await(0,Cx.postChangeSet)(e,r.map(o=>Iv(t,o,n,i)),`generative page '${t}' (${r.length} operation(s))`)}async function hx(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 cie(e,(0,ve.normalizeGuid)(s.file.id,"file id"),s.file.name,s.data,i,s.existing);continue}let l=Iv(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=>Iv(t,l,n,i));if(e.supportsAtomicBatch)await(0,Cx.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 gx(e,t,r,n,i,o,a){var s;let l=u=>({id:t,etag:null,memberEtags:{},warnings:[...a,u]});try{let u=await dx(e,t),c=new Map;for(let C of r)(C.kind==="createRow"||C.kind==="renameRow"||C.kind==="content")&&c.set((0,ve.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 mc(e,(0,ve.normalizeGuid)(C.file.id,"file id")),O=(0,xn.bytesToBase64)((0,xn.base64ToBytes)(C.data));(S.status!=="available"||S.data!==O)&&d.push(S.status==="available"?`file '${C.file.name}' holds ${(0,xn.base64ToBytes)(S.data).byteLength} byte(s) that differ from the ${(0,xn.base64ToBytes)(O).byteLength} written`:`file '${C.file.name}' holds no content`)}let f=new Set(r.filter(C=>C.kind==="content").map(C=>(0,ve.normalizeGuid)(C.file.id,"file id")));for(let[C,S]of c)!f.has(C)&&(await mc(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 dx(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.`):pie({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 yx(e,t,r,n=e.readConcurrency){var i;let o=(0,ve.normalizeGuid)(t,"id"),{row:a,etag:s}=await Ov(e,li,o,cc),l=await dc(e,o),u={},c=[];if(n>1)await(0,cx.readInOrder)(l,n,({row:f})=>{var m;let p=(0,ve.normalizeGuid)(String((m=f[Bt])!==null&&m!==void 0?m:""),Bt);return(0,cx.plainRead)(async()=>({fileId:p,content:await mc(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,ve.normalizeGuid)(String((i=f[Bt])!==null&&i!==void 0?i:""),Bt);u[p]=m;let h=await mc(e,p);c.push({...f,content:h})}return{raw:r?{project:a,files:c,conversation:await Dv(e,o)}:{project:a,files:c},etag:s,memberEtags:u}}Lp.genPageApi={get(e,t,r){return yx(e,t,!0,r?.fileConcurrency)},getForRebaseline(e,t){return yx(e,t,!1)},async getPublished(e,t){var r,n;let i=(0,ve.normalizeGuid)(t,"id"),o=`/${li}(${i})`+(0,ve.odataQuery)([["$select",cc]]),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 dc(e,i,Tv);for(let{row:g,etag:b}of c){let w=(0,ve.normalizeGuid)(String((n=g[Bt])!==null&&n!==void 0?n:""),Bt);l[w]=b,u.push({...g,content:await mc(e,w,Tv)})}let d=g=>g.map(({row:b,etag:w})=>`${String(b[Bt])}@${String(w)}`).sort().join("|"),f=()=>new Je.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,Be.ensureSuccess)(m,e.apiUrl(o));let p=await dc(e,i,Tv);if([(0,Be.readEtag)(a),(0,Be.readEtag)(m),...[...c,...p].map(g=>g.etag)].some(g=>!g))throw new Je.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)(m)!==(0,Be.readEtag)(a)||d(p)!==d(c))throw f();return{raw:{project:s,files:u,conversation:[]},etag:(0,Be.readEtag)(a),memberEtags:l}},async list(e,t){let r=`/${li}`+(0,ve.odataQuery)([["$select",cc]]);return(await(0,kp.collectPages)(e,r,"listArtifacts('genPage')",void 0,{headers:{...Oa}})).map(i=>{var o,a;return{type:"genPage",id:String((o=i[pc])!==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,ve.normalizeGuid)(r,"id"):(0,Ex.newId)(),a=fx(o,i,void 0);wx(e,a),vx(e,o,i);let s=bx(),l=[],u=!0;px(e,a)?await mx(e,o,a,i,s):{warnings:l,turnRecorded:u}=await hx(e,o,a,i,s);let c=new Set(((n=i.files)!==null&&n!==void 0?n:[]).map(f=>(0,ve.normalizeGuid)(f.id,"file id"))),d=await gx(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,ve.normalizeGuid)(t,"id");if(!Array.isArray(s.files))throw new Je.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 fie(e,l,s);vx(e,l,u);let c=await dc(e,l),{row:d,etag:f}=await Ov(e,li,l,cc);if(n&&f&&n!==f)throw new Je.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 Je.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 m=new Map(c.map(({row:I})=>{var D,P;return[(0,ve.normalizeGuid)(String((D=I[Bt])!==null&&D!==void 0?D:""),Bt),{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,ve.normalizeGuid)(I.id,"file id")));if(!i)throw new Je.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(!p.has(I)&&g.has(I))throw new Je.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 p)if(!g.has(I))throw new Je.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 P;return[(0,ve.normalizeGuid)(String((P=I[Bt])!==null&&P!==void 0?P:""),Bt),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 Je.SdkError(Be.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 Je.SdkError(Be.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=fx(l,u,{rows:m,name:String((a=d.name)!==null&&a!==void 0?a:"")});if(wx(e,w),w.length===0)return{id:l,etag:f,memberEtags:Object.fromEntries(c.map(({row:I,etag:D})=>{var P;return[(0,ve.normalizeGuid)(String((P=I[Bt])!==null&&P!==void 0?P:""),Bt),D]}))};let C=bx(),S=[],O=!0;px(e,w)?await mx(e,l,w,u,C):{warnings:S,turnRecorded:O}=await hx(e,l,w,u,C);let k=await gx(e,l,w,u,h,b,S);return O?k:{...k,intentPending:!0}},async delete(e,t){var r;let n=(0,ve.normalizeGuid)(t,"id"),i=await Dv(e,n);await(0,Be.deleteRecord)(e,li,n);let o=new Set(i.map(l=>{var u;return String((u=l[Ia])!==null&&u!==void 0?u:"")}).filter(l=>l!=="")),a=!1;try{for(let l of await Dv(e,n)){let u=String((r=l[Ia])!==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,fc,l)}catch(u){u instanceof Je.ConnectionError&&u.statusCode===404||s.push(l)}if(s.length>0||a)throw new Je.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 ${fc} rows regarding '${n}'.`)}};function bx(){return`uxagentproject_${(0,Ex.newId)()}`}function pie(e,t){var r;return t.length===0?e:{...e,warnings:[...(r=e.warnings)!==null&&r!==void 0?r:[],...t]}}function vx(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 Je.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 wx(e,t){let r=t.filter(i=>i.kind==="content");if(r.length>0&&!e.supportsBinaryPatch&&!e.supportsAtomicBatch)throw new Je.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=>Pv(i.data)===void 0)&&!e.supportsBinaryPatch)throw new Je.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 Gx=v(cl=>{"use strict";Object.defineProperty(cl,"__esModule",{value:!0});cl.genPageRegistration=cl.GenPageAdapter=void 0;var mie=_x(),hie=Qr(),Ie=rn(),Up=pt(),Bp=xd(),gie=le(),Pa=Q(),Fx=$g(),Rv=rh(),Po=2e8,Mx=200000001,Wi={source:{name:"src/pages/page.tsx",fileType:Po},output:{name:"src/pages/page.compiled",fileType:Mx},config:{name:"config.json",fileType:Po},prompt:{name:"firstPrompt.json",fileType:Po}},Ux=Object.keys(Wi),yie=["dataSources","model","connectorBindings","actionBindings"],bie=["userMessage","agentMessage"],Tx=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,vie={source:"6f1c2a4e9b3d47a1b85c0e2f7d914a63",output:"a8e53d17c2f64b09a1d7e4b8c3f2069d",config:"3b97f0c64e2a4d8f95b1c7a0e6d3f814",prompt:"d24e8b51f7a34c6e8b09d5f1a2c7e3b6"},wie="9c3e7a15d2b84f6e8a01c5d7b3f9e240";function Bx(e,t,r){let n=(0,gie.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 $p(e,t){return Bx(e,vie[t],"id")}function Cie(e,t){let r=Bx(e,wie,"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 Dx(e){return typeof e=="string"&&e.trim()!==""?e:(0,Up.newId)()}function Gi(e){return(0,Ie.isJsonObject)(e)?e:{}}function ul(e,t){return JSON.stringify(e??null)===JSON.stringify(t??null)}function xp(e){return JSON.parse(JSON.stringify(e))}function Eie(e){let t=Gi(e);return t.status==="available"&&typeof t.data=="string"?{status:"available",data:t.data}:{status:"unavailable",reason:t.reason==="unpublished"?"unpublished":"missing"}}function gc(e){if(!e||e.status!=="available")return;let t=(0,Bp.base64ToUtf8)(e.data);return(0,Bp.utf8ToBase64)(t)===e.data?t:void 0}function qx(e,t,r){var n,i,o,a;return e.source!==void 0&&t!==void 0&&t?.source===e.source&&ul((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,Fx.isLoadableGenPageOutput)(r)}function Aie(e,t){var r;try{return qx(e,t,gc((r=e.bag)===null||r===void 0?void 0:r.output))}catch{return!1}}function Fp(e){if(e!==void 0)try{let t=JSON.parse(e.replace(/^\uFEFF/,""));return(0,Ie.isJsonObject)(t)?t:void 0}catch{return}}function Ix(e,t){if(t===Po&&e.includes("page.tsx"))return"source";if(t===Mx&&e.includes(".compiled"))return"output";if(t===Po&&e===Wi.config.name)return"config";if(t===Po&&e===Wi.prompt.name)return"prompt"}function Ox(e){let t=e.toLowerCase();return Ux.some(r=>Wi[r].name.toLowerCase()===t)}function kv(e){return Object.fromEntries(e)}function Vx(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),kv(i)}function Px(e){var t,r,n;return Vx({dataSources:(t=e.dataSources)!==null&&t!==void 0?t:[],model:e.model,connectorBindings:e.connectorBindings,actionBindings:e.actionBindings},yie,(r=e.bag)===null||r===void 0?void 0:r.config,(n=e.bag)===null||n===void 0?void 0:n.configKeys)}function Rx(e){var t,r;return Vx({userMessage:e.firstPrompt,agentMessage:e.firstAgentMessage},bie,(t=e.bag)===null||t===void 0?void 0:t.prompt,(r=e.bag)===null||r===void 0?void 0:r.promptKeys)}function kx(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=kv(n)),!0}function Lx(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=kv(n)),!0}function yc(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 Sie=["dataSources","model","connectorBindings","actionBindings","firstPrompt","firstAgentMessage"];function $x(e){return yc(e)?[]:Sie.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 xx(){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 Mp(e){return{status:"available",data:(0,Bp.utf8ToBase64)(e)}}function hc(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 qp=class{toArtifact(t){return t}fromArtifact(t){return t}fromApiResponse(t){let r=t,n=Gi(r?.project),i=(Array.isArray(r?.files)?r.files:[]).map(g=>{var b,w,C;let S=Gi(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:Po),content:Eie(S.content)}}),o=Array.isArray(r?.conversation)?r.conversation.map(g=>{var b,w;let C=Gi(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=Ix(g.name,g.fileType);b?((s.has(b)||g.name!==Wi[b].name)&&(u=!1),s.set(b,g)):(Ox(g.name)&&(u=!1),l.push(g))}if(!u||s.size===0)return a(hc(n,i));let c=hc(n,l),d={rows:{}};for(let[g,b]of s)d.rows[g]=b.id;let f=s.get("source");if(f){let g=gc(f.content);if(g===void 0)return a(hc(n,i));c.source=g}let m=s.get("output");m&&(d.output=m.content);let p=s.get("config");if(p){let g=Fp(gc(p.content));if(!g||!kx(c,d,g))return a(hc(n,i))}let h=s.get("prompt");if(h){let g=Fp(gc(h.content));if(!g||!Lx(c,d,g))return a(hc(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&&!ul((i=t.conversation)!==null&&i!==void 0?i:[],(o=r.conversation)!==null&&o!==void 0?o:[]))throw new Pa.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=$x(t);if(b.length>0)throw new Pa.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(yc(S)){let I=(s=(a=S.bag)===null||a===void 0?void 0:a.rows)!==null&&s!==void 0?s:{},D=Xe=>{var Ne;return(Ne=I[Xe])!==null&&Ne!==void 0?Ne:$p(S.id,Xe)},P=(Xe,Ne,se)=>{w.push({id:D(Xe),name:Wi[Xe].name,fileType:Wi[Xe].fileType,content:Ne,unchanged:se})};if(S.source!==void 0){P("source",Mp(S.source),!C&&r?.source===S.source&&I.source!==void 0);let Xe=gc((l=S.bag)===null||l===void 0?void 0:l.output);qx(S,r,Xe)?P("output",{status:"retain"},!0):P("output",Mp(await this.compile(S,S.source,n)),!1)}else{if(I.source!==void 0)throw new Pa.ValidationError("genPage",S.id,[xx()]);if(I.output!==void 0){if(!C&&!ul((u=r?.dataSources)!==null&&u!==void 0?u:[],(c=S.dataSources)!==null&&c!==void 0?c:[]))throw new Pa.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=Px(S),K=!C&&r!==void 0&&ul(Px(r),x);(C||I.config!==void 0||!K)&&P("config",Mp(JSON.stringify(x)),K&&I.config!==void 0);let Oe=Rx(S),Vt=!C&&r!==void 0&&ul(Rx(r),Oe);(I.prompt!==void 0||Object.keys(Oe).length>0&&!Vt)&&P("prompt",Mp(JSON.stringify(Oe)),Vt&&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&&ul(D,I)})}let O=[];if(S.newTurn){let I=S.newTurn.id,D=P=>I?{id:Cie(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 k=(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(k.enabledTools)?k.enabledTools:[],configurableTools:Array.isArray(k.configurableTools)?k.configurableTools:[]}}:{}}}committed(t,r,n={intentPending:!1}){let i=this.serverState(t,r);return n.intentPending&&t.newTurn!==void 0?{artifact:{...i,newTurn:xp(t.newTurn)},baseline:i}:{artifact:i,baseline:i}}serverState(t,r){var n,i,o,a,s,l;if(!yc(t)&&!t.newTurn)return t;let u=xp(t);if(delete u.newTurn,!yc(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=Ux.find(p=>Wi[p].name===d.name&&Wi[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,Bp.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,kx(u,c,(s=Fp(m))!==null&&s!==void 0?s:{})):f==="prompt"&&(delete c.prompt,delete u.firstPrompt,delete u.firstAgentMessage,Lx(u,c,(l=Fp(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"&&Tx.test(r.id)?t:{...t,newTurn:{...r,id:(0,Up.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 Pa.ValidationError("genPage",t.id,s);if(!n?.loadTypeScript)throw new Pa.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,Rv.buildGenPageRuntimeTypes)(a):void 0,c=a.length>0?(0,Rv.buildGenPageLegacyEnums)(a):void 0,d=(0,Fx.compileGenPage)(l,r,u,c);if(d.diagnostics.length>0)throw new Pa.ValidationError("genPage",t.id,d.diagnostics.map(Nie));return d.code}metadataNeeds(t,r){if(t.source===void 0||!Array.isArray(t.dataSources))return[];let n=Aie(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=Dx(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:Dx(a.id),name:(s=a.name)!==null&&s!==void 0?s:"index.tsx",fileType:(l=a.fileType)!==null&&l!==void 0?l:Po,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=xp(t.connectorBindings)),t.actionBindings!==void 0&&(o.actionBindings=xp(t.actionBindings)),o.source!==void 0&&(o.bag={rows:{source:$p(i,"source"),output:$p(i,"output"),config:$p(i,"config")}}),o}assignMissingIds(t){if(t==null)return{id:(0,Up.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,Up.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&&Gi(Gi(n.bag).rows).source!==void 0&&r.push(xx()),r.push(...$x(t)),n.newTurn!==void 0){let s=Gi(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"||!Tx.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"||!Rv.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=yc(t),a=new Map;return(Array.isArray(i)?i:[]).forEach((s,l)=>{let u=`/files/${l}`,c=Gi(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&&(Ox(f)||Ix(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=Gi(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}};cl.GenPageAdapter=qp;function Nie(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 _ie(){return{adapter:new qp,api:mie.genPageApi,publish:(e,t)=>(0,hie.publishGenPageById)(e,t),publishScope:e=>({envelope:"uxagentproject",targetIds:[e]}),rebaselineAfterPublish:"snapshot"}}cl.genPageRegistration=_ie});var zx=v(Gp=>{"use strict";Object.defineProperty(Gp,"__esModule",{value:!0});Gp.reconcileBpfSecurityRoles=void 0;var Wx=Lt(),$v=Q(),Vp=ye(),bc=le(),Tie="Global",Lv={create:"Create",read:"Read",write:"Write",delete:"Delete"};async function Die(e,t){var r;let n=`/EntityDefinitions(LogicalName='${(0,bc.odataPathLiteral)(t)}')?$select=LogicalName,Privileges`,i=(0,Vp.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 $v.ConnectionError(e.apiUrl(n),i.status,`reading the privileges of business process flow table '${t}' returned no 'Privileges' array (got ${(0,Wx.describeMalformedValue)(o)}), so which access it can grant is unknown.`);let a=o,s={},l=new Set;return Object.keys(Lv).forEach(u=>{let c=a.find(d=>d.PrivilegeType===Lv[u]);if(c){let d=(0,bc.normalizeGuid)(c.PrivilegeId,"PrivilegeId");s[u]=d,l.add(d)}}),{byAccess:s,all:l}}async function Iie(e,t){var r;let n=`/RetrieveRolePrivilegesRole(RoleId=${t})`,i=(0,Vp.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 $v.ConnectionError(e.apiUrl(n),i.status,`reading the privileges of role '${t}' returned no 'RolePrivileges' array (got ${(0,Wx.describeMalformedValue)(o)}), so what it holds is unknown.`);return new Set(o.map(a=>(0,bc.normalizeGuid)(a.PrivilegeId,"PrivilegeId")))}async function Oie(e,t,r){if(r.length===0)return;let n={Privileges:r.map(o=>({Depth:Tie,PrivilegeId:o}))},i=`/roles(${t})/Microsoft.Dynamics.CRM.AddPrivilegesRole`;(0,Vp.ensureSuccess)(await e.post(i,n),e.apiUrl(i))}async function Pie(e,t,r){let n={Privilege:{"@odata.type":"Microsoft.Dynamics.CRM.privilege",privilegeid:r}},i=`/roles(${t})/Microsoft.Dynamics.CRM.RemovePrivilegeRole`;(0,Vp.ensureSuccess)(await e.post(i,n),e.apiUrl(i))}async function Rie(e,t,r){var n,i,o;if(!r||r.length===0)return;let a=await Die(e,t.toLowerCase());for(let s of r){let l=(0,bc.normalizeGuid)(s.roleId,"roleId"),u=((n=s.access)!==null&&n!==void 0?n:[]).find(c=>!a.byAccess[c]);if(u!==void 0)throw new $v.InvalidArgumentError(`Cannot grant '${u}' access to role '${l}' on business process flow table '${t.toLowerCase()}': its metadata lists no '${(i=Lv[u])!==null&&i!==void 0?i:u}' privilege. No security role was changed.`)}for(let s of r){let l=(0,bc.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 Iie(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 Oie(e,l,f);for(let p of m)await Pie(e,l,p)}}Gp.reconcileBpfSecurityRoles=Rie});var iF=v(jp=>{"use strict";Object.defineProperty(jp,"__esModule",{value:!0});jp.bpfApi=void 0;var mr=Qi(),jx=Kl(),kie=Lt(),Qe=Q(),Ye=ye(),gn=le(),Lie=zx(),$ie=Lm(),vc=xm(),xie={"Content-Type":"application/json",Accept:"application/json"},xv={...xie,Prefer:"return=representation"},Fie=`category eq ${mr.WorkflowCategory.BusinessProcessFlow} and type eq ${mr.WorkflowTypeCode.Definition} and businessprocesstype eq ${mr.BusinessProcessType.BusinessFlow}`,Mie="workflowid,name,description,primaryentity,statecode,category,type,businessprocesstype,processorder",Uie="workflowid,name,uniquename,description,primaryentity,statecode,statuscode,category,type,businessprocesstype,processorder,xaml,clientdata",Bie=["xaml","name","description","processorder"];async function Wp(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,Lie.reconcileBpfSecurityRoles)(e,n,t.securityRoles)}async function Mv(e,t,r){let n={statecode:mr.StateCode.Activated,statuscode:mr.StatusCode.Activated},i=`/workflows(${t})`,{response:o,resent:a}=await nF(e,i,n,r,null);try{return(0,Ye.ensureSuccess)(o,e.apiUrl(i))}catch(s){throw a?tF(s):s}}var eF=new WeakSet;function tF(e){return typeof e=="object"&&e!==null&&eF.add(e),e}function rF(e){return typeof e=="object"&&e!==null&&eF.has(e)}function Hx(e){return e instanceof Qe.ConnectionError&&(e.statusCode===0||Ye.AMBIGUOUS_WRITE_STATUSES.has(e.statusCode))}async function nF(e,t,r,n,i){let o=n??i,a=0;try{return{response:await(0,Ye.resendWhile)(Ye.isConcurrencyLockRefusal,()=>{a+=1;let l=a===1?n:o,u={...xv};return l&&(u["If-Match"]=l),e.patch(t,r,{headers:u})},o?Ye.LOCK_BACKOFF_MS:[]),resent:a>1}}catch(s){throw a>1?tF(s):s}}async function Kx(e,t,r){return(0,Ye.readEtag)(await Mv(e,t,r))}function Jx(e,t){return new Qe.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. `+zp(e))}async function wc(e,t){var r;let n=`/workflows(${t})${(0,gn.odataQuery)([["$select","statecode"]])}`,i=(0,Ye.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 Qe.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 Fv(e,t,r,n,i=null){if((n??await wc(e,t))!==mr.StateCode.Activated)return{deactivated:!1,etag:null};let o={statecode:mr.StateCode.Draft,statuscode:mr.StatusCode.Draft},a=`/workflows(${t})`,s,l;try{({response:s,resent:l}=await nF(e,a,o,r,i))}catch(c){return await Yx(e,t,c,rF(c))}if(Ye.AMBIGUOUS_WRITE_STATUSES.has(s.status))return await Yx(e,t,new Qe.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,Ye.ensureSuccess)(s,e.apiUrl(a));return{deactivated:!0,etag:(0,Ye.readEtag)(u)}}async function Yx(e,t,r,n){let i;try{i=await wc(e,t)}catch{i=void 0}if(i===mr.StateCode.Draft&&!n)return{deactivated:!0,etag:null,uncertainCause:r};if(i===mr.StateCode.Activated)throw r;let o=new Qe.SdkError("BPF_DEACTIVATE_OUTCOME_UNKNOWN",i===mr.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,Qe.attachCause)(o,r),o}async function qie(e,t){let r=(0,gn.normalizeGuid)(t,"workflowid");try{return await Mv(e,r,null),"restored"}catch{return Uv(e,r)}}async function Vie(e,t,r){let n=(0,gn.normalizeGuid)(t,"workflowid");try{let i=await Mv(e,n,r);return{outcome:"restored",acknowledged:!0,echo:(0,Ye.readEtag)(i)}}catch(i){return i instanceof Qe.SdkError&&i.code===Ye.VERSION_CONFLICT_CODE?{outcome:"changed",acknowledged:!1,echo:null}:{outcome:await Uv(e,n),acknowledged:!1,echo:null}}}async function Uv(e,t){try{let r=await wc(e,t);return r===mr.StateCode.Activated?"restored":r===mr.StateCode.Draft?"disabled":"unknown"}catch{return"unknown"}}async function Qx(e,t,r,n){return r?{...await Vie(e,t,r),attempted:!0}:n?{outcome:await Uv(e,(0,gn.normalizeGuid)(t,"workflowid")),attempted:!1,acknowledged:!1,echo:null}:{outcome:await qie(e,t),attempted:!0,acknowledged:!1,echo:null}}function Gie(e,t){let r=new Qe.SdkError(vc.WORKFLOW_DELETE_UNSETTLED_CODE,`Deleting business process flow '${e}' failed${(0,vc.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,Qe.attachCause)(r,t),r}function Xx(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 Qe.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 Qe.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 Qe.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,Qe.attachCause)(s,n),s}async function Wie(e,t){try{return await wc(e,t),"survived"}catch(r){return r instanceof Qe.ConnectionError&&r.statusCode===404?"removed":"unknown"}}async function zie(e,t,r){if(r)try{let{deactivated:n,etag:i}=await Fv(e,t,r),o=n?i:r;if(o)return await(0,vc.deleteWorkflowResending)(e,t,{bindingToken:o,kindName:"business process flow",resendDeadlockVictim:!0,ifMatchOnFirst:!0}),"removed"}catch{}return Wie(e,t)}function zp(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 Zx(e,t){return new Qe.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. ${zp(e)}`)}function jie(e,t){let r=new Qe.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.) ${zp(e)} Or delete it. Original failure: ${t instanceof Error?t.message:String(t)}`);return(0,Qe.attachCause)(r,t),r}function Hie(e,t){let r=new Qe.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. ${zp(e)} Or delete it. Original failure: ${t instanceof Error?t.message:String(t)}`);return(0,Qe.attachCause)(r,t),r}function Kie(e,t){let r=new Qe.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,Qe.attachCause)(r,t),r}function Bv(e){let t={};for(let r of Bie)e[r]!==void 0&&(t[r]=e[r]);return t}var Jie=["name,processorder","description,name,processorder"];function Yie(e){let{xaml:t,...r}=Bv(e);return typeof t=="string"&&Jie.includes(Object.keys(r).sort().join(","))}async function Qie(e,t,r,n){let{xaml:i,...o}=Bv(r),[,a]=await(0,jx.sendChangeSet)(e,[{method:"PATCH",path:`/workflows(${t})`,body:o,etag:n},{method:"PATCH",path:`/workflows(${t})${(0,gn.odataQuery)([["$select","workflowid"]])}`,body:{xaml:i},headers:{Prefer:"return=representation"}}],`business process flow '${t}'`,{resendWhileLockRefused:!0});return(0,Ye.readEtag)((0,jx.partResponse)(a))}jp.bpfApi={async get(e,t){let n=`/workflows(${(0,gn.normalizeGuid)(t,"id")})${(0,gn.odataQuery)([["$select",Uie]])}`,i=(0,Ye.ensureSuccess)(await e.get(n),e.apiUrl(n));return{raw:i.body,etag:(0,Ye.readEtag)(i)}},async list(e,t){let r=[Fie];t?.entityLogicalName&&r.push(`primaryentity eq '${(0,gn.odataLiteral)(t.entityLogicalName)}'`);let n=`/workflows${(0,gn.odataQuery)([["$select",Mie],["$filter",r.join(" and ")]])}`;return(await(0,kie.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,gn.normalizeGuid)(r.record.workflowid,"workflowid"),i="/workflows",o=(0,Ye.ensureSuccess)(await e.post(i,r.record,{headers:xv}),e.apiUrl(i)),a=(0,Ye.readEtag)(o);if(!a)throw Zx(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 Kx(e,n,a)),await Wp(e,r)}catch(l){let u=await zie(e,n,s);throw u==="survived"?jie(n,l):u==="unknown"?Hie(n,l):l instanceof Qe.SdkError&&l.code===Ye.VERSION_CONFLICT_CODE?Kie(n,l):l}if(!s)throw Zx(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,gn.normalizeGuid)(t,"id"),a=(0,Ye.requireEtag)(n,"bpf",o),s=await wc(e,o);if(s===mr.StateCode.Activated&&i.status==="Active"&&e.supportsAtomicBatch&&Yie(i.record)){let p=await Qie(e,o,i.record,a);return await Wp(e,i),{id:o,etag:p}}let{deactivated:l,etag:u,uncertainCause:c}=await Fv(e,o,a,s),d=u,f=!1,m=!1;try{if(c!==void 0)throw c;let p=a;if(l){if(!u)throw Jx(o,"deactivation");p=u}let h=`/workflows(${o})`,g;try{g=(0,Ye.ensureSuccess)(await e.patch(h,Bv(i.record),{headers:{...xv,"If-Match":p}}),e.apiUrl(h))}catch(w){throw Hx(w)&&(d=null),w}let b=(0,Ye.readEtag)(g);if(d=b,i.status==="Active"){if(!b)throw Jx(o,"definition write");try{b=await Kx(e,o,b)}catch(w){throw Hx(w)&&(d=null),m=(0,Ye.isConcurrencyLockRefusalError)(w),w}f=!0}return await Wp(e,i),{id:o,etag:b}}catch(p){if(l&&!f){let{outcome:h,attempted:g,acknowledged:b,echo:w}=await Qx(e,o,d,rF(p));if(m&&b)return f=!0,await Wp(e,i),{id:o,etag:w};if(h!=="restored")throw Xx(o,"to apply an edit, the edit failed",h,p,g)}throw p}},async delete(e,t){let r=(0,gn.normalizeGuid)(t,"id"),n=await(0,$ie.assertWorkflowKind)(e,r,mr.WorkflowCategory.BusinessProcessFlow),{deactivated:i,etag:o}=await Fv(e,r,null,void 0,n);try{await(0,vc.deleteWorkflowResending)(e,r,{bindingToken:i?o:n,kindName:"business process flow",deactivated:i,resendDeadlockVictim:!0})}catch(a){if(i&&!(0,vc.isWorkflowDeleteUnsettled)(a)){let{outcome:s,attempted:l}=await Qx(e,r,o,!1);if(s==="changed")throw Gie(r,a);if(s!=="restored")throw Xx(r,"so it could be deleted, the delete failed",s,a,l)}throw a}}}});var qF=v(fl=>{"use strict";Object.defineProperty(fl,"__esModule",{value:!0});fl.bpfRegistration=fl.BpfAdapter=void 0;var Hp=Qi(),Xie=iF(),qv=so(),Ra=uo(),yF=lo(),Hr=rn(),Mr=pt(),Fn=Q(),Zie=100,Vv='<?xml version="1.0" encoding="utf-16"?>',oF=1033,bF="mxswa:Workflow",eoe="mxswa:ActivityReference.Properties",toe="mcwo:StepLabel",roe="mcwb:Control",aF="mcwb:Control.ControlDisplayName",vF="mcwb:Control.DataFieldName",wF="DataFieldName",sF="ControlDisplayName",CF="Literal",Jp="x:Null",lF="x:String",Gv="x:Key",Wv="DisplayName",Qp="Activities",noe="StepLabels",EF="StageId",AF="StageCategory",SF="NextStageId",NF="ProcessStepId",Kp="IsProcessRequired",_F="EntityComposite",TF="StageComposite",DF="StepComposite";function Cc(e){return(0,Hr.isJsonObject)(e)?e:{}}function ci(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 ka(e,t){var r;return(r=ci(e).find(n=>n.tagName===t))!==null&&r!==void 0?r:null}function fi(e){return ka(e,eoe)}function hr(e,t){var r;return(r=ci(e).find(n=>n.getAttribute(Gv)===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 di(e){var t;return!e||!e.firstChild?"":(t=e.firstChild.nodeValue)!==null&&t!==void 0?t:""}function IF(e,t,r){e.firstChild?e.firstChild.nodeValue=r:e.appendChild(t.createTextNode(r))}function Ec(e){var t;let r=(t=e.getAttribute(Wv))!==null&&t!==void 0?t:"",n=r.indexOf(": ");return n>=0?r.slice(n+2):r}function OF(e,t){var r;let n=(r=e.getAttribute(Wv))!==null&&r!==void 0?r:"",i=n.indexOf(": ");e.setAttribute(Wv,i>=0?n.slice(0,i+2)+t:t)}function PF(e,t){let r=hr(e,noe),n=ka(r,toe);n&&n.setAttribute("Description",t)}function ioe(e){let t=hr(e,AF);if(!t||t.tagName===Jp)return;let r=di(t).trim();return r===""?void 0:Number(r)}function ooe(e){let t=hr(e,SF);if(!t||t.tagName===Jp)return;let r=di(t).trim();return r===""?void 0:r}function RF(e){let t=kF(e);if(!t)return;let r=$F(t,wF,vF);return r===""?void 0:r}function zv(e,t){let r=ci(e);for(;r.length>0;){let n=r.pop();if(n.tagName===t)return n;for(let i of ci(n))r.push(i)}return null}function kF(e){let t=hr(fi(e),Qp);return t?zv(t,roe):null}function LF(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 $F(e,t,r){var n;return LF(e,t)?(n=e.getAttribute(t))!==null&&n!==void 0?n:"":coe(e,r)}function uF(e,t,r,n){if(LF(e,t)){e.setAttribute(t,n);return}if(ka(e,r)){aoe(e,r,n);return}throw new Fn.InvalidArgumentError(`BPF step control exposes neither a '${t}' attribute nor a <${r}> wrapper to bind a column`)}function aoe(e,t,r){let n=ka(e,t),i=n?zv(n,CF):null;if(!i)throw new Fn.InvalidArgumentError(`BPF step control's <${t}> wrapper holds no <Literal> to bind a column`);i.setAttribute("Value",r)}function xF(e){return Ec(e)}function Xp(e){let t=ka(e,bF),r=[];for(let n of ci(t).filter(i=>dl(i,_F))){let i=hr(fi(n),Qp);for(let o of ci(i).filter(a=>dl(a,TF)))r.push({el:o,entity:xF(n)})}return r}function jv(e){let t=hr(fi(e),Qp);return ci(t).filter(r=>dl(r,DF))}function soe(e){let t=fi(e),r=di(hr(t,Kp)).trim().toLowerCase(),n=RF(e),i={id:di(hr(t,NF)),name:Ec(e)};return n!==void 0&&(i.fieldName=n),r==="true"&&(i.required=!0),i}function loe(e,t){let r=fi(e),n=ioe(r),i=ooe(r),o={id:di(hr(r,EF)),name:Ec(e),entityLogicalName:t,steps:jv(e).map(soe)};return n!==void 0&&(o.category=n),i!==void 0&&(o.nextStageId=i),o}function uoe(e){return Xp(e).map(({el:t,entity:r})=>loe(t,r))}function ui(e){return new Fn.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 coe(e,t){var r;let n=ka(e,t),i=n?zv(n,CF):null;return(r=i?.getAttribute("Value"))!==null&&r!==void 0?r:""}function Hv(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(Hv(e,s)):s.nodeType===3&&n.appendChild(e.createTextNode((r=s.nodeValue)!==null&&r!==void 0?r:""))}return n}function FF(e){return hr(fi(e),Qp)}function doe(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,Mr.newId)(),{body:a}=Zp(Kv(i,(0,Mr.newId)(),t.id,o));return Hv(e,Xp((0,Ra.parseXmlRoot)(a,"<Activity/>"))[0].el)}function foe(e,t){let{body:r}=Zp(Kv("account",(0,Mr.newId)(),(0,Mr.newId)(),t.id));return Hv(e,jv(Xp((0,Ra.parseXmlRoot)(r,"<Activity/>"))[0].el)[0])}function MF(e,t){for(;e.firstChild;)e.removeChild(e.firstChild);for(let r of t)e.appendChild(r)}function UF(e,t,r,n){let i=hr(e,r);if(!i||!i.parentNode){if(n!==void 0&&n!=="")throw ui(`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!==Jp&&di(i).trim()!==""){let s=t.createElement(Jp);s.setAttribute(Gv,r),o.replaceChild(s,i)}return}if(i.tagName===lF){di(i).trim()!==n&&IF(i,t,n);return}let a=t.createElement(lF);a.setAttribute(Gv,r),a.appendChild(t.createTextNode(n)),o.replaceChild(a,i)}function poe(e,t,r){UF(e,t,AF,r===void 0?void 0:String(r))}function moe(e,t,r){UF(e,t,SF,r)}function BF(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 cF(e){return di(hr(fi(e),EF))}function dF(e){return di(hr(fi(e),NF))}function fF(e,t,r){var n,i,o,a;let s=fi(e);r.name!==Ec(e)&&(OF(e,r.name),PF(s,r.name));let l=di(hr(s,Kp)).trim().toLowerCase()==="true";if(((n=r.required)!==null&&n!==void 0?n:!1)!==l){let u=hr(s,Kp);if(!u)throw ui(`setting '${Kp}' on a step whose xaml does not expose that slot`);IF(u,t,r.required?"True":"False")}if(((i=r.fieldName)!==null&&i!==void 0?i:"")!==((o=RF(e))!==null&&o!==void 0?o:"")){let u=kF(e);if(!u)throw new Fn.InvalidArgumentError("BPF step has no <mcwb:Control> element to bind a column to");let c=(a=r.fieldName)!==null&&a!==void 0?a:"";uF(u,wF,vF,c),c!==""&&$F(u,sF,aF)===""&&uF(u,sF,aF,c)}}function pF(e,t,r,n){var i;let o=fi(e);if(!o)throw new Fn.InvalidArgumentError("BPF stage composite has no <\u2026ActivityReference.Properties>");if(r.name!==Ec(e)&&(OF(e,r.name),PF(o,r.name)),poe(o,t,r.category),moe(o,t,n),r.relationshipName&&r.relationshipName.trim()!=="")throw ui("a stage relationship / table change (multi-table authoring)");if(r.actions&&r.actions.length>0||r.branch)throw ui("stage actions or conditional branching");let a=FF(e);if(!a)throw new Fn.InvalidArgumentError("BPF stage has no [Activities] collection");let s=(i=r.steps)!==null&&i!==void 0?i:[];if(s.length===0)throw new Fn.InvalidArgumentError(`BPF stage '${r.name}' must have at least one step`);let l=jv(e);if(BF(l,s.map(d=>d.id),dF)){l.forEach((d,f)=>fF(d,t,s[f]));return}let u=new Map(l.map(d=>[dF(d),d]));if(ci(a).some(d=>!dl(d,DF)))throw ui("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:foe(t,d)});MF(a,c),c.forEach((d,f)=>fF(d,t,s[f]))}function hoe(e,t,r){let n=ka(e,bF);if(!n)throw new Fn.InvalidArgumentError("BPF xaml has no <mxswa:Workflow> root activity");if(r.globalActions&&r.globalActions.length>0)throw ui("global (process-completed/abandoned) actions");if(!r.stages||r.stages.length===0)throw new Fn.InvalidArgumentError("a BPF must have at least one stage");let i=Xp(e),o=i.map(f=>f.el);if(BF(o,r.stages.map(f=>f.id),cF)){i.forEach(({el:f,entity:m},p)=>{let h=r.stages[p];if(h.entityLogicalName&&h.entityLogicalName.trim()!==""&&h.entityLogicalName!==m)throw ui(`changing a stage's table ('${h.entityLogicalName}' vs the process's '${m}')`);pF(f,t,h,h.nextStageId)});return}let a=ci(n).filter(f=>dl(f,_F));if(a.length!==1)throw ui("adding, removing or reordering stages on a multi-table process");let s=a[0],l=xF(s),u=FF(s);if(!u)throw new Fn.InvalidArgumentError("BPF primary entity composite has no [Activities] collection");if(ci(u).some(f=>!dl(f,TF)))throw ui("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 ui(`a stage on a different table ('${f.entityLogicalName}') than the process primary ('${l}')`);let c=new Map(o.map(f=>[cF(f),f])),d=r.stages.map(f=>{var m;return(m=c.get(f.id))!==null&&m!==void 0?m:doe(t,f,l)});MF(u,d),d.forEach((f,m)=>{let p=m<d.length-1?r.stages[m+1].id:void 0;pF(f,t,r.stages[m],p)})}function Zp(e){let t=e.match(/^<\?xml[^>]*\?>\s*/),r=t?t[0]:"";return{prolog:r,body:e.slice(r.length)}}function goe(e){var t,r,n,i,o,a;(0,yF.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,qv.mergeAttrs)(s.a,[]),c:(0,qv.spliceChildren)(s.c,[])};return{root:(0,qv.rebuildRaw)(m,(0,Ra.domEngine)(f),null),prolog:(n=(r=e.bag)===null||r===void 0?void 0:r.xamlProlog)!==null&&n!==void 0?n:Vv,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=Kv(e.entityLogicalName,(0,Mr.newId)(),l?.id&&l.id.trim()!==""?l.id:(0,Mr.newId)(),u?.id&&u.id.trim()!==""?u.id:(0,Mr.newId)()),{body:d}=Zp(c);return{root:(0,Ra.parseXmlRoot)(d,"<Activity/>"),prolog:Vv,eol:"lf"}}function yoe(e){let{root:t,prolog:r,eol:n}=goe(e);hoe(t,t.ownerDocument,e);let i=(0,Ra.serializeNode)(t);return n==="crlf"&&(i=i.replace(/\n/g,`\r-`)),r+i}function boe(e){return e.uniqueName&&e.uniqueName.trim()!==""?e.uniqueName:`new_${(e.name||"businessprocessflow").toLowerCase().replace(/[^a-z0-9]/g,"")||"businessprocessflow"}`}var Yp=class{toArtifact(t){return t}fromArtifact(t){return t}fromApiResponse(t){var r,n;(0,yF.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}=Zp(o),u=(0,Ra.parseXmlRoot)(l,"<Activity/>");a.stages=uoe(u),a.bag={xaml:(0,Ra.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,Mr.newId)(),name:t.name,uniquename:boe(t),primaryentity:t.entityLogicalName,xaml:yoe(t),category:Hp.WorkflowCategory.BusinessProcessFlow,type:Hp.WorkflowTypeCode.Definition,businessprocesstype:Hp.BusinessProcessType.BusinessFlow,scope:Hp.WorkflowScope.Organization,processorder:(r=t.order)!==null&&r!==void 0?r:Zie};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 Fn.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(hF):[hF({id:(0,Mr.newId)(),name:"New Stage",steps:[]})],a={id:t.id&&t.id.trim()!==""?t.id:(0,Mr.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=Cc(t);(typeof r.id!="string"||r.id.trim()==="")&&(r.id=(0,Mr.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,Hr.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,Hr.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=Cc(l),f=typeof d.id=="string"?d.id.trim():"";f===""?r.push((0,Hr.issue)(`${c}/id`,"stage-id-required","a stage needs an id")):a.has(f.toLowerCase())?r.push((0,Hr.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,Hr.issue)(`${c}/steps`,"stage-needs-step","a BPF stage must have at least one step")),m.length>30&&r.push((0,Hr.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 Cc(h).id=="string"?h.id.trim():"";w===""?r.push((0,Hr.issue)(`${b}/id`,"step-id-required","a step needs an id")):p.has(w.toLowerCase())?r.push((0,Hr.issue)(`${b}/id`,"step-id-duplicate",`two steps in this stage share the id '${h.id}'`)):p.set(w.toLowerCase(),g)}),d.branch&&!mF(i,d.branch.nextStageId)&&r.push((0,Hr.issue)(`${c}/branch/nextStageId`,"branch-target-unknown",`branch nextStageId '${d.branch.nextStageId}' does not match any stage id`)),typeof d.nextStageId=="string"&&d.nextStageId!==""&&!mF(i,d.nextStageId)&&r.push((0,Hr.issue)(`${c}/nextStageId`,"next-stage-unknown",`nextStageId '${d.nextStageId}' does not match any stage id`))}),o.size>5&&r.push((0,Hr.issue)("/stages","too-many-tables",`a BPF spans at most 5 tables, got ${o.size}`));let s=voe(i);return s>=0&&r.push((0,Hr.issue)(`/stages/${s}/nextStageId`,"next-stage-cycle","the stage nextStageId links form a cycle; the flow must be acyclic")),r}};fl.BpfAdapter=Yp;function voe(e){let t=new Map(e.map(r=>[Cc(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 mF(e,t){return e.some(r=>Cc(r).id===t)}function hF(e){var t,r;let n=e.steps&&e.steps.length>0?e.steps.map(gF):[gF({id:(0,Mr.newId)(),name:"New Step"})],i={id:e.id&&e.id.trim()!==""?e.id:(0,Mr.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 gF(e){var t;let r={id:e.id&&e.id.trim()!==""?e.id:(0,Mr.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 Kv(e,t,r,n){return`${Vv}<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="${oF}" /></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="${oF}" /></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 woe(){return{adapter:new Yp,api:Xie.bpfApi,languageSensitive:!0}}fl.bpfRegistration=woe});var VF=v(em=>{"use strict";Object.defineProperty(em,"__esModule",{value:!0});em.buildRegistrations=void 0;var Coe=Lk(),Eoe=eL(),Aoe=x1(),Soe=e$(),Noe=N$(),_oe=W$(),Toe=sx(),Doe=Gx(),Ioe=qF();function Ooe(e){let t=new Map;return t.set("form",(0,Coe.formRegistration)(e)),t.set("view",(0,Eoe.viewRegistration)()),t.set("businessRule",(0,Aoe.businessRuleRegistration)()),t.set("app",(0,Soe.appRegistration)(e)),t.set("command",(0,Noe.commandRegistration)()),t.set("chart",(0,_oe.chartRegistration)()),t.set("dashboard",(0,Toe.dashboardRegistration)(e)),t.set("genPage",(0,Doe.genPageRegistration)()),t.set("bpf",(0,Ioe.bpfRegistration)()),t}em.buildRegistrations=Ooe});var rM=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 zi=Lt(),yn=ye(),qe=le(),GF=pt(),Ve=Q();Te.AI_GATE={formFill:"FormFillBarUXEnabled",formFillSuggestions:"FormPredictEnabled",formFillSmartPaste:"FormPredictSmartPasteEnabled",formFillFiles:"FormFillFileUploadEnabled",nlSearch:"EnableNLGridSearch",nlChart:"NLChartVisualizationSetting",summaries:"EnableFormInsights",m365:"m365copilotmodelappenabled"};var JF={formFill:"FormFillBarUXEnabled",formFillSuggestions:"FormPredictEnabled",formFillSmartPaste:"FormPredictSmartPasteEnabledOnByDefault",formFillFiles:"FormFillFileUploadEnabled",nlSearch:"NLGridSearchSetting",nlChart:"NLChartDataVisualizationSetting",m365:"m365copilotmodelappenabled"},Poe=new Set(Object.entries(Te.AI_GATE).filter(([e,t])=>JF[e]===t).map(([e])=>e)),Roe={formFill:{enabled:"2",disabled:"1"},formFillSuggestions:{enabled:"2",disabled:"1"},formFillSmartPaste:{enabled:"2",disabled:"1"},formFillFiles:{enabled:"2",disabled:"1"}};function Jv(e){return Roe[e]}var tm=1e6;function koe(e,t){let r=Jv(t),n=()=>{throw new Ve.InvalidArgumentError(`setAppAiFeatures: '${t}' must be a boolean or an integer between 0 and ${tm} (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>tm?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(tm).length||Number(s)>tm?n():s}}return n()}function Loe(e,t){let r=Jv(t);return r?e===r.enabled:e!=="0"}async function $oe(e,t){var r,n;let i=`/appmodules${(0,qe.odataQuery)([["$select","appmoduleid"],["$filter",`uniquename eq '${(0,qe.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 Ve.ConnectionError(e.apiUrl(i),o.status,`the app lookup for '${t}' returned a malformed answer \u2014 expected an OData 'value' array but got ${(0,zi.describeMalformedValue)(a)}`);return(n=a[0])===null||n===void 0?void 0:n.appmoduleid}async function xoe(e,t){var r,n;let i=`/appmodules${(0,qe.odataQuery)([["$select","appmoduleid"],["$filter",`uniquename eq '${(0,qe.odataLiteral)(t)}'`]])}`,o;try{o=await e.get(i)}catch(l){throw new Ve.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 Ve.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 Ve.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 Ve.InvalidArgumentError(`setAppAiFeatures: cannot confirm that the supplied appModuleId belongs to app '${t}' \u2014 the lookup returned a row with no appmoduleid.`);return s}var WF=new WeakMap;async function Foe(e,t){var r,n;let i=WF.get(e);if(i||(i=new Map,WF.set(e,i)),i.has(t))return i.get(t);let o=`/settingdefinitions${(0,qe.odataQuery)([["$select","settingdefinitionid"],["$filter",`uniquename eq '${(0,qe.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 Ve.ConnectionError(e.apiUrl(o),a.status,`the setting definition lookup returned a malformed answer \u2014 expected an OData 'value' array but got ${(0,zi.describeMalformedValue)(s)}`);let l=(n=s[0])===null||n===void 0?void 0:n.settingdefinitionid;return l&&i.set(t,l),l}async function Moe(e,t,r){var n,i;let o=await Foe(e,r);if(!t||!o)return;let a=`/appsettings/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()${(0,qe.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 Ve.ConnectionError(e.apiUrl(a),s.status,`the app-scope override read returned a malformed answer \u2014 expected an OData 'value' array but got ${(0,zi.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 Uoe=4,Boe=500,zF=20,jF=3e4;function qoe(e){if(e===void 0)return Uoe;if(!Number.isFinite(e))throw new Ve.InvalidArgumentError(`setAppAiFeatures: verifyAttempts must be a finite integer between 1 and ${zF}; got ${e}.`);return Math.min(zF,Math.max(1,Math.floor(e)))}function Voe(e){if(e===void 0)return Boe;if(!Number.isFinite(e))throw new Ve.InvalidArgumentError(`setAppAiFeatures: verifyDelayMs must be a finite number between 0 and ${jF}; got ${e}.`);return Math.min(jF,Math.max(0,Math.floor(e)))}async function Goe(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 Moe(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 YF(e,t,r){if(t===2)return String(e).toLowerCase()==="true";let n=r?Jv(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,qe.odataPathLiteral)(t)}'`];r.appUniqueName&&i.push(`AppUniqueName='${(0,qe.odataPathLiteral)(r.appUniqueName)}'`);let o=`/RetrieveSetting(${i.join(",")})`,a=(0,yn.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 Ve.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 QF(e,t,r,n={}){let i={SettingName:t,Value:r};n.appUniqueName&&(i.AppUniqueName=n.appUniqueName),n.solutionUniqueName&&(i.SolutionUniqueName=n.solutionUniqueName),(0,yn.ensureSuccess)(await e.post("/SaveSettingValue",i),e.apiUrl("/SaveSettingValue"))}Te.saveSettingValue=QF;async function Woe(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:YF(o,a,n),setting:i,value:o}}return r}Te.getAiReadiness=Woe;async function zoe(e,t,r,n={}){var i;if(!t||!t.trim())throw new Ve.InvalidArgumentError("setAppAiFeatures: a non-empty appUniqueName is required (an empty value would write the setting at organization scope, affecting every app).");let o=qoe(n.verifyAttempts),a=Voe(n.verifyDelayMs),s=[];for(let[p,h]of Object.entries(r)){if(h===void 0)continue;let g=JF[p];g&&s.push({feature:p,setting:g,requestedValue:koe(h,p)})}let l=[],u=n.appModuleId?(0,qe.normalizeGuid)(n.appModuleId,"appModuleId"):void 0;if(u){let p=await xoe(e,t);if(p&&(0,qe.normalizeGuid)(p,"appModuleId")!==u)throw new Ve.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 $oe(e,t)),c),f=new Map,m=async p=>{if(Poe.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:YF(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 QF(e,h,g,{appUniqueName:t,solutionUniqueName:n.solutionUniqueName});let b=await Goe(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=Loe(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=zoe;var XF="GptPowerPrompt",joe='{ "consumptionSource": "Api", "partnerSource": "AIBuilder", "consumptionSourceVersion": "GptApiClient"}';function ZF(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=ZF;async function Hoe(e,t){var r;let n=`/EntityDefinitions(LogicalName='${(0,qe.odataPathLiteral)(t)}')${(0,qe.odataQuery)([["$select","MetadataId"]])}`,i=(0,yn.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 Ve.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,zi.describeMalformedValue)(o)}`);return o}function Yv(e,t,r,n){if(e.length===0)return;let i=e[0];if(typeof i!="object"||i===null||Array.isArray(i))throw new Ve.ConnectionError(t,r,`${n} returned a malformed row \u2014 expected an object but got ${Array.isArray(i)?"an array":(0,zi.describeMalformedValue)(i)}`);return i}async function eM(e){var t;let r=`/msdyn_aitemplates${(0,qe.odataQuery)([["$select","msdyn_aitemplateid"],["$filter",`msdyn_uniquename eq '${XF}'`],["$top",1]])}`,n=(0,yn.ensureSuccess)(await e.get(r),e.apiUrl(r)),i=(t=n.body)===null||t===void 0?void 0:t.value;if(!Array.isArray(i))throw new Ve.ConnectionError(e.apiUrl(r),n.status,`the row-summary template lookup returned a malformed answer \u2014 expected an OData 'value' array but got ${(0,zi.describeMalformedValue)(i)}`);let o=Yv(i,e.apiUrl(r),n.status,"the row-summary template lookup");if(!o)return;let a=o.msdyn_aitemplateid;if(typeof a=="string"&&a!=="")try{return(0,qe.normalizeGuid)(a,"msdyn_aitemplateid")}catch{}throw new Ve.ConnectionError(e.apiUrl(r),n.status,`the row-summary template lookup returned a malformed row \u2014 expected a GUID 'msdyn_aitemplateid' but got ${a===""?"an empty string":typeof a=="string"?"a string that is not a GUID":(0,zi.describeMalformedValue)(a)}`)}function tM(e){return`${e} row summary`}async function Koe(e,t,r){var n;let i=`/msdyn_aimodels(${t})${(0,qe.odataQuery)([["$select","msdyn_name,_msdyn_templateid_value"]])}`,o=await e.get(i);if(o.status===404)return!1;let a=(n=(0,yn.ensureSuccess)(o,e.apiUrl(i)).body)!==null&&n!==void 0?n:{},s=await eM(e);return typeof a.msdyn_name=="string"&&a.msdyn_name.toLowerCase()===tM(r).toLowerCase()&&typeof a._msdyn_templateid_value=="string"&&s!==void 0&&a._msdyn_templateid_value.toLowerCase()===s.toLowerCase()}async function Joe(e,t,r={}){var n;let i=`ais_RowSummary_${t.entityLogicalName}`,o=`/aiskillconfigs${(0,qe.odataQuery)([["$select","aiskillconfigid,_aimodel_value"],["$filter",`uniquename eq '${(0,qe.odataLiteral)(i)}'`],["$top",1]])}`,a=(0,yn.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 Ve.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,zi.describeMalformedValue)(s)}`);let l=Yv(s,e.apiUrl(o),a.status,"the existing row-summary skill lookup");if(l)return{modelId:l._aimodel_value,aiSkillConfigId:l.aiskillconfigid};let u=await Hoe(e,t.entityLogicalName),c=await eM(e);if(c===void 0)throw new Ve.SdkError(Te.ROW_SUMMARY_TEMPLATE_NOT_FOUND_CODE,`Cannot configure the row summary of '${t.entityLogicalName}': this org has no AI template '${XF}' (msdyn_aitemplates), which a row-summary model is built from. Nothing was written.`);let d=(0,GF.newId)(),f=(0,GF.newId)(),m=JSON.stringify(ZF(t)),p={ModelId:d,RunConfigurationId:f,ModelName:tM(t.entityLogicalName),TemplateId:c,CustomConfiguration:m,Source:joe,RunConfiguration:""};(0,yn.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,yn.ensureSuccess)(await e.post("/aiskillconfigs",h),e.apiUrl("/aiskillconfigs")),b=(0,yn.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=Joe;async function Yoe(e,t){var r;let n=`ais_RowSummary_${t.entityLogicalName}`,i=`/aiskillconfigs${(0,qe.odataQuery)([["$select","aiskillconfigid,_aimodel_value"],["$filter",`uniquename eq '${(0,qe.odataLiteral)(n)}'`],["$top",1]])}`,o=(0,yn.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 Ve.ConnectionError(e.apiUrl(i),o.status,`the row-summary skill lookup returned a malformed answer \u2014 expected an OData 'value' array but got ${(0,zi.describeMalformedValue)(a)}`);let s=Yv(a,e.apiUrl(i),o.status,"the row-summary skill lookup");if(!s)return{removed:!1};let l=(0,qe.normalizeGuid)(s.aiskillconfigid,"aiskillconfigid"),u=s._aimodel_value?(0,qe.normalizeGuid)(s._aimodel_value,"_aimodel_value"):void 0,c=u?await Koe(e,u,t.entityLogicalName):!1,d=t.entityLogicalName,f=`/aiskillconfigs(${l})`,m=await HF(e,f,`${f}${(0,qe.odataQuery)([["$select","aiskillconfigid"]])}`);if(m.kind==="failed")throw m.stillThere===void 0&&u&&c?(0,Ve.attachCause)(new Ve.SdkError(Te.ROW_SUMMARY_REMOVAL_UNCONFIRMED_CODE,`Removing the row summary of '${d}' could not be confirmed: deleting its skill row failed (${KF(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 HF(e,p,`${p}${(0,qe.odataQuery)([["$select","msdyn_aimodelid"]])}`,Xoe);if(h.kind==="failed")throw(0,Ve.attachCause)(new Ve.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"} (${KF(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)}return{removed:!0}}Te.removeRowSummary=Yoe;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 Qoe="0x8004f01f";function Xoe(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()===Qoe}function Zoe(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 HF(e,t,r,n=()=>!1){let i;try{let o=await(0,yn.resendWhile)(Zoe,()=>e.delete(t));if(o.status>=200&&o.status<300||o.status===404)return{kind:"gone"};if(n(o))return{kind:"kept"};try{(0,yn.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 KF(e){return e instanceof Error?e.message:String(e)}});var oM=v(pl=>{"use strict";Object.defineProperty(pl,"__esModule",{value:!0});pl.findArtifact=pl.resolveArtifact=void 0;var qt=le(),ji=$d(),eae=zd(),tae=Lt(),rae=ye(),nM=Q();async function iM(e,t,r){let n="/uxagentprojects"+(0,qt.odataQuery)([["$select","uxagentprojectid,name"],["$filter",`name eq '${(0,qt.odataLiteral)(t)}'`],...r!==void 0?[["$top",String(r)]]:[]]);return(await(0,tae.collectPages)(e,n,"resolveArtifact('genPage')",void 0,{headers:{"MSCRM.IncludeUnpublished":"true"}})).map(o=>({id:String(o.uxagentprojectid),name:String(o.name)}))}async function nae(e,t,r){var n,i,o,a,s,l,u,c,d,f,m,p;switch(t){case"app":{let h=(0,eae.unpublishedAppModulesQuery)("appmoduleid,name,appmoduleidunique",`uniquename eq '${(0,qt.odataLiteral)((n=r.uniqueName)!==null&&n!==void 0?n:"")}'`,1),b=(i=(0,rae.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,ji.queryRecords)(e,"systemform",{select:["formid","name"],filter:`name eq '${(0,qt.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,ji.queryRecords)(e,"appaction",{select:["appactionid","buttonlabeltext"],filter:`contextvalue eq '${(0,qt.odataLiteral)(r.entity)}'`,top:1});return h&&h.length?[{id:r.entity,entity:r.entity}]:[]}case"form":return(await(0,ji.queryRecords)(e,"systemform",{select:["formid","name"],filter:`name eq '${(0,qt.odataLiteral)((a=r.name)!==null&&a!==void 0?a:"")}' and objecttypecode eq '${(0,qt.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,ji.queryRecords)(e,"savedqueryvisualization",{select:["savedqueryvisualizationid","name"],filter:`name eq '${(0,qt.odataLiteral)((l=r.name)!==null&&l!==void 0?l:"")}' and primaryentitytypecode eq '${(0,qt.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,ji.queryRecords)(e,"savedquery",{select:["savedqueryid","name"],filter:`name eq '${(0,qt.odataLiteral)((c=r.name)!==null&&c!==void 0?c:"")}' and returnedtypecode eq '${(0,qt.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,ji.queryRecords)(e,"webresource",{select:["webresourceid","name"],filter:`name eq '${(0,qt.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,ji.queryRecords)(e,"solution",{select:["solutionid","uniquename"],filter:`uniquename eq '${(0,qt.odataLiteral)((m=r.uniqueName)!==null&&m!==void 0?m:"")}'`,top:1})||[]).map(g=>({id:String(g.solutionid),name:String(g.uniquename)}));case"genPage":return iM(e,(p=r.name)!==null&&p!==void 0?p:"");default:return[]}}pl.resolveArtifact=nae;async function iae(e,t,r){var n,i,o,a,s,l;let u=(0,qt.odataLiteral)((n=r.name)!==null&&n!==void 0?n:""),c=(0,qt.odataLiteral)((i=r.entity)!==null&&i!==void 0?i:"");if(t==="command"){if(!r.entity)return null;let h=await(0,ji.queryRecords)(e,"appaction",{select:["appactionid"],filter:`contextvalue eq '${(0,qt.odataLiteral)(r.entity)}'`,top:1});return h&&h.length?r.entity:null}if(t==="genPage"){let h=await iM(e,(o=r.name)!==null&&o!==void 0?o:"",2);if(h.length>1)throw new nM.AmbiguousArtifactError(t,(a=r.name)!==null&&a!==void 0?a:"",h.length);return h.length===1?h[0].id:null}let d=oae(t,u,c,r),f=t!=="app",m=await(0,ji.queryRecords)(e,d.set,{select:[d.idField],filter:d.filter,top:f?2:1});if(f&&m&&m.length>1)throw new nM.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}pl.findArtifact=iae;function oae(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,qt.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 sM=v(im=>{"use strict";Object.defineProperty(im,"__esModule",{value:!0});im.seedRecordGraph=void 0;var aM=$d(),aae=bd(),nm=le(),sae=Q();async function lae(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,aae.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 k of f.records){let I={...k.body};for(let D of(a=k.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 sae.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,nm.assertODataName)(await u(P),`entity set for parent '${D.parentEntity}'`),Oe=(0,nm.normalizeGuid)(x,`parent id for bind '${D.navProperty}'`);I[`${D.navProperty}@odata.bind`]=`/${K}(${Oe})`}h.push(I)}let g=p?h.map(k=>{let I=k[p];return I!=null&&I!==""?String(I):null}):h.map(()=>null),b=new Map;if(p){let k=(0,nm.assertODataName)(p,"RecordGraph matchOn key"),I=[...new Set(g.filter(D=>D!==null))];if(I.length){let D=I.map(x=>`${k} eq '${(0,nm.odataLiteral)(x)}'`).join(" or "),P=await(0,aM.queryRecords)(e,m,{select:[k,`${m}id`],filter:D,top:5e3});for(let x of P??[]){let K=x[k];K!=null&&b.set(String(K).toLowerCase(),String(x[`${m}id`]))}}}let w=[],C=new Map,S=h.map((k,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(k)-1;return C.set(P,K),K}return w.push(k)-1}),O=w.length?await(0,aM.createRecordsBulk)(e,m,w):[];c[m]=h.map((k,I)=>{let D=g[I];return D&&b.has(D.toLowerCase())?b.get(D.toLowerCase()):O[S[I]]})}return{createdIds:c}}im.seedRecordGraph=lae});var yM=v(tr=>{"use strict";Object.defineProperty(tr,"__esModule",{value:!0});tr.getEntityPrivileges=tr.addEntityPrivilegesToRole=tr.deleteSecurityRole=tr.createPersonaRole=tr.createSecurityRole=tr.SDK_ROLE_MARKER=void 0;var Mn=ye(),Rt=le(),Kr=Q(),om={read:"Read",create:"Create",write:"Write",delete:"Delete",append:"Append",appendTo:"AppendTo",assign:"Assign",share:"Share"},Xv={user:"Basic",businessUnit:"Local",parentChild:"Deep",organization:"Global"},lM={user:1,businessUnit:2,parentChild:3,organization:4},Qv={user:"CanBeBasic",businessUnit:"CanBeLocal",parentChild:"CanBeDeep",organization:"CanBeGlobal"};tr.SDK_ROLE_MARKER="Authored by @maker-studio/cds-maker-sdk (persona/security role).";function uae(e){return Object.prototype.hasOwnProperty.call(om,e)?om[e]:void 0}function cae(e){return Object.prototype.hasOwnProperty.call(Xv,e)}var uM=new WeakMap,cM=new WeakMap;async function pM(e,t){var r,n;(0,Rt.assertODataName)(t,"entity logical name");let i=uM.get(e);i||(i=new Map,uM.set(e,i));let o=i.get(t);if(o)return o;let a=`/EntityDefinitions(LogicalName='${(0,Rt.odataPathLiteral)(t)}')${(0,Rt.odataQuery)([["$select","LogicalName,Privileges"]])}`,l=(n=(r=(0,Mn.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 Kr.InvalidArgumentError(`Entity '${t}' exposes no privileges (unknown or non-securable entity).`);return i.set(t,l),l}async function dae(e){var t,r,n;let i=cM.get(e);if(i)return i;let o=`/businessunits${(0,Rt.odataQuery)([["$select","businessunitid"],["$filter","_parentbusinessunitid_value eq null"],["$top",1]])}`,l=(n=((r=(t=(0,Mn.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 Kr.InvalidArgumentError("Could not resolve the root business unit.");let u=(0,Rt.normalizeGuid)(l,"businessUnitId");return cM.set(e,u),u}async function mM(e,t){var r;let n=new Map;for(let i of t){if(!i.access||i.access.length===0)throw new Kr.InvalidArgumentError(`Entity '${i.entity}' privilege request has no access levels.`);let o=(r=i.scope)!==null&&r!==void 0?r:"user";if(!cae(o))throw new Kr.InvalidArgumentError(`Unknown privilege scope '${o}' for entity '${i.entity}'.`);let a=await pM(e,i.entity);for(let s of i.access){let l=uae(s);if(!l)throw new Kr.InvalidArgumentError(`Unknown access level '${s}' for entity '${i.entity}'.`);let u=a.find(p=>p.PrivilegeType===l);if(!u)throw new Kr.InvalidArgumentError(`Entity '${i.entity}' does not support '${s}' access.`);let c=Qv[o];if(u[c]===!1)throw new Kr.InvalidArgumentError(`Privilege '${u.Name}' on '${i.entity}' does not support the '${o}' scope.`);let d=(0,Rt.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 Kr.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=lM[o]>lM[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 fae(e,t,r,n){if(r.length===0&&!n)return;let i={Privileges:r.map(a=>({Depth:Xv[a.scope],PrivilegeId:a.privilegeId}))},o=`/roles(${t})/Microsoft.Dynamics.CRM.ReplacePrivilegesRole`;(0,Mn.ensureSuccess)(await e.post(o,i),e.apiUrl(o))}async function dM(e,t,r,n,i){var o,a;let s=`/${t}(${r})/${n}${(0,Rt.odataQuery)([["$select","roleid"],["$filter",`roleid eq ${i}`]])}`;return((a=(o=(0,Mn.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 pae(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,Rt.normalizeGuid)(l,"teamId");if(!await dM(e,"teams",u,"teamroles_association",t)){let c=`/teams(${u})/teamroles_association/$ref`;(0,Mn.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,Rt.normalizeGuid)(l,"userId");if(!await dM(e,"systemusers",u,"systemuserroles_association",t)){let c=`/systemusers(${u})/systemuserroles_association/$ref`;(0,Mn.ensureSuccess)(await e.post(c,s),e.apiUrl(c))}a.push(u)}return{teams:o,users:a}}async function fM(e,t,r){var n,i;let o=`/roles${(0,Rt.odataQuery)([["$select","roleid,description,ismanaged"],["$filter",`name eq '${(0,Rt.odataLiteral)(t)}' and _businessunitid_value eq ${r}`]])}`,l=((i=(n=(0,Mn.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:"")===tr.SDK_ROLE_MARKER};if(l.some(d=>!u(d)))throw new Kr.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 Kr.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,Rt.normalizeGuid)(c,"roleId"):void 0}function mae(e){var t,r;return{teams:((t=e?.teams)!==null&&t!==void 0?t:[]).map(n=>(0,Rt.normalizeGuid)(n,"teamId")),users:((r=e?.users)!==null&&r!==void 0?r:[]).map(n=>(0,Rt.normalizeGuid)(n,"userId"))}}function hM(e){return e.map(t=>({entity:t.entity,privilegeName:t.privilegeName,privilegeType:t.privilegeType,scope:t.scope}))}async function gM(e,t){var r,n;let i=(r=t.name)===null||r===void 0?void 0:r.trim();if(!i)throw new Kr.InvalidArgumentError("createSecurityRole: a non-empty role name is required.");let o=t.businessUnitId?(0,Rt.normalizeGuid)(t.businessUnitId,"businessUnitId"):await dae(e),a=await mM(e,(n=t.privileges)!==null&&n!==void 0?n:[]),s=mae(t.assignTo),l=await fM(e,i,o),u=l!==void 0;if(!l){let d="/roles",f={name:i,description:tr.SDK_ROLE_MARKER,"[email protected]":`/businessunits(${o})`};try{let m=(0,Mn.ensureSuccess)(await e.post(d,f),e.apiUrl(d));l=(0,Rt.normalizeGuid)((0,Mn.requireCreatedId)(m,"roleid","role"),"roleId")}catch(m){let p;try{p=await fM(e,i,o)}catch{p=void 0}if(!p)throw m;l=p}}await fae(e,l,a,u);let c=await pae(e,l,s);return{roleId:l,name:i,reused:u,appliedPrivileges:hM(a),assignedTeams:c.teams,assignedUsers:c.users}}tr.createSecurityRole=gM;async function hae(e,t){var r,n;let i=(r=t.persona)===null||r===void 0?void 0:r.trim();if(!i)throw new Kr.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 gM(e,{name:i,businessUnitId:t.businessUnitId,privileges:o,assignTo:t.assignTo})}tr.createPersonaRole=hae;async function gae(e,t){let n=`/roles(${(0,Rt.normalizeGuid)(t,"roleId")})`;(0,Mn.ensureSuccess)(await e.delete(n),e.apiUrl(n))}tr.deleteSecurityRole=gae;async function yae(e,t,r){let n=(0,Rt.normalizeGuid)(t,"roleId");if(r.length===0)throw new Kr.InvalidArgumentError("addEntityPrivilegesToRole requires at least one entity privilege (an empty grant would be a silent no-op).");let i=await mM(e,r),o={Privileges:i.map(s=>({Depth:Xv[s.scope],PrivilegeId:s.privilegeId}))},a=`/roles(${n})/Microsoft.Dynamics.CRM.AddPrivilegesRole`;return(0,Mn.ensureSuccess)(await e.post(a,o),e.apiUrl(a)),hM(i)}tr.addEntityPrivilegesToRole=yae;var bae=new Map(Object.keys(om).map(e=>[om[e],e]));async function vae(e,t){return(await pM(e,t)).map(n=>{let i=Object.keys(Qv).filter(a=>n[Qv[a]]!==!1),o=bae.get(n.PrivilegeType);return{name:n.Name,privilegeId:n.PrivilegeId,privilegeType:n.PrivilegeType,...o?{access:o}:{},scopes:i}})}tr.getEntityPrivileges=vae});var LM=v(yr=>{"use strict";Object.defineProperty(yr,"__esModule",{value:!0});yr.createMakerSdk=yr.MakerSdk=yr.PUSH_NOT_ATTEMPTED_CODE=yr.ALREADY_EXISTS_CODE=void 0;var bM=Fm(),vM=Qr(),Z=Q(),bn=Ma(),wae=MC(),OM=zC(),ml=QC(),Cae=Um(),Eae=bE(),hl=CE(),Aae=$E(),Sae=qE(),Nae=bA(),wM=mS(),kt=bd(),Zv=_g(),CM=_N(),am=ru(),Hi=$d(),sm=$N(),gl=Fd(),_ae=Ud(),rr=Tg(),Tae=$g(),Dae=zg(),EM=xg(),Iae=VF(),lm=pt(),Oae=Jo(),pi=qb(),vn=Wm(),ew=_v(),Pae=3e5,gr=ye(),La=le(),yl=rM(),AM=oM(),Rae=sM(),kae=nb(),Ac=yM(),PM=Symbol("cds-maker-sdk.committedWrite");function Lae(e){return typeof e=="object"&&e!==null&&(e[PM]=!0),e}function $ae(e){return typeof e=="object"&&e!==null&&e[PM]===!0}var xae={fileConcurrency:1},tw="SOLUTION_COMPONENT_UNCLASSIFIED",Fae=2,Mae=4,Uae="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 SM(e){return{componentId:e.objectId,componentType:e.componentType,workflowCategory:e.workflowCategory,reason:"unsupported",...e.includesAllSubcomponents?{detail:Uae}:{}}}function NM(e,t){return{componentId:e.objectId,componentType:e.componentType,workflowCategory:e.workflowCategory,reason:"failed",error:Ro(t)}}function _M(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,gr.nowIso)(),isDirty:!1}}var Bae=new Set(["entity","appmodule","dashboard","uxagentproject"]);function qae(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,La.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 Vae(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 OM.WorkspaceManager(Wae,e.instanceUrl,(0,Cae.assertStorageContract)(t))}yr.ALREADY_EXISTS_CODE="ARTIFACT_ALREADY_EXISTS";var Gae="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";yr.PUSH_NOT_ATTEMPTED_CODE="PUSH_NOT_ATTEMPTED";var Wae="<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,ew.resolveReadConcurrency)(t.readConcurrency),this.languageCode=(r=t.languageCode)!==null&&r!==void 0?r:Oae.DEFAULT_LCID,this.cacheStalenessMs=(n=t.cacheStalenessMs)!==null&&n!==void 0?n:Pae,this.compiler={load:(0,Tae.createGenPageTypeScriptLoader)(t.typescript)},this.workspace=Vae(t),this.versions=new ml.VersionManager(this.workspace),this.dataverse=new Eae.DataverseClient(t.instanceUrl,t.httpClient,t.solutionUniqueName,this.readConcurrency),this.connectivity=new Nae.ConnectivityRouter(this.dataverse,t.instanceUrl,{powerAppsServiceClient:t.powerAppsServiceClient,powerPlatformApiClient:t.powerPlatformApiClient,connectorRuntimeClient:t.connectorRuntimeClient}),this.registrations=(0,Iae.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,vn.deepEqual)(b.snapshot,m))throw new Z.LocalEditsWouldBeLostError(t,r,h,c);await this.versions.storeMeta(t,r,{...b,etag:c,fetchedAt:(0,gr.nowIso)()},b)}return(0,pi.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:ml.PROJECTION_VERSION,fetchedAt:(0,gr.nowIso)(),snapshot:(0,pi.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,pi.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,rr.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(SM(o));continue}let s=await this.fetchArtifact(a,o.objectId);n.push(_M(a,o,s))}catch(a){i.push(NM(o,a))}return await this.workspace.updateManifest({lastSyncAt:(0,gr.nowIso)()}),{summaries:n,skipped:i}}async fetchComponentsOverlapped(t,r,n){await(0,ew.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(SM(o));return}let s=await this.applyFetchedArtifactUnlocked(a.type,o.objectId,a.reg,a.fetched);await this.acknowledgeRefresh(a.type,o.objectId),r.push(_M(a.type,o,s))}catch(a){n.push(NM(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,xae);return{kind:"artifact",type:r,reg:n,fetched:i}}):(0,ew.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,hl.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,Aae.generateGenPageRuntimeTypes)(n=>this.fetchEntityMetadata(n),t,r)}findTables(t,r){return(0,hl.findTables)(this.dataverse,t,r)}getEnvironmentLanguages(){return(0,Sae.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,hl.findColumns)(this.dataverse,t,r,n)}createTable(t){return this.schemaWrite([t.schemaName],()=>(0,kt.createTable)(this.dataverse,t))}createColumn(t,r){return this.schemaWrite([t],()=>(0,kt.createColumn)(this.dataverse,t,r))}createColumns(t,r){return this.schemaWrite([t],()=>(0,kt.createColumns)(this.dataverse,t,r))}updateColumn(t,r,n){return this.schemaWrite([t],()=>(0,kt.updateColumn)(this.dataverse,t,r,n))}deleteColumn(t,r){return this.schemaWrite([t],()=>(0,kt.deleteColumn)(this.dataverse,t,r))}setFormSecurityRoles(t,r){return(0,Zv.setFormSecurityRoles)(this.dataverse,t,r)}getFormSecurityRoles(t){return(0,Zv.getFormSecurityRoles)(this.dataverse,t)}setColumnVisualization(t,r,n){return(0,kt.setColumnVisualization)(this.dataverse,t,r,n)}getColumnVisualization(t,r){return(0,kt.getColumnVisualization)(this.dataverse,t,r)}createCustomerColumn(t,r){return this.schemaWrite([t,"account","contact"],()=>(0,kt.createCustomerColumn)(this.dataverse,t,r))}insertStatusValue(t,r){return this.schemaWrite([t],()=>(0,kt.insertStatusValue)(this.dataverse,t,r))}updateTable(t,r){return this.schemaWrite([t],()=>(0,kt.updateTable)(this.dataverse,t,r))}async setEntityIcon(t,r){if(await this.schemaWrite([t],()=>(0,kt.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,La.xmlText)(t)}</entity></entities></importexportxml>`;(0,gr.ensureSuccess)(await this.dataverse.post("/PublishXml",{ParameterXml:n}),this.dataverse.apiUrl("/PublishXml"))}}createAlternateKey(t,r){return(0,kt.createAlternateKey)(this.dataverse,t,r)}deleteAlternateKey(t,r){return(0,kt.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,kt.createRelationship)(this.dataverse,t))}deleteRelationship(t){return this.schemaWrite(void 0,()=>(0,kt.deleteRelationship)(this.dataverse,t))}createGlobalOptionSet(t){return(0,kt.createGlobalOptionSet)(this.dataverse,t)}deleteGlobalOptionSet(t){return(0,kt.deleteGlobalOptionSet)(this.dataverse,t)}deleteTable(t){return this.schemaWrite(void 0,()=>(0,kt.deleteTable)(this.dataverse,t))}createSecurityRole(t){return(0,Ac.createSecurityRole)(this.dataverse,t)}createPersonaRole(t){return(0,Ac.createPersonaRole)(this.dataverse,t)}deleteSecurityRole(t){return(0,Ac.deleteSecurityRole)(this.dataverse,t)}addEntityPrivilegesToRole(t,r){return(0,Ac.addEntityPrivilegesToRole)(this.dataverse,t,r)}getEntityPrivileges(t){return(0,Ac.getEntityPrivileges)(this.dataverse,t)}createRecord(t,r){return(0,Hi.createRecord)(this.dataverse,t,r)}createRecordsBulk(t,r){return(0,Hi.createRecordsBulk)(this.dataverse,t,r)}updateRecord(t,r,n){return(0,Hi.updateRecord)(this.dataverse,t,r,n)}upsertRecord(t,r,n){return(0,Hi.upsertRecord)(this.dataverse,t,r,n)}deleteRecord(t,r){return(0,Hi.deleteRecord)(this.dataverse,t,r)}getRecord(t,r,n){return(0,Hi.getRecord)(this.dataverse,t,r,n)}queryRecords(t,r){return(0,Hi.queryRecords)(this.dataverse,t,r)}seedRecordGraph(t,r){return(0,Rae.seedRecordGraph)(this.dataverse,t,r)}resolveArtifact(t,r){return(0,AM.resolveArtifact)(this.dataverse,t,r)}findArtifact(t,r){return(0,AM.findArtifact)(this.dataverse,t,r)}async deleteAppCascade(t,r){await this.workspace.ensureReady();let n=await(0,Dae.deleteAppCascade)(this.dataverse,t,r),i=(0,La.normalizeGuid)(t,"appModuleId");return await this.workspace.readArtifact("app",i)&&await this.workspace.deleteArtifact("app",i),n}associateRecords(t,r,n){return(0,Hi.associateRecords)(this.dataverse,t,r,n)}disassociateRecords(t,r,n,i){return(0,Hi.disassociateRecords)(this.dataverse,t,r,n,i)}createWebResource(t){return(0,sm.createWebResource)(this.dataverse,t)}updateWebResource(t,r){return(0,sm.updateWebResource)(this.dataverse,t,r)}getWebResource(t){return(0,sm.getWebResource)(this.dataverse,t)}deleteWebResource(t){return(0,sm.deleteWebResource)(this.dataverse,t)}getAppSettings(t){return(0,gl.readAppSettings)(this.dataverse,t)}setAppSetting(t,r,n){return(0,gl.setAppSetting)(this.dataverse,t,r,n)}setHeaderAndNavigationRefresh(t,r){if(typeof r!="boolean")throw new Z.ValidationError("app",t,[{pointer:"/headerAndNavigationRefresh",rule:_ae.HEADER_NAV_BOOLEAN_RULE,message:`enabled must be a boolean, got ${typeof r}`}]);return(0,gl.setAppSetting)(this.dataverse,t,gl.HEADER_AND_NAVIGATION_REFRESH,r?gl.APP_SETTING_ON:gl.APP_SETTING_OFF)}getSolution(t){return(0,rr.getSolution)(this.dataverse,t)}createPublisher(t){return(0,rr.createPublisher)(this.dataverse,t)}createSolution(t){return(0,rr.createSolution)(this.dataverse,t)}setSolutionVersion(t,r){return(0,rr.setSolutionVersion)(this.dataverse,t,r)}addSolutionComponent(t){return(0,rr.addSolutionComponent)(this.dataverse,t)}removeSolutionComponent(t,r,n){return(0,rr.removeSolutionComponent)(this.dataverse,t,r,n)}exportSolution(t){return(0,rr.exportSolution)(this.dataverse,t)}importSolution(t){return this.schemaWrite(void 0,()=>(0,rr.importSolution)(this.dataverse,t))}getDeploymentSettingsTemplate(t){return(0,rr.getDeploymentSettingsTemplate)(this.dataverse,t)}deleteSolution(t){return this.schemaWrite(void 0,()=>(0,rr.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,OM.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,vn.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=bn.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,wae.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=bn.JsonPointer.resolve(a,n);if(s===void 0)throw new Z.PathNotFoundError(t,r,n);let l=Ki(s)&&Ki(i)?{...s,...i}:i;return bn.JsonPointer.set(a,n,(0,pi.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=bn.JsonPointer.resolve(s,n);if(l===void 0)throw new Z.PathNotFoundError(t,r,n);if(!Array.isArray(l)){if(!Ki(l)||!Ki(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,pi.cloneJson)(i[f]),p=(0,lm.isValueMapKey)(f)||(0,lm.pointerTouchesValueMap)(n);d[f]=p?m:Array.isArray(m)?m.map(h=>Ki(h)?this.assignMissingIds(t,h):h):Ki(m)?this.assignMissingIds(t,m):m}for(let f of Object.keys(d))bn.JsonPointer.set(s,bn.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,lm.pointerTouchesValueMap)(n)?(0,pi.cloneJson)(i):this.assignMissingIds(t,(0,pi.cloneJson)(i)),c=Kae(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=bn.JsonPointer.resolve(l,n);if(u===void 0)throw new Z.PathNotFoundError(t,r,n);let c=bn.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");bn.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),IM(c);let f=bn.JsonPointer.resolve(l,DM(n));return Array.isArray(f)&&f!==c&&IM(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(bn.JsonPointer.resolve(o,n)===void 0)throw new Z.PathNotFoundError(t,r,n);return bn.JsonPointer.remove(o,n),this.assertStructurallyValid(t,r,o,DM(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,yl.retrieveSetting)(this.dataverse,t,r)}saveSettingValue(t,r,n){return(0,yl.saveSettingValue)(this.dataverse,t,r,n)}getAiReadiness(t){return(0,yl.getAiReadiness)(this.dataverse,t)}setAppAiFeatures(t,r,n){return(0,yl.setAppAiFeatures)(this.dataverse,t,r,n)}configureRowSummary(t,r){return(0,yl.configureRowSummary)(this.dataverse,t,r)}removeRowSummary(t){return(0,yl.removeRowSummary)(this.dataverse,t)}async enrichDefaultViews(t,r,n={}){let i=await(0,kae.findDefaultViews)(this.dataverse,t,{excludeViewIds:n.excludeViewIds}),o=n.publish===!1,a=[],s=[],l=()=>({updated:[...a],results:[...s],pendingPublish:a.length>0?[{scope:(0,vM.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&&$ae(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,pi.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=qae(a),f;if(d)try{await(0,vM.publishXml)(this.dataverse,d)}catch(p){f=Ro(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||!Bae.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,vn.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:Ro(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,gr.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||!jae(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,vn.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,gr.isVersionToken)(o)||!RM(a,t.heldSiblings)||!kM(a)||!(o!==t.heldEtag||!(0,vn.deepEqual)(a??void 0,t.heldSiblings))||!(0,vn.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,gr.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 (${Ro(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,vn.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,vn.deepEqual)(c(i.snapshot),c(u)))return;await this.versions.storeMeta(r,n,{...i,etag:a,fetchedAt:(0,gr.nowIso)(),...s?{memberEtags:s}:{},...l?{siblingEtags:l}:{}},i)}catch{}}async verifyPublished(t,r,n){var i;if(t!=="app"){let o=this.registrations.get(t);return o?.api.getPublished?this.verifyPublishedContent(o,t,r,n):{kind:"unverifiable",reason:`published-projection verification is not characterised for '${t}'; the publish was submitted`}}try{let o=`/appmodules(${(0,La.normalizeGuid)(r,"id")})${(0,La.odataQuery)([["$select","appmoduleid,name,description"]])}`,a=await this.dataverse.get(o);if(a.status>=200&&a.status<300){let s=(i=a.body)!==null&&i!==void 0?i:{},l=n;if(!l)return{kind:"unverifiable",reason:"there is no local copy of the app to compare the published projection with"};let u=["name","description"].filter(d=>l[d]!==void 0);if(u.length===0)return{kind:"unverifiable",reason:"the local copy of the app holds neither a name nor a description to compare the published projection with, and its presence alone proves nothing for a re-publish"};let c=u.filter(d=>{var f,m;return((f=l[d])!==null&&f!==void 0?f:"")!==((m=s[d])!==null&&m!==void 0?m:"")});return c.length>0?{kind:"unverifiable",reason:`the published projection does not yet match the saved app (${c.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 ${a.status}`}}catch(o){return{kind:"unverifiable",reason:Ro(o).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,vn.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,vn.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:Ro(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,hl.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 k=S?.artifact!==void 0&&!(0,vn.deepEqual)(S.artifact,p),I=k?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:ml.PROJECTION_VERSION,fetchedAt:(0,gr.nowIso)(),snapshot:(0,pi.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}:{}})():{},...k?{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===yr.ALREADY_EXISTS_CODE)return{type:d,id:f,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:w};if(w instanceof Z.SdkError&&w.code===bM.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===bM.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===gr.VERSION_CONFLICT_CODE)return{type:d,id:f,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:(0,EM.isFailureAfterPrimaryWrite)(w)?w:new Z.VersionConflictError(d,f,(c=h?.etag)!==null&&c!==void 0?c:null,null,w.message)};throw b?Lae(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!==ml.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 ${ml.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,Zv.readPrimaryCreateRefusal)(a):void 0;if(s?.status===404&&await(0,CM.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(yr.ALREADY_EXISTS_CODE,rw(r,n,u)+(this.createRecovery==="adoptExact"?` ${TM(Gae)}`:"")),a)}if(!(a instanceof Z.SdkError)||a.code!==gr.VERSION_CONFLICT_CODE||(0,EM.isFailureAfterPrimaryWrite)(a))throw a;if(this.createRecovery==="adoptExact"&&s?.status===412){let l=await(0,CM.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(yr.ALREADY_EXISTS_CODE,`${rw(r,n)} ${TM(l.refused)}`)}throw new Z.SdkError(yr.ALREADY_EXISTS_CODE,rw(r,n))}}async persistAdoption(t,r,n,i){let{artifact:o,etag:a}=i,s=!(0,vn.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:ml.PROJECTION_VERSION,fetchedAt:(0,gr.nowIso)(),snapshot:(0,pi.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(k=>k.entityLogicalName).filter(k=>!!k)),c=new Set(l.filter(k=>k.needsColumnDetail).map(k=>k.entityLogicalName)),d=new Set(l.filter(k=>k.needsColumnDetail||!k.fieldName).map(k=>k.entityLogicalName)),f=k=>l.filter(I=>I.entityLogicalName===k).every(I=>I.fetchRequired===!1),m=new Map,p=new Map;for(let k of u){let I=await this.readCachedEntityMetadata(k);if(I&&c.has(k)&&(I.columnDetailComplete!==!0||!(typeof I.columnDetailVersion=="number"&&I.columnDetailVersion>=hl.COLUMN_DETAIL_VERSION)||I.attributes.some(D=>typeof D.attributeTypeName!="string"))&&(I=null),!I&&!d.has(k)){if(!f(k)){let D=l.filter(P=>P.entityLogicalName===k).map(P=>P.fieldName);try{let P=await(0,hl.readColumnHints)(this.dataverse,k,D);p.set(k,new Map(P.map(x=>[x.logicalName,x])))}catch{}}continue}if(!I&&!f(k))try{await this.loadMissedEntityMetadata(k),I=await this.readCachedEntityMetadata(k)}catch{}I&&m.set(k,I)}let h=(k,I)=>{var D,P,x;return(P=(D=m.get(k))===null||D===void 0?void 0:D.attributes.find(K=>K.logicalName===I))!==null&&P!==void 0?P:(x=p.get(k))===null||x===void 0?void 0:x.get(I)},g=this.languageCode,w=l.some(k=>{if(!k.needsLabel||!k.fieldName)return!1;let I=h(k.entityLogicalName,k.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:(k,I)=>{let D=h(k,I);return D?{displayName:Hae(D,g,w),attributeType:D.attributeType}:void 0},resolveEntity:k=>m.get(k),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,wM.readControlManifest)(this.dataverse,i));let n=new Map;for(let i of t.columns)n.set(i,await(0,wM.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:Ro(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(yr.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:Ro(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,lm.assignMissingIds)(r)}async resolveComponentType(t){if(t.genPage)return"genPage";switch(t.componentType){case rr.SolutionComponentType.SavedQuery:return"view";case rr.SolutionComponentType.SavedQueryVisualization:return"chart";case rr.SolutionComponentType.AppModule:return"app";case rr.SolutionComponentType.Workflow:return this.workflowArtifactType(t);case rr.SolutionComponentType.SystemForm:return this.systemFormArtifactType(t.objectId);default:return}}async systemFormArtifactType(t){let r=await(0,am.readSystemFormType)(this.dataverse,t);if(Number.isNaN(r))throw new Z.SdkError(tw,`System form '${t}' answered without a readable type, so whether it is a form or a dashboard cannot be told.`);return(0,am.systemFormKindOf)(r)}async workflowArtifactType(t){let r=(0,La.normalizeGuid)(t.objectId,"workflowId"),n=`/workflows(${r})${(0,La.odataQuery)([["$select","category,businessprocesstype"]])}`,o=(0,gr.ensureSuccess)(await this.dataverse.get(n),this.dataverse.apiUrl(n)).body,a=(0,am.decodeCode)(o?.category);if(Number.isNaN(a))throw new Z.SdkError(tw,`Workflow '${r}' answered without a readable category, so its kind cannot be told.`);if(t.workflowCategory=a,a===Fae)return"businessRule";if(a===Mae){let s=(0,am.decodeCode)(o?.businessprocesstype);if(Number.isNaN(s))throw new Z.SdkError(tw,`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}};yr.MakerSdk=um;function zae(e){return new um(e)}yr.createMakerSdk=zae;function Ro(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 kM(e){return Object.values(e??{}).every(gr.isVersionToken)}function jae(e,t){return RM(e,t)&&kM(e)&&Object.keys(e??{}).every(r=>t?.[r]===e?.[r])}function TM(e){return`createRecovery 'adoptExact' did not adopt it: ${e}.`}function rw(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 Hae(e,t,r){let n=e.localizedDisplayName;return n?.[t]||(r===void 0?void 0:n?.[r])||e.displayName}function Ki(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function DM(e){let t=e.lastIndexOf("/");return t<=0?"":e.slice(0,t)}function IM(e){e.length===0||!e.every(t=>Ki(t)&&typeof t.order=="number")||e.forEach((t,r)=>{t.order=r})}function Kae(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=>Ki(i)&&i.id===t.before);return n<0?e.length:n}let r=e.findIndex(n=>Ki(n)&&n.id===t.after);return r<0?e.length:r+1}});var $M=v(cm=>{"use strict";Object.defineProperty(cm,"__esModule",{value:!0});cm.ARTIFACT_TYPES=void 0;cm.ARTIFACT_TYPES=["form","view","businessRule","app","command","chart","dashboard","genPage","bpf"]});var FM=v(xM=>{"use strict";Object.defineProperty(xM,"__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(KM=>{"use strict";Object.defineProperty(KM,"__esModule",{value:!0})});var QM=v(YM=>{"use strict";Object.defineProperty(YM,"__esModule",{value:!0})});var ZM=v(XM=>{"use strict";Object.defineProperty(XM,"__esModule",{value:!0})});var tU=v(eU=>{"use strict";Object.defineProperty(eU,"__esModule",{value:!0})});var nU=v(rU=>{"use strict";Object.defineProperty(rU,"__esModule",{value:!0})});var oU=v(iU=>{"use strict";Object.defineProperty(iU,"__esModule",{value:!0})});var sU=v(aU=>{"use strict";Object.defineProperty(aU,"__esModule",{value:!0})});var uU=v(lU=>{"use strict";Object.defineProperty(lU,"__esModule",{value:!0})});var dU=v(cU=>{"use strict";Object.defineProperty(cU,"__esModule",{value:!0})});var pU=v(fU=>{"use strict";Object.defineProperty(fU,"__esModule",{value:!0})});var hU=v(mU=>{"use strict";Object.defineProperty(mU,"__esModule",{value:!0})});var yU=v(gU=>{"use strict";Object.defineProperty(gU,"__esModule",{value:!0})});var vU=v(bU=>{"use strict";Object.defineProperty(bU,"__esModule",{value:!0})});var CU=v(wU=>{"use strict";Object.defineProperty(wU,"__esModule",{value:!0})});var AU=v(EU=>{"use strict";Object.defineProperty(EU,"__esModule",{value:!0})});var NU=v(pe=>{"use strict";var Jae=pe&&pe.__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]})),Ge=pe&&pe.__exportStar||function(e,t){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(t,r)&&Jae(t,e,r)};Object.defineProperty(pe,"__esModule",{value:!0});pe.projectConnectorOperationSchema=pe.projectConnectorOperations=pe.createMakerSdk=void 0;var Yae=LM();Object.defineProperty(pe,"createMakerSdk",{enumerable:!0,get:function(){return Yae.createMakerSdk}});Ge($M(),pe);Ge(FM(),pe);Ge(UM(),pe);Ge(qM(),pe);Ge(GM(),pe);Ge(zM(),pe);Ge(HM(),pe);Ge(JM(),pe);Ge(QM(),pe);Ge(ZM(),pe);Ge(tU(),pe);Ge(nU(),pe);Ge(oU(),pe);Ge(sU(),pe);Ge(uU(),pe);Ge(Ud(),pe);Ge(dU(),pe);Ge(pU(),pe);Ge(hU(),pe);Ge(yU(),pe);Ge(vU(),pe);Ge(CU(),pe);Ge(AU(),pe);Ge(Q(),pe);var SU=Tl();Object.defineProperty(pe,"projectConnectorOperations",{enumerable:!0,get:function(){return SU.projectConnectorOperations}});Object.defineProperty(pe,"projectConnectorOperationSchema",{enumerable:!0,get:function(){return SU.projectConnectorOperationSchema}})});var iw=v(mi=>{"use strict";var Qae=mi&&mi.__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]})),Xae=mi&&mi.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),DU=mi&&mi.__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)&&Qae(t,e,r);return Xae(t,e),t};Object.defineProperty(mi,"__esModule",{value:!0});mi.NodeFileSystemStorage=void 0;var Ct=DU(require("fs")),nr=DU(require("path")),_U=Q(),TU=Bm();async function IU(e){let t;try{t=await Ct.promises.lstat(e)}catch{return}if(t.isSymbolicLink()){try{await Ct.promises.unlink(e)}catch{await Ct.promises.rmdir(e)}return}if(!t.isDirectory()){await Ct.promises.unlink(e);return}for(let r of await Ct.promises.readdir(e))await IU(nr.join(e,r));await Ct.promises.rmdir(e)}var nw=class{constructor(t){this.root=t}getRoot(){return this.root}pathFor(t,r=!0){return this.assertWithinRoot(nr.join(this.root,...t),r)}realPathThroughNearestAncestor(t){let r=t,n=[];for(;!Ct.existsSync(r);){n.unshift(nr.basename(r));let i=nr.dirname(r);if(i===r)return nr.resolve(t);r=i}return nr.resolve(Ct.realpathSync(r),...n)}assertWithinRoot(t,r){let n=nr.resolve(this.root),i=nr.resolve(t);if(i!==n&&!i.startsWith(n+nr.sep))throw new _U.PathTraversalError(t,this.root);let o=this.realPathThroughNearestAncestor(n),a=r?this.realPathThroughNearestAncestor(i):nr.resolve(this.realPathThroughNearestAncestor(nr.dirname(i)),nr.basename(i));if(a!==o&&!a.startsWith(o+nr.sep))throw new _U.PathTraversalError(t,this.root);return i}async readText(t){let r=this.pathFor(t);if(!Ct.existsSync(r))return null;try{return await(0,TU.retryTransientIoAsync)(()=>Ct.promises.readFile(r,"utf8"))}catch(n){if(n.code==="ENOENT")return null;throw n}}async writeTextAtomic(t,r){let n=this.pathFor(t),i=nr.dirname(n);await Ct.promises.mkdir(i,{recursive:!0});let o=nr.join(i,`.${nr.basename(n)}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`);try{await Ct.promises.writeFile(o,r,"utf8"),await(0,TU.retryTransientIoAsync)(()=>Ct.promises.rename(o,n))}catch(a){try{Ct.existsSync(o)&&await Ct.promises.unlink(o)}catch{}throw a}}async deleteFile(t){let r=this.pathFor(t);Ct.existsSync(r)&&await Ct.promises.unlink(r)}async deleteByPrefix(t){await IU(this.pathFor(t,!1))}async ensureContainer(t){await Ct.promises.mkdir(this.pathFor(t),{recursive:!0})}async exists(t){return Ct.existsSync(this.pathFor(t))}};mi.NodeFileSystemStorage=nw});var OU=v(Ur=>{"use strict";var Zae=Ur&&Ur.__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]})),ese=Ur&&Ur.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),tse=Ur&&Ur.__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)&&Zae(t,e,r);return ese(t,e),t};Object.defineProperty(Ur,"__esModule",{value:!0});Ur.loadNodeTypeScript=Ur.createNodeWorkspaceStorage=Ur.NodeFileSystemStorage=void 0;var rse=iw(),nse=iw();Object.defineProperty(Ur,"NodeFileSystemStorage",{enumerable:!0,get:function(){return nse.NodeFileSystemStorage}});function ise(e){return new rse.NodeFileSystemStorage(e)}Ur.createNodeWorkspaceStorage=ise;async function ose(){return await Promise.resolve().then(()=>tse(require("typescript")))}Ur.loadNodeTypeScript=ose});var Ji={};module.exports=Br(Ji);Yi(Ji,Ae(NU()),module.exports);Yi(Ji,Ae(OU()),module.exports);+`),diagnostics:p}}});var G2={};Fi(G2,{Guid:()=>H});var H,Dn=B(()=>{"use strict";H=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 n=Math.random()*16|0,r=t=="x"?n:n&3|8;return r.toString(16)})}constructor(t,n=!1){this.guidString=t;let r=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}$");(n||r.test(t))&&(this.guid=t)}ToString(){return this.guid}}});var Q,Sr=B(()=>{"use strict";En();Q=class e{static get EmptyString(){return""}static IsTrue(t){let n=!1;return n=t&&(this.IsStrictTrue(t)||this.IsYes(t)),n}static IsStrictTrue(t){let n=!1;return t&&(n=t.toLowerCase()==="true"),n}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,n){return e.IsNullOrEmpty(t)?t:t.replace(/\{\{|\}\}|\{(\d+)\}/g,function(r,i){return r=="{{"?"{":r=="}}"?"}":n[i]})}static EndsWithString(t,n){return t.indexOf(n,t.length-n.length)!==-1}static IsBlankString(t){return t.replace(/\s/g,"").length==0}static EscapeXml(t,n){let r=t;return this.IsNullOrEmpty(r)||(r=r.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">"),n&&(r=r.replace(/"/g,""").replace(/'/g,"'"))),r}static EscapeDomId(t){return t.replace(".","\\.")}static ToSnakeCase(t){let n=e.EmptyString;for(let r=0;r<t.length;r++)r!==0&&t[r]==t[r].toUpperCase()&&(n+="-"),n+=t[r].toLowerCase();return n}static GetSnakeCaseMarkup(t,n){let r="<"+this.ToSnakeCase(t);if(!F.IsNullOrUndefined(n))for(let i of n.getKeys())r+=" "+this.ToSnakeCase(i)+'="'+n.getValue(i)+'"';return r+">"}static StripBraces(t){return t&&t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"?t.substr(1,t.length-2):t}static AddBraces(t){return F.IsNullOrUndefined(t)||t.charAt(0)==="{"||t.charAt(t.length-1)==="}"?t:`{${t}}`}static GuidStringEquals(t,n){return t===n?!0:!t||!n?!1:e.StripBraces(t).toUpperCase()===e.StripBraces(n).toUpperCase()}static AddBracesToArrayValues(t){return t.length>0?t.map(r=>(r.charAt(0)!=="{"&&(r="{"+r),r.charAt(r.length-1)!=="}"&&(r=r+"}"),r)):t}static StripBracesOnArrayValues(t){return t.length>0?t.map(r=>{let i;return r.charAt(0)==="{"&&(i=r.substr(1,r.length-1)),r.charAt(r.length-1)==="}"&&(i=i.substr(0,r.length-2)),i}):t}}});var j2={};Fi(j2,{ScriptUtilities:()=>F});var F,En=B(()=>{"use strict";Dn();Sr();F=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:H.EmptyGuid.ToString()===t.ToString()}static IsNullOrUndefinedNested(t,n){return n.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,n){let r=t.getNamedItem(n);return e.IsNullOrUndefined(r)?null:r.value}static getBooleanValue(t,n){let r=e.getNamedItemValue(t,n);return e.IsNullOrUndefined(r)?null:Q.IsTrue(r)}static getNumericValue(t){return e.IsNullOrUndefined(t)?null:parseInt(t)}static getAllUniqueTagNames(t){let n=new Set;return e.getAllUniqueTagNamesHelper(t,n),n}static getAllUniqueTagNamesHelper(t,n){if(t.nodeType===Node.ELEMENT_NODE&&(n.add(t.tagName),t.hasChildNodes()))for(let r=0;r<t.children.length;r++)this.getAllUniqueTagNamesHelper(t.children.item(r),n)}}});var _0,I0,yl,T0,yC,O0,bC=B(()=>{"use strict";(function(e){e[e.FormElementNodeChange=0]="FormElementNodeChange",e[e.FormElementAttributeChange=1]="FormElementAttributeChange"})(_0||(_0={}));I0=class{type;targetNode;constructor(t,n){this.type=t,this.targetNode=n}},yl=class extends I0{key;oldValue;newValue;constructor(t,n,r,i){super(_0.FormElementNodeChange,t),this.key=n,this.oldValue=r,this.newValue=i}apply(){this.targetNode.replaceObjectPropertyValue(this.key,this.newValue)}revert(){this.targetNode.replaceObjectPropertyValue(this.key,this.oldValue)}},T0=class extends I0{property;oldValue;newValue;constructor(t,n,r,i){super(_0.FormElementAttributeChange,t),this.property=n,this.oldValue=r,this.newValue=i}apply(){this.targetNode.replaceAttributeValue(this.property,this.newValue)}revert(){this.targetNode.replaceAttributeValue(this.property,this.oldValue)}},yC=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()})}},O0=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 yC(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 W2={};Fi(W2,{ChartGridMode:()=>Zi,ColumnLayoutWidths:()=>Bse,ComponentCategory:()=>P0,ComponentType:()=>vC,ControlLayoutTypes:()=>_C,DisplayConditionsInfo:()=>Use,ElementNames:()=>D,ElementProperties:()=>A,ElementType:()=>EC,EntityAttributeProperty:()=>AC,EventType:()=>kp,FormActivationState:()=>NC,FormCanvasServiceScope:()=>Zse,FormDesignerSideBarTab:()=>wC,FormPresentation:()=>CC,FormState:()=>D0,FormType:()=>Pn,HeaderDensityType:()=>su,LookUpTable:()=>fa,MORE_TAB_PREFIX:()=>Gse,NavBarChildElementType:()=>SC,PREVIEW_ID_HEADER_FLYOUT:()=>Hse,PREVIEW_ID_HEADER_OVERFLOW_BUTTON:()=>Jse,PREVIEW_ID_NAVIGATION_AREA:()=>Wse,PREVIEW_ID_QUICKCREATE_ROOT:()=>Qse,PREVIEW_ID_TAB:()=>Yse,PREVIEW_ID_TAB_LIST:()=>Kse,PREVIEW_ID_TAB_PANEL:()=>zse,PropertyModelKeys:()=>OC,PropertyModelSectionKeys:()=>Vse,RELATED_TAB_ID:()=>DC,RELATED_TAB_PREFIX:()=>jse,SectionDefaultProperties:()=>qse,SectionLayoutTypes:()=>Vt,TabContentType:()=>IC,TabDefaultProperties:()=>uu,TabLayoutTypes:()=>Bt,TelemetryPropertyNames:()=>Xse,UnboundControlPropertyKeys:()=>TC,compositeAddressFields:()=>Fse,compositeFieldNames:()=>Li,compositeFields:()=>xse});var Pn,vC,wC,D,A,EC,Li,xse,Fse,AC,fa,D0,su,CC,Use,SC,NC,Bt,qse,uu,Vt,_C,IC,Bse,TC,OC,Vse,kp,Zi,DC,Gse,jse,Wse,zse,Hse,Kse,Jse,Yse,Qse,Xse,P0,Zse,Re=B(()=>{"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"})(Pn||(Pn={}));(function(e){e[e.Form=0]="Form",e[e.Dialog=1]="Dialog"})(vC||(vC={}));(function(e){e[e.Components=0]="Components",e[e.Properties=1]="Properties",e[e.Relationship=2]="Relationship",e[e.BusinessRules=3]="BusinessRules"})(wC||(wC={}));(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"})(D||(D={}));A={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"})(EC||(EC={}));Li={fullname:"fullname",yomifullname:"yomifullname",address1_composite:"address1_composite",address2_composite:"address2_composite",address3_composite:"address3_composite",billto:"billto_composite",shipto:"shipto_composite"},xse=[Li.fullname,Li.yomifullname,Li.address1_composite,Li.address2_composite,Li.address3_composite,Li.billto,Li.shipto],Fse=[Li.address1_composite,Li.address2_composite,Li.address3_composite,Li.billto,Li.shipto];(function(e){e[e.IsValidForForm=0]="IsValidForForm",e[e.IsValidForCreate=1]="IsValidForCreate"})(AC||(AC={}));(function(e){e[e.DependencyFieldTable=0]="DependencyFieldTable",e[e.LockedFieldTable=1]="LockedFieldTable"})(fa||(fa={}));(function(e){e[e.Published=0]="Published",e[e.Draft=1]="Draft",e[e.New=2]="New",e[e.SaveAs=3]="SaveAs"})(D0||(D0={}));(function(e){e.Low="Low",e.HighReadOnlyValues="HighReadOnlyValues",e.HighWithControls="HighWithControls"})(su||(su={}));(function(e){e[e.ClassicForm=0]="ClassicForm",e[e.AirForm=1]="AirForm",e[e.ConvertedICForm=2]="ConvertedICForm"})(CC||(CC={}));Use={TopOrderFormId:"topOrderFormId",NextDisplayOrder:"nextDisplayOrder"};(function(e){e[e.NavBarRelationShipItem=0]="NavBarRelationShipItem",e[e.NavBarItem=1]="NavBarItem"})(SC||(SC={}));(function(e){e[e.InActive=0]="InActive",e[e.Active=1]="Active"})(NC||(NC={}));(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"})(Bt||(Bt={}));qse={ShowLabel:"false",LockLevel:"0",IsUserDefined:"0",LabelWidth:"115",columns:"1",ShowBar:"false",Layout:"varwidth",namePrefix:"_section_"},uu={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"})(Vt||(Vt={}));(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"})(_C||(_C={}));(function(e){e.cardSections="cardSections",e.singleComponent="singleComponent",e.default="default",e.expandAvailableSpace="expandAvailableSpace"})(IC||(IC={}));Bse={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"})(TC||(TC={}));(function(e){e.entityName="entityName",e.formName="formName",e.formDisplayName="formDisplayName",e.description="description",e.maxWidth="maxWidth",e.showNavigation="showNavigation",e.showImageCheck="showImageCheck",e.downloadFormXml="downloadFormXml",e.downloadRawFormXml="downloadRawFormXml",e.expandTab="expandTab",e.singleComponent="singleComponent",e.label="label",e.name="name",e.hiddenByDefault="hiddenByDefault",e.hideForPhone="hideForPhone",e.tabLayout="tabLayout",e.column1Width="column1Width",e.column2Width="column2Width",e.column3Width="column3Width",e.hideLabel="hideLabel",e.lockElement="lockElement",e.sectionLayout="sectionLayout",e.labelWidth="labelWidth",e.fieldLabelAlignment="fieldLabelAlignment",e.fieldLabelPosition="fieldLabelPosition",e.cellWidth="cellWidth",e.fieldHeight="fieldHeight",e.cellHeight="cellHeight",e.showLine="showLine",e.readonly="readonly",e.required="required",e.maxLength="maxLength",e.isTitle="isTitle",e.minValue="minValue",e.maxValue="maxValue",e.precision="precision",e.autoExpand="autoExpand",e.highDensityEnabled="highDensityEnabled",e.hideExtendedHeader="hideExtendedHeader",e.defaultViewProperty="defaultViewProperty",e.defaultChartProperty="defaultChartProperty",e.teamTemplateProperty="teamTemplateProperty",e.datasourceProperty="datasourceProperty",e.eventType="eventType",e.addEvent="addEvent",e.cellOnChange="cellOnChange",e.cellOnChangeEventDependencies="cellOnChangeEventDependencies",e.cellOnChangeHandlers="cellOnChangeHandlers",e.gridOnChange="gridOnChange",e.gridOnChangeEventDependencies="gridOnChangeEventDependencies",e.gridOnChangeHandlers="gridOnChangeHandlers",e.gridOnChangeTargetField="gridOnChangeTargetField",e.gridOnRecordSelect="gridOnRecordSelect",e.gridOnRecordSelectEventDependencies="gridOnRecordSelectEventDependencies",e.gridOnRecordSelectHandlers="gridOnRecordSelectHandlers",e.cellOnReadyStateEventDependencies="cellOnReadyStateEventDependencies",e.cellOnReadyStateHandlers="cellOnReadyStateEventHandlers",e.tabOnChange="tabOnChange",e.tabOnChangeEventDependencies="tabOnChangeEventDependencies",e.tabOnChangeHandlers="tabOnChangeHandlers",e.formOnLoad="formOnLoad",e.formOnLoadEventDependencies="formOnLoadEventDependencies",e.formOnLoadHandlers="formOnLoadHandlers",e.formOnSave="formOnSave",e.formOnSaveDependencies="formOnSaveDependencies",e.formOnSaveHandlers="formOnSaveHandlers",e.gridOnSave="gridOnSave",e.gridOnSaveDependencies="gridOnSaveDependencies",e.gridOnSaveHandlers="gridOnSaveHandlers",e.formHasNoLibraries="formHasNoLibraries",e.hideHeaderCommandBar="hideHeaderCommandBar",e.hideHeaderBody="hideHeaderBody",e.hideHeaderTabNavigator="hideHeaderTabNavigator",e.hideFooter="hideFooter",e.scrollingDropdown="scrollingDropdown",e.displayBorder="displayBorder",e.crossScripting="crossScripting",e.passParams="passParams",e.webResourceCustomParamData="webResourceCustomParameterData",e.webResourceAltText="webResourceAltText",e.verticalAlignment="verticalAlignment",e.horizontalAlignment="horizontalAlignment",e.specificSize="specificSize",e.urlProperty="urlProperty",e.enableViewPicker="enableViewPicker",e.enableChartPicker="enableChartPicker",e.chartGridMode="chartGridMode",e.relatedRecords="relatedRecords",e.hideSearchBox="hideSearchBox",e.showAllViews="showAllViews",e.availableViewsProperty="availableViewsProperty",e.recordsPerPage="recordsPerPage",e.businessRulePill="business-rule-pill-",e.addBusinessRule="addBusinessRule",e.rowHeight="rowHeight",e.refPanelSectionTabs="refPanelSectionTabs",e.editCanvasAppProperty="editCanvasAppProperty"})(OC||(OC={}));Vse={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"})(kp||(kp={}));(function(e){e.All="All",e.Chart="Chart",e.Grid="Grid"})(Zi||(Zi={}));DC="tab_related3b554255-7717-4d17-bb7f-9936fb1e75ca",Gse="more_tab_",jse="related_tab_",Wse="preview_id_navigation_area",zse="tab-section",Hse="headerFieldsFlyout",Kse="tablist",Jse="header_overflowButton",Yse="tab",Qse="quickCreateRoot",Xse={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"})(P0||(P0={}));Zse="CellCanvasServiceScope"});var z2={};Fi(z2,{Attribute:()=>R0,FormElementNode:()=>Se});var R0,Se,Jn=B(()=>{"use strict";En();Sr();bC();Re();Dn();R0=class{key;value;constructor(t,n){this.key=t,this.value=n}},Se=class e{nodeName;properties;childrenNodes;parentNode;nodeId;isTransient;constructor(t,n){this.nodeName=t,this.properties=[],this.childrenNodes=[],this.parentNode=n,this.isTransient=!1,this.nodeId=`nodeId-${H.NewGuid()}`}getProperty(t){for(let n of this.properties)if(n.key===t)return n.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,n){this.properties.find(r=>r===t)&&(t.value=n)}replaceObjectPropertyValue(t,n){this[t]=n}getAllChildren(){return this.childrenNodes}getParentNode(){return this.parentNode}visit(t){let n=!1;if(t){n=!!t(this);let r=this.childrenNodes;if(!n&&r)for(let i=0;!n&&i<r.length;i++)n=r[i].visit(t)}return n}findAll(t){let n=[];return t&&this.visit(r=>{t(r)&&n.push(r)}),n}findFirst(t){let n=null;return t&&this.visit(r=>{if(t(r))return n=r,!0}),n}raiseMetadataChange(t){let n=this.getAncestor(D.form);n&&n.raiseMetadataChange(t)}trackPropertyAddition(t,n){this.trackPropertyCollectionChange(()=>{this.properties.push(new R0(t,n))})}trackPropertyDeletion(t){this.trackPropertyCollectionChange(()=>{let n=this.properties.findIndex(r=>r.key===t);n>-1&&this.properties.splice(n,1)})}trackPropertyCollectionChange(t){let n=this.changeTracker();if(n&&n.isTracking){let r=this.properties.slice();t(),n.addChange(new yl(this,"properties",r,this.properties.slice()))}else t()}trackChildrenCollectionChange(t){let n=this.changeTracker();if(n&&n.isTracking){let r=this.childrenNodes.slice();t(),n.addChange(new yl(this,"childrenNodes",r,this.childrenNodes.slice()))}else t()}trackParentNodeChange(t){let n=this.changeTracker();if(n&&n.isTracking){let r=this.parentNode;if(t(),r===this.parentNode)return;n.addChange(new yl(this,"parentNode",r,this.parentNode))}else t()}trackAttributeValueChange(t,n){let r=this.changeTracker();if(r&&r.isTracking){let i=t.value;if(i===n)return;t.value=n,r.addChange(new T0(this,t,i,n))}else t.value=n}trackObjectPropertyChange(t,n){let r=this.changeTracker();if(r&&r.isTracking){let i=this[t];if(i===n)return;this[t]=n,r.addChange(new yl(this,t,i,n))}else this[t]=n}setProperty(t,n){if(!t)throw new Error("Invalid property key");let r=this.properties.find(i=>i.key===t);r?this.trackAttributeValueChange(r,n):this.addProperty(t,n)}addProperty(t,n){if(!t)throw new Error("Invalid property key");this.trackPropertyAddition(t,n)}removeProperty(t){this.trackPropertyDeletion(t)}addChild(t){t.trackParentNodeChange(()=>{t.parentNode=this}),this.trackChildrenCollectionChange(()=>{this.childrenNodes.push(t)})}insertChildAtIndex(t,n){F.IsNullOrUndefined(t)||(t.trackParentNodeChange(()=>{t.parentNode=this}),this.trackChildrenCollectionChange(()=>{this.childrenNodes.splice(n,0,t)}))}moveChild(t,n){let r=this.childrenNodes.indexOf(t);if(r<0)return!1;let i=Math.min(Math.max(0,r+n),this.childrenNodes.length-1);return r!==i&&this.trackChildrenCollectionChange(()=>{this.childrenNodes.splice(i,0,this.childrenNodes.splice(r,1)[0])}),!0}getChildren(t){let n=[];for(let r of this.childrenNodes)r.nodeName===t&&n.push(r);return n}getFirstChild(t){for(let n of this.childrenNodes)if(n.nodeName===t)return n;return null}getAllGrandChildren(t){let n=this.getChildren(t),r=null;return n.length===0?new Array:(r=n[0],r.childrenNodes)}deleteChild(t){if(F.IsNullOrUndefined(t))return-1;for(let n=0;n<this.childrenNodes.length;n++)if(this.childrenNodes[n]===t)return this.trackChildrenCollectionChange(()=>{this.childrenNodes.splice(n,1)}),n;return-1}deleteAllChildren(){this.trackChildrenCollectionChange(()=>{this.childrenNodes=[]})}getParent(){return this.parentNode}getParentType(){return this.parentNode?this.parentNode.nodeName:Q.EmptyString}updateChild(t,n){let r=this.childrenNodes.indexOf(t);return r>-1?(n.trackParentNodeChange(()=>{n.parentNode=this}),this.trackChildrenCollectionChange(()=>{this.childrenNodes.splice(r,1,n)}),!0):!1}getAncestor(t){let n=this.getParent(),r=this.getParentType();for(;n;){if(r===t)return n;r=n.getParentType(),n=n.getParent()}return null}deleteFirstGrandChildOfName(t,n){return this.getChildren(t)[0].deleteChild(n)}deleteChildren(t,n){n=F.IsNullOrUndefined(n)?this.childrenNodes.length:n,this.trackChildrenCollectionChange(()=>{this.childrenNodes.splice(t,n)})}deleteGrandChildren(t,n,r){this.getChildren(t)[0].deleteChildren(n,r)}addGrandChild(t,n){let r=this.getChildren(t),i=null;r.length===0?(i=new e(t,this),this.addChild(i)):i=r[0],i.addChild(n)}addGrandChildAtIndex(t,n,r){let i=this.getChildren(t),o=null;i.length===0?(o=new e(t,this),this.addChild(o)):o=i[0],o.insertChildAtIndex(n,r)}GetPropertyByParameter(t){return this.getProperty(t)}getSemanticParent(){switch(this.getNodeName()){case D.formCell:let t=this.getAncestor(D.formSection);return t||(t=this.getAncestor(D.formHeader),t)||(t=this.getAncestor(D.formFooter),t)?t:null;case D.formSection:return this.getAncestor(D.formTab);case D.formTab:return this.getAncestor(D.form);default:return null}}isDirty(){return this.visit(t=>t.isInChangeSet())}isInChangeSet(){return this.changeTracker().getChangeSets().some(n=>n.changeSet.some(r=>r.targetNode.getNodeId()===this.getNodeId()))}changeTracker(){let t=this.getAncestor(D.form);return t?t.changeTracker():null}}});var H2={};Fi(H2,{ControlClassId:()=>k,ControlNamePrefixes:()=>k0,getControlDisplayNames:()=>eue});function eue(e){return{[k.AccessPrivilegeControl]:e("controls.controlNames.accessPrivilege"),[k.AccessTeamTablePickerControl]:e("controls.controlNames.accessTeamTablePicker"),[k.ACIControl]:e("controls.controlNames.aci"),[k.ActivitiesContainerControl]:e("controls.controlNames.activitiesContainer"),[k.ActivitiesWallControl]:e("controls.controlNames.activitiesWall"),[k.AppliedFiltersControl]:e("controls.controlNames.appliedFilters"),[k.ArticleContentControl]:e("controls.controlNames.articleContent"),[k.BooleanControl]:e("controls.controlNames.twoOption"),[k.ButtonControl]:e("controls.controlNames.button"),[k.CheckboxControl]:e("controls.controlNames.checkbox"),[k.CompositionLinkControl]:e("controls.controlNames.compositionLink"),[k.ConnectionControl]:e("controls.controlNames.connection"),[k.ConnectionRoleObjectTypeListControl]:e("controls.controlNames.connectionRoleObjectTypeList"),[k.CoverageChoiceControl]:e("controls.controlNames.coverageChoice"),[k.DashboardControl]:e("controls.controlNames.dashboard"),[k.DynamicPropertyListControl]:e("controls.controlNames.dynamicPropertyList"),[k.EditFilterControl]:e("controls.controlNames.editFilter"),[k.ErrorStatusControl]:e("controls.controlNames.errorStatus"),[k.GlobalFilterControl]:e("controls.controlNames.globalFilter"),[k.HiddenInputControl]:e("controls.controlNames.hiddenInput"),[k.KBViewerControl]:e("controls.controlNames.kbViewer"),[k.LabelControl]:e("controls.controlNames.label"),[k.MailMergeLanguagePickerControl]:e("controls.controlNames.mailMergeLanguagePicker"),[k.MapLinkControl]:e("controls.controlNames.mapLink"),[k.OrgInsightsControl]:e("controls.controlNames.orgInsights"),[k.ChoiceLookupControl]:e("controls.controlNames.choiceLookup"),[k.PowerBIControl]:e("controls.controlNames.powerBI"),[k.ProcessControl]:e("controls.controlNames.process"),[k.RelatedInformationControl]:e("controls.controlNames.relatedInformation"),[k.RelationshipRoleChoiceControl]:e("controls.controlNames.relationshipRoleChoice"),[k.ReportControl]:e("controls.controlNames.report"),[k.StreamsControl]:e("controls.controlNames.streams"),[k.WebResourceSilverlightControl]:e("controls.controlNames.webResourceSilverlight"),[k.CurrencyControl]:e("controls.controlNames.currency"),[k.DateTimeControl]:e("controls.controlNames.dateAndTime"),[k.DecimalControl]:e("controls.controlNames.decimal"),[k.DurationControl]:e("controls.controlNames.duration"),[k.EmailAddressControl]:e("controls.controlNames.email"),[k.FileControl]:e("controls.controlNames.file"),[k.FloatingNumberControl]:e("controls.controlNames.floatingNumber"),[k.IframeControl]:e("controls.controlNames.iframe"),[k.ImageControl]:e("controls.controlNames.image"),[k.LookupControl]:e("controls.controlNames.lookup"),[k.MapsControl]:e("controls.controlNames.maps"),[k.PhoneNumberControl]:e("controls.controlNames.phoneNumber"),[k.ChoiceControl]:e("controls.controlNames.choice"),[k.QuickViewControl]:e("controls.controlNames.quickView"),[k.QuickFormControl]:e("controls.controlNames.quickForm"),[k.CustomControl]:e("controls.controlNames.customControl"),[k.SearchWidgetControl]:e("controls.controlNames.searchWidget"),[k.SocialInsightsControl]:e("controls.controlNames.socialInsights"),[k.SubgridControl]:e("controls.controlNames.subgrid"),[k.TextAreaControl]:e("controls.controlNames.textArea"),[k.TextboxControl]:e("controls.controlNames.textBox"),[k.TickerControl]:e("controls.controlNames.ticker"),[k.UrlControl]:e("controls.controlNames.url"),[k.WebResourceHTMLControl]:e("controls.controlNames.webResourceHTML"),[k.WebResourceImageControl]:e("controls.controlNames.webResourceImage"),[k.IntegerControl]:e("controls.controlNames.integer"),[k.TimerControl]:e("controls.controlNames.timer"),[k.TimelineControl]:e("controls.controlNames.timeline"),[k.EmailBodyControl]:e("controls.controlNames.emailBody"),[k.PartyListControl]:e("controls.controlNames.partyList"),[k.TimezoneControl]:e("controls.controlNames.timezone"),[k.LanguageControl]:e("controls.controlNames.language"),[k.ChoiceStatusControl]:e("controls.controlNames.choiceStatus"),[k.ChoicesControl]:e("controls.controlNames.choices"),[k.RegardingControl]:e("controls.controlNames.regarding"),[k.EmailEngagementActionsControl]:e("controls.controlNames.emailEngagementActions"),[k.EmailRecipientActivityControl]:e("controls.controlNames.emailRecipientActivity"),[k.ReferencePanelSearchWidgetControl]:e("controls.controlNames.referencePanelSearchWidget"),[k.ReferencePanelQuickViewControl]:e("controls.controlNames.referencePanelQuickView"),[k.ReferencePanelSubgridControl]:e("controls.controlNames.referencePanelSubgrid"),[k.KBEditorControl]:e("controls.controlNames.KBEditor"),[k.LinkControl]:e("controls.controlNames.link")}}var k,k0,bl=B(()=>{"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"})(k||(k={}));k0={[k.WebResourceHTMLControl]:"WebResource",[k.WebResourceImageControl]:"WebResource",[k.IframeControl]:"IFRAME",[k.SearchWidgetControl]:"Search widget",[k.SubgridControl]:"Subgrid",[k.TimelineControl]:"Timeline",[k.QuickViewControl]:"QuickviewControl"}});var vl=C((lOe,J2)=>{var $p=new Proxy(function(){return $p},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:$p},apply:function(){return $p},construct:function(){return{}}}),K2=function(){return $p};Object.setPrototypeOf(K2,$p);J2.exports=K2});var Vr,us,Y2,Q2,td=B(()=>{"use strict";Vr="cds-designer-models",us="FormCustomControl",Y2="FormCell",Q2="Form"});var wl,PC=B(()=>{"use strict";bp();Re();wl=class e{static lockedFieldCount=new qr;static dependencyFieldCount=new qr;static getNecessaryLookUpTable(t){switch(t){case fa.DependencyFieldTable:return e.dependencyFieldCount;case fa.LockedFieldTable:return e.lockedFieldCount}}static initCanvasLockedFieldLookUp(t){switch(t){case fa.DependencyFieldTable:e.dependencyFieldCount=new qr;case fa.LockedFieldTable:e.lockedFieldCount=new qr}}}});var $0,X2=B(()=>{"use strict";Dn();En();Re();Jn();$0=class extends Se{constructor(t){super(D.controlDescription,t)}get forControl(){let t=this.getProperty(A.ForControl);return F.IsNullOrUndefined(t)?null:(t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"&&(t=t.substr(1,t.length-2)),new H(t))}set forControl(t){this.setProperty(A.ForControl,`{${t.ToString()}}`)}get customControls(){return this.getChildren(D.customControl)}set customControls(t){this.deleteAllChildren();for(let n of t)this.addChild(n)}get DefaultControlClassId(){for(let t of this.customControls)if(!F.IsNullOrUndefined(t.id))return t.id;return null}get DefaultCustomControl(){for(let t of this.customControls)if(!F.IsNullOrUndefined(t.id))return t;return null}get DefaultCustomControls(){let t=[];for(let n of this.customControls)F.IsNullOrUndefined(n.id)||t.push(n);return t}async toJSON(t){let n=await this.getCustomControlsJSON(t);return n?{UniqueId:this.forControl.guidString,CustomControls:n,VersionNumber:0,OverallVersionNumber:0}:null}async getCustomControlsJSON(t){if(this.customControls){let n=[];for(let r of this.customControls){let i=await r.toJSON(t);i&&n.push(i)}return n}return null}}});function ls(){return pa||(pa=window._makerConfig,pa&&window?.location?.search?.indexOf("useProductionConfig")>-1&&(pa={...pa,region:"prod",graphQLEndpoint:"https://graph.make.powerapps.com/"}),pa?.region==="prod"&&(pa={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/"}}},...pa}),pa||{aadClientId:"a8f7a65c-f5ba-4859-b2d6-df772c264e9d",location:"cus",region:"test",publicPath:"/",graphQLEndpoint:"https://graph.make.test.powerapps.com/"})}var pa,L0=B(()=>{"use strict";});function Z2(e,t,n){if(!e)return M0.has(e)||(window._ppux?.log?.("PPUX/Geo/NonExistent",{eventType:"Trace",team:"Shell",severity:"Error",errorCode:"GeoIsEmpty"}),M0.add("")),!1;if(e){if(e=e.toLowerCase(),M0.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:n}}),M0.add(e),!1}return!0}function tue(e){return Z2(e,RC,"Location dictionary")?RC[e.toLowerCase()]:"us"}function nue(){let e=ls().location.toLowerCase();return Z2(e,RC,"Current location dictionary")?e:"us"}var M0,RC,AOe,e1=B(()=>{"use strict";L0();M0=new Set,RC={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"};AOe=tue(nue())});var ue,SOe,t1=B(()=>{"use strict";ue={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"},SOe={[ue.USWest]:{geoName:"us",regionShortName:"wus"},[ue.USCentral]:{geoName:"us",regionShortName:"cus"},[ue.USEast]:{geoName:"us",regionShortName:"eus"},[ue.USEast2]:{geoName:"us",regionShortName:"eus2"},[ue.USWestCentral]:{geoName:"us",regionShortName:"wcus"},[ue.USWest2]:{geoName:"us",regionShortName:"wus2"},[ue.USSouthCentral]:{geoName:"br",regionShortName:"scus"},[ue.BrazilSouth]:{geoName:"br",regionShortName:"sbr"},[ue.UKSouth]:{geoName:"uk",regionShortName:"suk"},[ue.UKWest]:{geoName:"uk",regionShortName:"wuk"},[ue.JapanEast]:{geoName:"jp",regionShortName:"ejp"},[ue.JapanWest]:{geoName:"jp",regionShortName:"wjp"},[ue.IndiaCentral]:{geoName:"in",regionShortName:"cin"},[ue.IndiaSouth]:{geoName:"in",regionShortName:"sin"},[ue.ItalyNorth]:{geoName:"it",regionShortName:"nit"},[ue.GermanyWestCentral]:{geoName:"de",regionShortName:"wcde"},[ue.GermanyNorth]:{geoName:"de",regionShortName:"nde"},[ue.EuropeNorth]:{geoName:"eu",regionShortName:"neu"},[ue.EuropeWest]:{geoName:"eu",regionShortName:"weu"},[ue.AustraliaEast]:{geoName:"au",regionShortName:"eau"},[ue.AustraliaSouthEast]:{geoName:"au",regionShortName:"seau"},[ue.AsiaSouthEast]:{geoName:"as",regionShortName:"seas"},[ue.AsiaEast]:{geoName:"as",regionShortName:"eas"},[ue.CanadaCentral]:{geoName:"ca",regionShortName:"cca"},[ue.CanadaEast]:{geoName:"ca",regionShortName:"eca"},[ue.SouthAfricaNorth]:{geoName:"za",regionShortName:"nza"},[ue.SouthAfricaWest]:{geoName:"za",regionShortName:"wza"},[ue.FranceCentral]:{geoName:"fr",regionShortName:"cfr"},[ue.FranceSouth]:{geoName:"fr",regionShortName:"sfr"},[ue.UAENorth]:{geoName:"ae",regionShortName:"nae"},[ue.UAECentral]:{geoName:"ae",regionShortName:"cae"},[ue.SwedenCentral]:{geoName:"se",regionShortName:"cse"},[ue.SwitzerlandNorth]:{geoName:"ch",regionShortName:"nch"},[ue.SwitzerlandWest]:{geoName:"ch",regionShortName:"wch"},[ue.NorwayEast]:{geoName:"no",regionShortName:"eno"},[ue.NorwayWest]:{geoName:"no",regionShortName:"wno"},[ue.KoreaCentral]:{geoName:"kr",regionShortName:"ckr"},[ue.KoreaSouth]:{geoName:"kr",regionShortName:"skr"},[ue.SingaporeSouthEast]:{geoName:"sg",regionShortName:"seas"},[ue.PolandCentral]:{geoName:"pl",regionShortName:"cpl"},[ue.QatarCentral]:{geoName:"qa",regionShortName:"cqa"},[ue.NewZealandNorth]:{geoName:"nz",regionShortName:"nnz"},[ue.GovernmentUSTexas]:{geoName:"us",regionShortName:"ugtx"},[ue.GovernmentUSVirginia]:{geoName:"us",regionShortName:"ugva"},[ue.GovernmentUSDodCentral]:{regionShortName:"udc"},[ue.GovernmentUSDodEast]:{regionShortName:"ude"},[ue.ChinaEast]:{regionShortName:"cne"},[ue.ChinaEast2]:{regionShortName:"cne2"},[ue.ChinaEast3]:{regionShortName:"cne3"},[ue.ChinaNorth]:{regionShortName:"cnn"},[ue.ChinaNorth2]:{regionShortName:"cnn2"},[ue.ChinaNorth3]:{regionShortName:"cnn3"},[ue.UssecEast]:{geoName:"us",regionShortName:"erx"},[ue.UssecWest]:{geoName:"us",regionShortName:"wrx"},[ue.UsnatEast]:{geoName:"us",regionShortName:"eex"},[ue.UsnatWest]:{geoName:"us",regionShortName:"wex"}}});var n1=B(()=>{"use strict";L0();});var Lp=B(()=>{"use strict";L0();e1();t1();n1();});function Mp(e,t){return r1?r1.isOverridden(e,t):{overridden:!1}}var r1,xp=B(()=>{"use strict";});var kC=B(()=>{"use strict";Lp();xp();});function rue(e,t){let{region:n}=ls();return()=>{let r=e.settings[t];if(r.allowOverrides){let s=Mp(e.packageName,t);if(s.overridden)return typeof s.value=="string"?iue(s.value):s.value}let o=r.values,a=process.env.SETTINGS_FALLBACK_REGION?.[n];return o[n]!==void 0?o[n]:a&&o[a]!==void 0?o[a]:o.default}}function iue(e){return isNaN(Number(e))?e==="true"?!0:e==="false"?!1:e:Number(e)}function oue(e){let t=e.packageName;if(x0.has(t)){let n=`settings has already been created for this package ${t}`;throw console.error(n),new Error(n)}if(Object.keys(e.settings).some(n=>LC(t,n))){let n=`error parsing settings config for package ${t}, a feature gate with the same name exists`;throw console.error(n),new Error(n)}Object.keys(e.settings).forEach(n=>{if(Object.keys(e.settings[n].values).filter(i=>i!=="default").some(i=>!U0(i))){let i=`error parsing settings config for package ${t}, setting ${n} has invalid region`;throw console.error(i),new Error(i)}})}function Fp(e){oue(e);let t={};return Object.keys(e.settings).forEach(n=>{t[n]={enumerable:!0,get:rue(e,n)}}),x0.set(e.packageName,e),Object.defineProperties({},t)}function $C(e,t){return x0.has(e)?!!x0.get(e).settings[t]:!1}var x0,F0=B(()=>{"use strict";Lp();xp();MC();Up();x0=new Map});function i1(e,t){let{region:n}=ls();return()=>{let r=Mp(e.packageName,t);if(r.overridden)return r.value.toString()==="true";let i=e.features[t].enabledFor,o=process.env.SETTINGS_FALLBACK_REGION?.[n];return i[n]!==void 0?!!i[n]:o&&i[o]!==void 0?!!i[o]:!1}}function aue(e){let t=e.packageName;if(q0.has(t)){let n="feature gates has already been created for this package";throw console.error(n),new Error(n)}if(Object.keys(e.features).some(n=>$C(t,n))){let n=`error parsing feature gates config for package ${t}, a setting with the same name exists`;throw console.error(n),new Error(n)}Object.keys(e.features).forEach(n=>{if(Object.keys(e.features[n].enabledFor).some(i=>!U0(i))){let i=`error parsing feature gates config for package ${t}, feature ${n} has invalid region`;throw console.error(i),new Error(i)}})}function xC(e){aue(e);let t={};Object.keys(e.features).forEach(i=>{t[i]={enumerable:!0,configurable:!0,get:i1(e,i)}});let n={},r=new Set;return t.dangerouslySet={enumerable:!1,value:(i,o)=>{r.add(i),Object.defineProperty(n,i,{enumerable:!0,configurable:!0,value:o})}},t.dangerouslyReset={enumerable:!1,value:()=>{let i={};r.forEach(o=>{i[o.toString()]={enumerable:!0,configurable:!0,get:i1(e,o.toString())}}),Object.defineProperties(n,i),r.clear()}},q0.set(e.packageName,e),Object.defineProperties(n,t)}function LC(e,t){return q0.has(e)?!!q0.get(e).features[t]:!1}var q0,MC=B(()=>{"use strict";Lp();Up();xp();F0();q0=new Map});var a1=C((JOe,o1)=>{"use strict";o1.exports=function(t,n){if(n=n.split(":")[0],t=+t,!t)return!1;switch(n){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 l1=C(FC=>{"use strict";var sue=Object.prototype.hasOwnProperty,uue;function s1(e){try{return decodeURIComponent(e.replace(/\+/g," "))}catch{return null}}function u1(e){try{return encodeURIComponent(e)}catch{return null}}function lue(e){for(var t=/([^=?#&]+)=?([^&]*)/g,n={},r;r=t.exec(e);){var i=s1(r[1]),o=s1(r[2]);i===null||o===null||i in n||(n[i]=o)}return n}function cue(e,t){t=t||"";var n=[],r,i;typeof t!="string"&&(t="?");for(i in e)if(sue.call(e,i)){if(r=e[i],!r&&(r===null||r===uue||isNaN(r))&&(r=""),i=u1(i),r=u1(r),i===null||r===null)continue;n.push(i+"="+r)}return n.length?t+n.join("&"):""}FC.stringify=cue;FC.parse=lue});var BC=C((QOe,h1)=>{"use strict";var d1=a1(),B0=l1(),f1=/[\n\r\t]/g,due=/^[A-Za-z][A-Za-z0-9+-.]*:\/\//,fue=/^([a-z][a-z0-9.+-]*:)?(\/\/)?([\\/]+)?([\S\s]*)/i,pue=/^[a-zA-Z]:/,mue=/^[\x00-\x20\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]+/;function qC(e){return(e||"").toString().replace(mue,"")}var UC=[["#","hash"],["?","query"],function(t,n){return ma(n.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]],c1={hash:1,query:1};function p1(e){var t;typeof window<"u"?t=window:typeof global<"u"?t=global:typeof self<"u"?t=self:t={};var n=t.location||{};e=e||n;var r={},i=typeof e,o;if(e.protocol==="blob:")r=new ha(unescape(e.pathname),{});else if(i==="string"){r=new ha(e,{});for(o in c1)delete r[o]}else if(i==="object"){for(o in e)o in c1||(r[o]=e[o]);r.slashes===void 0&&(r.slashes=due.test(e.href))}return r}function ma(e){return e==="file:"||e==="ftp:"||e==="http:"||e==="https:"||e==="ws:"||e==="wss:"}function m1(e,t){e=qC(e),e=e.replace(f1,""),t=t||{};var n=fue.exec(e),r=n[1]?n[1].toLowerCase():"",i=!!n[2],o=!!n[3],a=0,s;return i?o?(s=n[2]+n[3]+n[4],a=n[2].length+n[3].length):(s=n[2]+n[4],a=n[2].length):o?(s=n[3]+n[4],a=n[3].length):s=n[4],r==="file:"?a>=2&&(s=s.slice(2)):ma(r)?s=n[4]:r?i&&(s=s.slice(2)):a>=2&&ma(t.protocol)&&(s=n[4]),{protocol:r,slashes:i||ma(r),slashesCount:a,rest:s}}function hue(e,t){if(e==="")return t;for(var n=(t||"/").split("/").slice(0,-1).concat(e.split("/")),r=n.length,i=n[r-1],o=!1,a=0;r--;)n[r]==="."?n.splice(r,1):n[r]===".."?(n.splice(r,1),a++):a&&(r===0&&(o=!0),n.splice(r,1),a--);return o&&n.unshift(""),(i==="."||i==="..")&&n.push(""),n.join("/")}function ha(e,t,n){if(e=qC(e),e=e.replace(f1,""),!(this instanceof ha))return new ha(e,t,n);var r,i,o,a,s,u,l=UC.slice(),c=typeof t,d=this,f=0;for(c!=="object"&&c!=="string"&&(n=t,t=null),n&&typeof n!="function"&&(n=B0.parse),t=p1(t),i=m1(e||"",t),r=!i.protocol&&!i.slashes,d.slashes=i.slashes||r&&t.slashes,d.protocol=i.protocol||t.protocol||"",e=i.rest,(i.protocol==="file:"&&(i.slashesCount!==2||pue.test(e))||!i.slashes&&(i.protocol||i.slashesCount<2||!ma(d.protocol)))&&(l[3]=[/(.*)/,"pathname"]);f<l.length;f++){if(a=l[f],typeof a=="function"){e=a(e,d);continue}o=a[0],u=a[1],o!==o?d[u]=e:typeof o=="string"?(s=o==="@"?e.lastIndexOf(o):e.indexOf(o),~s&&(typeof a[2]=="number"?(d[u]=e.slice(0,s),e=e.slice(s+a[2])):(d[u]=e.slice(s),e=e.slice(0,s)))):(s=o.exec(e))&&(d[u]=s[1],e=e.slice(0,s.index)),d[u]=d[u]||r&&a[3]&&t[u]||"",a[4]&&(d[u]=d[u].toLowerCase())}n&&(d.query=n(d.query)),r&&t.slashes&&d.pathname.charAt(0)!=="/"&&(d.pathname!==""||t.pathname!=="")&&(d.pathname=hue(d.pathname,t.pathname)),d.pathname.charAt(0)!=="/"&&ma(d.protocol)&&(d.pathname="/"+d.pathname),d1(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:"&&ma(d.protocol)&&d.host?d.protocol+"//"+d.host:"null",d.href=d.toString()}function gue(e,t,n){var r=this;switch(e){case"query":typeof t=="string"&&t.length&&(t=(n||B0.parse)(t)),r[e]=t;break;case"port":r[e]=t,d1(t,r.protocol)?t&&(r.host=r.hostname+":"+t):(r.host=r.hostname,r[e]="");break;case"hostname":r[e]=t,r.port&&(t+=":"+r.port),r.host=t;break;case"host":r[e]=t,/:\d+$/.test(t)?(t=t.split(":"),r.port=t.pop(),r.hostname=t.join(":")):(r.hostname=t,r.port="");break;case"protocol":r.protocol=t.toLowerCase(),r.slashes=!n;break;case"pathname":case"hash":if(t){var i=e==="pathname"?"/":"#";r[e]=t.charAt(0)!==i?i+t:t}else r[e]=t;break;case"username":case"password":r[e]=encodeURIComponent(t);break;case"auth":var o=t.indexOf(":");~o?(r.username=t.slice(0,o),r.username=encodeURIComponent(decodeURIComponent(r.username)),r.password=t.slice(o+1),r.password=encodeURIComponent(decodeURIComponent(r.password))):r.username=encodeURIComponent(decodeURIComponent(t))}for(var a=0;a<UC.length;a++){var s=UC[a];s[4]&&(r[s[1]]=r[s[1]].toLowerCase())}return r.auth=r.password?r.username+":"+r.password:r.username,r.origin=r.protocol!=="file:"&&ma(r.protocol)&&r.host?r.protocol+"//"+r.host:"null",r.href=r.toString(),r}function yue(e){(!e||typeof e!="function")&&(e=B0.stringify);var t,n=this,r=n.host,i=n.protocol;i&&i.charAt(i.length-1)!==":"&&(i+=":");var o=i+(n.protocol&&n.slashes||ma(n.protocol)?"//":"");return n.username?(o+=n.username,n.password&&(o+=":"+n.password),o+="@"):n.password?(o+=":"+n.password,o+="@"):n.protocol!=="file:"&&ma(n.protocol)&&!r&&n.pathname!=="/"&&(o+="@"),r[r.length-1]===":"&&(r+=":"),o+=r+n.pathname,t=typeof n.query=="object"?e(n.query):n.query,t&&(o+=t.charAt(0)!=="?"?"?"+t:t),n.hash&&(o+=n.hash),o}ha.prototype={set:gue,toString:yue};ha.extractProtocol=m1;ha.location=p1;ha.trimLeft=qC;ha.qs=B0;h1.exports=ha});var bue,g1=B(()=>{"use strict";bue=Xe(BC());});function VC(e,t,n){let r=Object.keys(n).sort();if(r.length===0)throw new Error(`ECS feature has no properties: ${e}.${t}`);let i=`ecs.${e}.${t}`;return r.length===1?`${i}.${r[0]}`:`${i}.{${r.join(";")}}`}var V0=B(()=>{"use strict";});var GC,jC,WC=B(()=>{"use strict";V0();GC=class{features=new Map;register(t,n){let r=VC(n,t.teamName,t.fallback),i={clientName:n,teamName:t.teamName,fullName:r,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(r,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(n=>n.clientName===t)}getByTeam(t){return this.getAll().filter(n=>n.teamName===t)}search(t){let n=t.toLowerCase();return this.getAll().filter(r=>r.fullName.toLowerCase().includes(n)||r.description?.toLowerCase().includes(n)||r.teamName.toLowerCase().includes(n)||r.clientName.toLowerCase().includes(n))}getClientNames(){let t=new Set;return this.features.forEach(n=>t.add(n.clientName)),Array.from(t)}getTeamNames(){let t=new Set;return this.features.forEach(n=>t.add(n.teamName)),Array.from(t)}clear(){this.features.clear()}},jC=new GC});var zC=B(()=>{"use strict";});function U0(e){return vue.has(e)}var vue,Up=B(()=>{"use strict";kC();MC();F0();xp();kC();g1();WC();V0();zC();vue=new Set(["tie","test","prod","preview","preprod","gov","high","dod","mooncake","ex","rx"])});var wue,y1=B(()=>{"use strict";Up();wue=Fp({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 E1,KC,nd,El,HC,G0,rd,cs,xt,b1,v1,w1,Io=B(()=>{"use strict";E1={ThreeEqColumn_FirstColumn:34,ThreeEqColumn_SecondColumn:33,ThreeEqColumn_ThirdColumn:33,FiveEqColumn:20},KC={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"})(nd||(nd={}));(function(e){e.Left="Left",e.Right="Right",e.Center="Center"})(El||(El={}));(function(e){e[e.Mobile=0]="Mobile",e[e.Tablet=1]="Tablet",e[e.Web=2]="Web"})(HC||(HC={}));G0=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"})(rd||(rd={}));cs=class{static StartTag="<"},xt={ShowLabel:"true",LockLevel:"0",IsUserDefined:"0",LabelWidth:"115",columns:"1",ShowBar:"false",Layout:"varwidth",namePrefix:"_section_",labelAlignment:El.Left,labelPosition:rd.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"})(b1||(b1={}));(function(e){e.TabWithLockedFieldRemoval="TabWithLockedFieldRemoval",e.SectionWithLockedFieldRemoval="SectionWithLockedFieldRemoval",e.LockedSectionRemoval="LockedSectionRemoval",e.LockedFieldRemoval="LockedFieldRemoval",e.RequiredFieldRemoval="RequiredFieldRemoval",e.LastRemainingTab="LastRemainingTab",e.UnknownRemoval="UnknownRemoval"})(v1||(v1={}));(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"})(w1||(w1={}))});var JC,A1=B(()=>{"use strict";(function(e){e.DefaultValue="defaultValue",e.Loaded="loaded"})(JC||(JC={}))});var N1,Eue,C1,zDe,HDe,qp,S1,KDe,JDe,_1=B(()=>{"use strict";N1=Xe(vl());En();td();y1();xc();Io();cl();Re();Eue=Xe(Ds());A1();(function(e){e.Model="Model",e.Canvas="Canvas",e.CustomPages="CustomPages"})(C1||(C1={}));zDe={Read:eu.Read,Edit:eu.Edit,Both:eu.Both,Container:eu.Container},HDe={input:ll.Input,bound:ll.Bound,output:ll.Output};(function(e){e[e.dataset=0]="dataset",e[e.property=1]="property",e[e.groups=2]="groups",e[e.group=3]="group"})(qp||(qp={}));(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"})(S1||(S1={}));KDe=new Set([j.Currency,j.Decimal,j.FP,j.Multiple,j.SingleLineEmail,j.SingleLinePhone,j.SingleLineText,j.SingleLineTextArea,j.SingleLineURL,j.SingleLineTickerSymbol,j.WholeNone,j.WholeDuration,j.WholeLanguage,j.WholeTimeZone,j.Enum,j.LookupSimple,j.LookupCustomer,j.LookupOwner,j.LookupPartyList,j.LookupRegarding,j.TwoOptions,j.Boolean,j.PowerBIReport,j.DateAndTimeDateAndTime,j.DateAndTimeDateOnly,j.OptionSet,j.MultiSelectOptionSet,j.CardForm]),JDe={numbers:[j.WholeNone,j.FP,j.Decimal,j.Currency],text:[j.SingleLineText,j.SingleLineTextArea,j.Multiple],lookup:[j.LookupSimple,j.LookupCustomer,j.LookupOwner,j.LookupPartyList,j.LookupRegarding],dates:[j.DateAndTimeDateOnly,j.DateAndTimeDateAndTime],allFields:[j.TwoOptions,j.DateAndTimeDateOnly,j.DateAndTimeDateAndTime,j.FP,j.Decimal,j.WholeNone,j.WholeDuration,j.WholeTimeZone,j.WholeLanguage,j.LookupSimple,j.LookupCustomer,j.LookupOwner,j.LookupPartyList,j.LookupRegarding,j.Multiple,j.OptionSet,j.SingleLineText,j.SingleLineTextArea,j.SingleLineEmail,j.SingleLineURL,j.SingleLineTickerSymbol,j.SingleLinePhone]}});var To,j0,I1=B(()=>{"use strict";To=Xe(vl());Dn();En();Sr();td();cl();_1();xc();Re();Jn();Io();j0=class extends Se{constructor(t){super(D.customControl,t)}customControlId;get id(){let t=this.getProperty(A.id);return F.IsNullOrUndefined(t)?null:t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"?new H(t.substr(1,t.length-2)):new H(t)}getParameters(){let t=new Map,n=this.getAllChildren();if(n&&n.length!==0&&n[0]){let r=n[0].getAllChildren();if(r!=null){for(let i of r)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 n=this.getParameters()?.get(vr.value);if(n?.length>0){let r=n[0],i=r?.getAllChildren()?.length>0?r.getAllChildren().find(a=>a.getNodeName()===t):null,o=i?.getAllChildren()?.length>0?i.getAllChildren()[0].getNodeName():"";return this.normalizePropertyValue(o)}}getParameterValue(t){let n=this.getParameterNodeChild(t);return n&&this.normalizePropertyValue(n.getNodeName())}getParameterNodeChild(t){let n=this.getParameters().get(t);return n?.length>0&&n[0].getAllChildren()?.length>0?n[0].getAllChildren()[0]:null}getDatasetName(t){return t.getAllProperties().find(n=>n.key===vr.name)?.value}getParameterChildrenValues(t,n,r){if(this.isDataSet(t)){let i=n.find(l=>l.key===vr.name)?.value,o={Name:i,Type:j.Grid,Columns:[]},u=this.getParameters().get(vr.dataset).find(l=>this.getDatasetName(l)===i).getAllChildren();for(let l of u){let c=l.getNodeName();if(l&&l.getAllChildren().length>0){let d=this.normalizePropertyValue(l.getAllChildren()[0].getNodeName());o[c]=d}}return o}}getParameterIsStatic(t){let n=!1,r=this.getParameters().get(t)[0],i=r&&r.getAllProperties();if(i){for(let o of i)if(o.key===A.static&&o.value==="true"){n=!0;break}}return n}get name(){return this.getProperty(A.Name)}get formFactor(){return this.getProperty(A.formFactor)}set formFactor(t){this.setProperty(A.formFactor,t)}async toJSON(t){if(this.id)return null;let n=await this.parametersToJSON(t),r=parseInt(this.formFactor,10);return{CustomControlId:this.customControlId,FormFactor:isNaN(r)?-1:r,Name:this.name,Version:null,Parameters:n,ShouldOverrideControlVisible:!1}}normalizePropertyValue(t){return t.startsWith(cs.StartTag)&&(t=t.substring(1)),t}async parametersToJSON(t){let n=[];if(!this.name)return n;try{let r=await t.formModelService.customControlDiscoveryService.getCustomControlMetadata(this.name);if(r)if(r.configurations){let i=r.configurations,o=this.getParameters();for(let[a,s]of o)if(this.isDataSet(a))for(let u of o.get(a)){let l=u.getAllProperties(),c=this.getDatasetName(u),d=i.get(c),f=await this.parameterJSON(a,l,d,t);n.push({Name:c,Value:f})}else if(this.isGroups(s))n.push({Name:a,Value:{Type:IA.GroupDefinition,Value:this.normalizePropertyValue(this.getParameterNodeChild(s[0].NodeName).NodeName)}}),i.get(a).groupSet?.forEach(l=>{l.groupConfigurableProperties.forEach(async c=>{let d=c.name;c.propertyType===qp.dataset?o.get(vr.dataset)?.some(p=>this.getDatasetName(p)===d)||n.push({Name:d,Value:{Name:d,Columns:[],Type:j.Grid}}):c.propertyType===qp.property&&(o.has(d)||n.push({Name:d,Value:{Usage:c.usage}}))})});else{let u=s[0].getAllProperties(),l=i.get(a),c=await this.parameterJSON(a,u,l,t);if(c)n.push({Name:a,Value:c});else{(0,To.trackInfoTrace)(Vr,{eventName:`${us}/parametersToJSON`,eventData:{message:`Configuration metadata for custom control parameter ${a} is not available for custom control : ${this.name}.`}}),n=[];break}}}else(0,To.trackErrorTrace)(Vr,{eventName:`${us}/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,To.trackErrorTrace)(Vr,{eventName:`${us}/parametersToJSON`,eventData:{message:"Custom Control Manifest not found"}},new Error(`No custom control manifest found for ${this.name}`))}catch(r){(0,To.trackErrorTrace)(Vr,{eventName:`${us}/parametersToJSON`,eventData:{message:"parameters to json failed"}},r)}return n}async parameterJSON(t,n,r,i){if(this.isDataSet(t)){let o=r,a=n.find(s=>s.key===vr.name)?.value;if(o)return this.getParameterChildrenValues(t,n);{let s=new Error(`No dataset manifest info for ${a}`);(0,To.trackErrorTrace)(Vr,{eventName:`${us}/parameterJSON`,eventData:{message:"Missing custom control manifest dataset info"}},s)}}else{let o=r,a=n&&n.find(u=>u.key===A.Type),s=o&&!o.ofTypeGroup.every(u=>!Xg.includes(u));if(this.isLookupType(a?.value)||this.isLookupType(o?.ofType)||s)if(o){let u=o.usage,l=this.getParameterIsStatic(t),c=o.isPrimary;if(this.name===is.FormComponent){let d=this.getFormComponentValueByParameterName(A.bindAttribute),f=await i.formModelService.loadLookupModel(d),p=f.lookupColumn,m=this.getLookupDataTypeFromAttributeMetadata(p);return{Name:t,Type:m,Usage:u,Static:l,Primary:c,EntityName:f.primaryTableName,Value:d,ViewId:this.getFormComponentValueByParameterName(_A.DefaultViewId),TargetEntityType:p.targets[0],FilterRelationshipName:this.getFormComponentValueByParameterName(A.FilterRelationshipName),AvailableViewIds:this.getFormComponentValueByParameterName(A.AvailableViewIds),DependentAttributeName:this.getFormComponentValueByParameterName(A.DependentAttributeName),DependentAttributeType:this.getFormComponentValueByParameterName(A.DependentAttributeType),AllowFilterOff:Q.IsStrictTrue(this.getFormComponentValueByParameterName(A.AllowFilterOff)),DisableQuickFind:Q.IsStrictTrue(this.getFormComponentValueByParameterName(A.DisableQuickFind)),EnableViewPicker:!Q.IsStrictTrue(this.getFormComponentValueByParameterName(A.DisableViewPicker))}}return{Name:t,Usage:u,Static:l,Primary:c,Value:this.getParameterValue(t)}}else{let u=new Error(`No lookup manifest info for ${t}`);(0,To.trackErrorTrace)(Vr,{eventName:`${us}/parameterJSON`,eventData:{message:"Missing custom control manifest lookup property info"}},u)}if(o){let u=o.usage,l=this.getParameterIsStatic(t),c=this.getParameterValue(t),d=o.isPrimary;if(a){let p=a.value;return{Type:p,Static:l,Usage:u,Value:this.isNumberTypeProperty(o,p)&&Number(c)?Number(c):c,Primary:d}}if(o.ofType)return{Type:o.ofType,Static:l,Usage:u,Value:c,Primary:!0};if(o.ofTypeGroup)return{Static:l,Usage:u,Value:c,Primary:!0};let f=new Error(`No property type info for ${t}`);(0,To.trackErrorTrace)(Vr,{eventName:`${us}/parameterJSON`,eventData:{message:"Missing property type info"}},f)}else{let u=new Error(`No property manifest info for ${t}`);(0,To.trackWarningTrace)(Vr,{eventName:`${us}/parameterJSON`,eventData:{message:"Missing custom control manifest property info"}},u)}}return null}getLookupDataTypeFromAttributeMetadata(t){let{attributeType:n,format:r}=t;switch(n){case V.Customer:return j.LookupCustomer;case V.Owner:return j.LookupOwner;case V.PartyList:return j.LookupPartyList;default:return r===ne.Regarding?j.LookupRegarding:j.LookupSimple}}isLookupType(t){return Xg.includes(t)}isNumberTypeProperty(t,n){return Zg.includes(n)||t.ofTypeGroup.some(r=>Zg.includes(r))}isDataSet(t){return vr.dataset===t}isGroups(t){return!!t[0].getAllProperties().find(r=>r.key==="isGroup"&&r.value==="true")}}});var be,YC=B(()=>{"use strict";be=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 T1={};Fi(T1,{CustomControlUniqueId:()=>Al,DeprecatedControlClassIds:()=>te,FieldControlTypes:()=>An,mapFieldTypeToControl:()=>Aue});function Aue(e,t){switch(e){case V.TwoOptions:return k.BooleanControl;case V.Customer:case V.CustomerType:return k.LookupControl;case V.DateTime:return t===ne.DateAndTime?k.DateTimeControl:k.DateTimeControl;case V.DecimalNumber:return k.DecimalControl;case V.FloatingPointNumber:return k.FloatingNumberControl;case V.WholeNumber:return t===ne.Duration?k.DurationControl:t===ne.Language?k.LanguageControl:t===ne.TimeZone?k.TimezoneControl:k.IntegerControl;case V.CustomerType:case V.Lookup:case V.LookupType:return t===ne.Regarding?k.RegardingControl:k.LookupControl;case V.MultipleLineofText:return t===ne.Email?k.EmailBodyControl:k.TextAreaControl;case V.Currency:return k.CurrencyControl;case V.Owner:case V.OwnerType:return k.LookupControl;case V.PartyList:case V.PartyListType:return k.PartyListControl;case V.Status:case V.OptionSet:return k.ChoiceControl;case V.SingleLineofText:return t===ne.Email?k.EmailAddressControl:t===ne.Phone?k.PhoneNumberControl:t===ne.Text?k.TextboxControl:t===ne.TextArea?k.TextAreaControl:t===ne.TickerSymbol?k.TickerControl:t===ne.Url?k.UrlControl:t===ne.PhoneticGuide?k.TextboxControl:k.TextboxControl;case V.MultiSelectOptionSet:return k.ChoicesControl;case V.Image:return k.ImageControl;case V.File:return k.FileControl;case V.State:return k.ChoiceControl;case V.Status:return k.ChoiceStatusControl;default:throw new Error(`Cannot get base control for ${e} field type`)}}var te,Al,An,Bp=B(()=>{"use strict";Dn();bp();En();Sr();xc();bl();YC();Io();te=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"}};Al=class{static get RelationshipAssistant(){return"3ff9a528-dd50-4aca-8f10-2e5ed73513ad"}static get PredictiveLeadScoring(){return"6f503f2a-d033-4106-b62c-f8f2e5f01a57"}},An=class e{static FieldControlIds=e.initializeFieldControls();static UnboundControlIds=e.initializeUnboundControls();static ControlsAllowedForReferencePanel=e.initializeReferencePanelControls();static ControlsAllowedForFooter=e.initializeFooterControls();static CustomControlIdMap=new qr;static initializeFieldControls(){let t=new qr,n=e.getControlName(V.SingleLineofText,ne.Phone);t.add(n,new H(te.PhoneNumberControl));let r=e.getControlName(V.SingleLineofText,ne.TextArea);t.add(r,new H(te.TextAreaControl));let i=e.getControlName(V.SingleLineofText,ne.Text);t.add(i,new H(te.TextBoxControl));let o=e.getControlName(V.SingleLineofText,ne.Email);t.add(o,new H(te.EmailAddressControl));let a=e.getControlName(V.SingleLineofText,ne.Url);t.add(a,new H(te.UrlControl));let s=e.getControlName(V.SingleLineofText,ne.TickerSymbol);t.add(s,new H(te.TickerControl));let u=e.getControlName(V.SingleLineofText,ne.PhoneticGuide);t.add(u,new H(te.TextBoxControl));let l=e.getControlName(V.WholeNumber,ne.Duration);t.add(l,new H(te.DurationControl));let c=e.getControlName(V.WholeNumber,ne.Language);t.add(c,new H(te.LanguagePickerControl));let d=e.getControlName(V.WholeNumber,ne.TimeZone);t.add(d,new H(te.TimeZonePicklistControl));let f=e.getControlName(V.WholeNumber,ne.None);t.add(f,new H(te.IntegerControl));let p=e.getControlName(V.DateTime,ne.DateOnly);t.add(p,new H(te.DateTimeControl));let m=e.getControlName(V.DateTime,ne.DateAndTime);t.add(m,new H(te.DateTimeControl));let h=e.getControlName(V.LookupType,ne.None);t.add(h,new H(te.LookupControl));let g=e.getControlName(V.CustomerType,ne.None);t.add(g,new H(te.LookupControl));let y=e.getControlName(V.FloatingPointNumber,ne.None);t.add(y,new H(te.FloatControl));let b=e.getControlName(V.DecimalNumber,ne.None);t.add(b,new H(te.DecimalControl));let E=e.getControlName(V.Currency,ne.None);t.add(E,new H(te.MoneyControl));let w=e.getControlName(V.MultipleLineofText,ne.None);t.add(w,new H(te.TextAreaControl));let _=e.getControlName(V.MultipleLineofText,ne.Text);t.add(_,new H(te.TextAreaControl));let I=e.getControlName(V.MultipleLineofText,ne.TextArea);t.add(I,new H(te.TextAreaControl));let T=e.getControlName(V.MultipleLineofText,ne.Email);t.add(T,new H(te.EmailBodyControl));let O=e.getControlName(V.OptionSet,ne.None);t.add(O,new H(te.PicklistControl));let v=e.getControlName(V.TwoOptions,ne.None);t.add(v,new H(te.RadioControl));let N=e.getControlName(V.Image,ne.None);t.add(N,new H(te.WebResourceImageControl));let S=e.getControlName(V.Image,ne.None);t.add(S,new H(te.WebResourceHtmlControl));let R=e.getControlName(V.TwoOptions,"Radio");t.add(R,new H(te.RadioControl));let x=e.getControlName(V.TwoOptions,"CheckBox");t.add(x,new H(te.CheckBoxControl));let G=e.getControlName(V.TwoOptions,"List");t.add(G,new H(te.PicklistControl));let U=e.getControlName(V.State,ne.None);t.add(U,new H(te.PicklistControl));let M=e.getControlName(V.Status,ne.None);t.add(M,new H(te.PicklistStatusControl));let q=e.getControlName(V.OwnerType,ne.None);t.add(q,new H(te.LookupControl));let X=e.getControlName(V.PartyListType,ne.None);t.add(X,new H(te.PartyListControl));let ye=e.getControlName(V.LookupType,ne.Regarding);t.add(ye,new H(te.RegardingControl));let Ve=e.getControlName(V.MultiSelectOptionSet,ne.None);return t.add(Ve,new H(te.ChoicesControl)),t}static getControlName(t,n){return t+"_"+n}static getControlIdByTypeAndFormat(t,n){let r=e.getControlName(t.toString(),n.toString());return e.FieldControlIds.containsKey(r)?e.FieldControlIds.getValue(r):null}static getTypeAndFormatByControlOrUniqueId(t){for(let n in e.FieldControlIds.getKeys())if(e.FieldControlIds.getValue(e.FieldControlIds.getKeys()[n]).guidString.toLowerCase()===t)return e.FieldControlIds.getKeys()[n]}static getControlDataTypeByControlOrUniqueId(t){if(!F.IsNullOrEmptyGuid(t)){let n=e.getTypeAndFormatByControlOrUniqueId(t.guidString.toLowerCase());return n=F.IsNullOrUndefined(n)?e.getUnboundControlNameFromIdentifier(t):n.substring(0,n.indexOf("_")),n}return null}static isCustomControl(t){return F.IsNullOrUndefined(t.control)||F.IsNullOrUndefined(t.control.ClassId)||t.control.ClassId.guidString===te.CustomControl}static initializeUnboundControls(){let t=new qr;return t.add(te.ACIControl,be.ACIControl),t.add(te.IframeControl,be.IframeControl),t.add(te.SearchWidgetControl,be.SearchWidgetControl),t.add(te.MapsControl,be.MapsControl),t.add(te.QuickFormCollectionControl,be.QuickFormCollectionControl),t.add(te.GridControl,be.SubGridControl),t.add(te.WebResourceImageControl,be.WebResourceImageControl),t.add(te.WebResourceHtmlControl,be.WebResourceHtmlControl),t.add(te.ReferencePanelSearchWidget,be.SearchWidgetControl),t.add(te.ReferencePanelQuickFormCollectionControl,be.QuickFormCollectionControl),t.add(te.ReferencePanelSubgridControl,be.SubGridControl),t.add(te.TimerControl,be.TimerControl),t.add(te.TimeLineControl,be.NotesControl),t.add(te.TimeLineControlUC,be.NotesControl),t.add(te.SocialInsightControl,be.SocialInsightControl),t.add(Al.RelationshipAssistant,be.CustomControl),t}static initializeReferencePanelControls(){let t=new qr;return t.add(te.IframeControl,be.IframeControl),t.add(te.ReferencePanelSearchWidget,be.SearchWidgetControl),t.add(te.ReferencePanelQuickFormCollectionControl,be.QuickFormCollectionControl),t.add(te.ReferencePanelSubgridControl,be.SubGridControl),t.add(te.WebResourceHtmlControl,be.WebResourceHtmlControl),t.add(te.WebResourceImageControl,be.WebResourceHtmlControl),t}static initializeFooterControls(){let t=new Mc;return t.add(nd.IFRAME,!0),t.add(nd.SPACER,!0),t.add(nd.WEB_RESOURCE_HTML,!0),t}static isUnboundFormControl(t){if(F.IsNullOrUndefined(t)||F.IsNullOrUndefined(t.control)||F.IsNullOrUndefined(t.control.ClassId))return!1;let n=e.getUniqueIdentifierForControl(t.control);return e.UnboundControlIds.containsKey(n.guidString)}static isReferencePanelSection(t){return!F.IsNullOrUndefined(t)&&!F.IsNullOrUndefined(t.Name)&&t.Name.indexOf(xt.referencePanelNamePrefix)===0}static isUnboundFormControlByIdentifier(t){return F.IsNullOrUndefined(t)||F.IsNullOrUndefined(t.guidString)?!1:e.UnboundControlIds.containsKey(t.guidString)}static getUnboundFormControlName(t){let n=Q.EmptyString;if(F.IsNullOrUndefined(t)||F.IsNullOrUndefined(t.control)||F.IsNullOrUndefined(t.control.ClassId))return n;let r=e.getUniqueIdentifierForControl(t.control);return e.UnboundControlIds.getValue(r.guidString).toString()}static getUnboundControlNameFromIdentifier(t){return F.IsNullOrUndefined(t)||F.IsNullOrUndefined(t.guidString)?Q.EmptyString:e.UnboundControlIds.getValue(t.guidString).toString()}static isSpacerControl(t){return t===te.SpacerControl}static GetRowSpan(t){let n=t.ClassId;if(e.isRelationshipAssistantControl(t))n=t.UniqueId;else if(n.guidString===te.CustomControl&&!F.IsNullOrUndefined(t.UniqueId)){let r=t.UniqueId.ToString();e.CustomControlIdMap.containsKey(r)&&(n=e.CustomControlIdMap.getValue(r))}switch(e.UnboundControlIds.getValue(n.guidString)){case be.IframeControl:case be.ACIControl:case be.SocialInsightControl:return 6;case be.SubGridControl:case be.CustomControl:return 4;case be.WebResourceImageControl:return 15;case be.WebResourceHtmlControl:return 15;case be.MapsControl:return 8;case be.SearchWidgetControl:return 10;case be.NotesControl:case be.TimeLineControl:return 15;case be.TimerControl:return 2;default:}}static isLookUpControl(t){return!F.IsNullOrUndefined(t)&&t.ClassId.guidString===te.LookupControl}static isRelationshipAssistantOrLeadScoringControl(t){return!F.IsNullOrUndefined(t)&&e.isRelationshipAssistantOrLeadScoring(t.UniqueId)}static isRelationshipAssistantOrLeadScoring(t){return!F.IsNullOrUndefined(t)&&(t.guidString===Al.RelationshipAssistant||t.guidString===Al.PredictiveLeadScoring)}static isRelationshipAssistantControl(t){return!F.IsNullOrUndefined(t)&&e.isRelationshipAssistant(t.UniqueId)}static isRelationshipAssistant(t){return!F.IsNullOrUndefined(t)&&t.guidString===Al.RelationshipAssistant}static getUniqueIdentifierForControl(t){if(F.IsNullOrUndefined(t))return null;let n=t.ClassId;if(e.isRelationshipAssistantControl(t))n=t.UniqueId;else if(n.guidString===te.CustomControl&&!F.IsNullOrUndefined(t.UniqueId)){let r=t.UniqueId.ToString();e.CustomControlIdMap.containsKey(r)&&(n=e.CustomControlIdMap.getValue(r))}return n}}});var W0,O1=B(()=>{"use strict";W0=class{listeners=[];listenersOncer=[];on(t){return this.listeners.push(t),{dispose:()=>this.off(t)}}once(t){this.listenersOncer.push(t)}off(t){let n=this.listeners.indexOf(t);n>-1&&this.listeners.splice(n,1)}emit(t){this.listeners.forEach(n=>n(t)),this.listenersOncer.forEach(n=>n(t)),this.listenersOncer=[]}pipe(t){return this.on(n=>t.emit(n))}}});var Cl,id,D1,P1,lu,R1,k1,QC=B(()=>{"use strict";(function(e){e[e.Center=0]="Center",e[e.Left=1]="Left",e[e.Right=2]="Right"})(Cl||(Cl={}));(function(e){e[e.Left=0]="Left",e[e.Top=1]="Top"})(id||(id={}));(function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle"})(D1||(D1={}));(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"})(P1||(P1={}));(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"})(lu||(lu={}));(function(e){e[e.None=0]="None",e[e.SystemRequired=1]="SystemRequired",e[e.ApplicationRequired=2]="ApplicationRequired",e[e.Recommended=3]="Recommended"})(R1||(R1={}));(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"})(k1||(k1={}))});var od,$1=B(()=>{"use strict";Up();od=xC({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 L1(e){return{...e,extractConfig:t=>Cue(t,Object.keys(e.fallback))}}function Cue(e,t){let n={};for(let r of t)typeof e[r]<"u"&&(n[r]=e[r]);return n}var XC=B(()=>{"use strict";});var ZC=C((APe,x1)=>{var Vp=new Proxy(function(){return Vp},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:Vp},apply:function(){return Vp},construct:function(){return{}}}),M1=function(){return Vp};Object.setPrototypeOf(M1,Vp);x1.exports=M1});var q1=C((CPe,U1)=>{var Gp=new Proxy(function(){return Gp},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:Gp},apply:function(){return Gp},construct:function(){return{}}}),F1=function(){return Gp};Object.setPrototypeOf(F1,Gp);U1.exports=F1});var eS=C((SPe,V1)=>{var jp=new Proxy(function(){return jp},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:jp},apply:function(){return jp},construct:function(){return{}}}),B1=function(){return jp};Object.setPrototypeOf(B1,jp);V1.exports=B1});var j1=C((NPe,G1)=>{function Sue(){this.__data__=[],this.size=0}G1.exports=Sue});var ad=C((_Pe,W1)=>{function Nue(e,t){return e===t||e!==e&&t!==t}W1.exports=Nue});var Wp=C((IPe,z1)=>{var _ue=ad();function Iue(e,t){for(var n=e.length;n--;)if(_ue(e[n][0],t))return n;return-1}z1.exports=Iue});var K1=C((TPe,H1)=>{var Tue=Wp(),Oue=Array.prototype,Due=Oue.splice;function Pue(e){var t=this.__data__,n=Tue(t,e);if(n<0)return!1;var r=t.length-1;return n==r?t.pop():Due.call(t,n,1),--this.size,!0}H1.exports=Pue});var Y1=C((OPe,J1)=>{var Rue=Wp();function kue(e){var t=this.__data__,n=Rue(t,e);return n<0?void 0:t[n][1]}J1.exports=kue});var X1=C((DPe,Q1)=>{var $ue=Wp();function Lue(e){return $ue(this.__data__,e)>-1}Q1.exports=Lue});var ex=C((PPe,Z1)=>{var Mue=Wp();function xue(e,t){var n=this.__data__,r=Mue(n,e);return r<0?(++this.size,n.push([e,t])):n[r][1]=t,this}Z1.exports=xue});var zp=C((RPe,tx)=>{var Fue=j1(),Uue=K1(),que=Y1(),Bue=X1(),Vue=ex();function sd(e){var t=-1,n=e==null?0:e.length;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}sd.prototype.clear=Fue;sd.prototype.delete=Uue;sd.prototype.get=que;sd.prototype.has=Bue;sd.prototype.set=Vue;tx.exports=sd});var rx=C((kPe,nx)=>{var Gue=zp();function jue(){this.__data__=new Gue,this.size=0}nx.exports=jue});var ox=C(($Pe,ix)=>{function Wue(e){var t=this.__data__,n=t.delete(e);return this.size=t.size,n}ix.exports=Wue});var sx=C((LPe,ax)=>{function zue(e){return this.__data__.get(e)}ax.exports=zue});var lx=C((MPe,ux)=>{function Hue(e){return this.__data__.has(e)}ux.exports=Hue});var tS=C((xPe,cx)=>{var Kue=typeof global=="object"&&global&&global.Object===Object&&global;cx.exports=Kue});var Oo=C((FPe,dx)=>{var Jue=tS(),Yue=typeof self=="object"&&self&&self.Object===Object&&self,Que=Jue||Yue||Function("return this")();dx.exports=Que});var Hp=C((UPe,fx)=>{var Xue=Oo(),Zue=Xue.Symbol;fx.exports=Zue});var gx=C((qPe,hx)=>{var px=Hp(),mx=Object.prototype,ele=mx.hasOwnProperty,tle=mx.toString,Kp=px?px.toStringTag:void 0;function nle(e){var t=ele.call(e,Kp),n=e[Kp];try{e[Kp]=void 0;var r=!0}catch{}var i=tle.call(e);return r&&(t?e[Kp]=n:delete e[Kp]),i}hx.exports=nle});var bx=C((BPe,yx)=>{var rle=Object.prototype,ile=rle.toString;function ole(e){return ile.call(e)}yx.exports=ole});var Sl=C((VPe,Ex)=>{var vx=Hp(),ale=gx(),sle=bx(),ule="[object Null]",lle="[object Undefined]",wx=vx?vx.toStringTag:void 0;function cle(e){return e==null?e===void 0?lle:ule:wx&&wx in Object(e)?ale(e):sle(e)}Ex.exports=cle});var ds=C((GPe,Ax)=>{function dle(e){var t=typeof e;return e!=null&&(t=="object"||t=="function")}Ax.exports=dle});var z0=C((jPe,Cx)=>{var fle=Sl(),ple=ds(),mle="[object AsyncFunction]",hle="[object Function]",gle="[object GeneratorFunction]",yle="[object Proxy]";function ble(e){if(!ple(e))return!1;var t=fle(e);return t==hle||t==gle||t==mle||t==yle}Cx.exports=ble});var Nx=C((WPe,Sx)=>{var vle=Oo(),wle=vle["__core-js_shared__"];Sx.exports=wle});var Tx=C((zPe,Ix)=>{var nS=Nx(),_x=(function(){var e=/[^.]+$/.exec(nS&&nS.keys&&nS.keys.IE_PROTO||"");return e?"Symbol(src)_1."+e:""})();function Ele(e){return!!_x&&_x in e}Ix.exports=Ele});var rS=C((HPe,Ox)=>{var Ale=Function.prototype,Cle=Ale.toString;function Sle(e){if(e!=null){try{return Cle.call(e)}catch{}try{return e+""}catch{}}return""}Ox.exports=Sle});var Px=C((KPe,Dx)=>{var Nle=z0(),_le=Tx(),Ile=ds(),Tle=rS(),Ole=/[\\^$.*+?()[\]{}|]/g,Dle=/^\[object .+?Constructor\]$/,Ple=Function.prototype,Rle=Object.prototype,kle=Ple.toString,$le=Rle.hasOwnProperty,Lle=RegExp("^"+kle.call($le).replace(Ole,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function Mle(e){if(!Ile(e)||_le(e))return!1;var t=Nle(e)?Lle:Dle;return t.test(Tle(e))}Dx.exports=Mle});var kx=C((JPe,Rx)=>{function xle(e,t){return e?.[t]}Rx.exports=xle});var cu=C((YPe,$x)=>{var Fle=Px(),Ule=kx();function qle(e,t){var n=Ule(e,t);return Fle(n)?n:void 0}$x.exports=qle});var H0=C((QPe,Lx)=>{var Ble=cu(),Vle=Oo(),Gle=Ble(Vle,"Map");Lx.exports=Gle});var Jp=C((XPe,Mx)=>{var jle=cu(),Wle=jle(Object,"create");Mx.exports=Wle});var Ux=C((ZPe,Fx)=>{var xx=Jp();function zle(){this.__data__=xx?xx(null):{},this.size=0}Fx.exports=zle});var Bx=C((eRe,qx)=>{function Hle(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t}qx.exports=Hle});var Gx=C((tRe,Vx)=>{var Kle=Jp(),Jle="__lodash_hash_undefined__",Yle=Object.prototype,Qle=Yle.hasOwnProperty;function Xle(e){var t=this.__data__;if(Kle){var n=t[e];return n===Jle?void 0:n}return Qle.call(t,e)?t[e]:void 0}Vx.exports=Xle});var Wx=C((nRe,jx)=>{var Zle=Jp(),ece=Object.prototype,tce=ece.hasOwnProperty;function nce(e){var t=this.__data__;return Zle?t[e]!==void 0:tce.call(t,e)}jx.exports=nce});var Hx=C((rRe,zx)=>{var rce=Jp(),ice="__lodash_hash_undefined__";function oce(e,t){var n=this.__data__;return this.size+=this.has(e)?0:1,n[e]=rce&&t===void 0?ice:t,this}zx.exports=oce});var Jx=C((iRe,Kx)=>{var ace=Ux(),sce=Bx(),uce=Gx(),lce=Wx(),cce=Hx();function ud(e){var t=-1,n=e==null?0:e.length;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}ud.prototype.clear=ace;ud.prototype.delete=sce;ud.prototype.get=uce;ud.prototype.has=lce;ud.prototype.set=cce;Kx.exports=ud});var Xx=C((oRe,Qx)=>{var Yx=Jx(),dce=zp(),fce=H0();function pce(){this.size=0,this.__data__={hash:new Yx,map:new(fce||dce),string:new Yx}}Qx.exports=pce});var eF=C((aRe,Zx)=>{function mce(e){var t=typeof e;return t=="string"||t=="number"||t=="symbol"||t=="boolean"?e!=="__proto__":e===null}Zx.exports=mce});var Yp=C((sRe,tF)=>{var hce=eF();function gce(e,t){var n=e.__data__;return hce(t)?n[typeof t=="string"?"string":"hash"]:n.map}tF.exports=gce});var rF=C((uRe,nF)=>{var yce=Yp();function bce(e){var t=yce(this,e).delete(e);return this.size-=t?1:0,t}nF.exports=bce});var oF=C((lRe,iF)=>{var vce=Yp();function wce(e){return vce(this,e).get(e)}iF.exports=wce});var sF=C((cRe,aF)=>{var Ece=Yp();function Ace(e){return Ece(this,e).has(e)}aF.exports=Ace});var lF=C((dRe,uF)=>{var Cce=Yp();function Sce(e,t){var n=Cce(this,e),r=n.size;return n.set(e,t),this.size+=n.size==r?0:1,this}uF.exports=Sce});var K0=C((fRe,cF)=>{var Nce=Xx(),_ce=rF(),Ice=oF(),Tce=sF(),Oce=lF();function ld(e){var t=-1,n=e==null?0:e.length;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}ld.prototype.clear=Nce;ld.prototype.delete=_ce;ld.prototype.get=Ice;ld.prototype.has=Tce;ld.prototype.set=Oce;cF.exports=ld});var fF=C((pRe,dF)=>{var Dce=zp(),Pce=H0(),Rce=K0(),kce=200;function $ce(e,t){var n=this.__data__;if(n instanceof Dce){var r=n.__data__;if(!Pce||r.length<kce-1)return r.push([e,t]),this.size=++n.size,this;n=this.__data__=new Rce(r)}return n.set(e,t),this.size=n.size,this}dF.exports=$ce});var iS=C((mRe,pF)=>{var Lce=zp(),Mce=rx(),xce=ox(),Fce=sx(),Uce=lx(),qce=fF();function cd(e){var t=this.__data__=new Lce(e);this.size=t.size}cd.prototype.clear=Mce;cd.prototype.delete=xce;cd.prototype.get=Fce;cd.prototype.has=Uce;cd.prototype.set=qce;pF.exports=cd});var hF=C((hRe,mF)=>{var Bce="__lodash_hash_undefined__";function Vce(e){return this.__data__.set(e,Bce),this}mF.exports=Vce});var yF=C((gRe,gF)=>{function Gce(e){return this.__data__.has(e)}gF.exports=Gce});var vF=C((yRe,bF)=>{var jce=K0(),Wce=hF(),zce=yF();function J0(e){var t=-1,n=e==null?0:e.length;for(this.__data__=new jce;++t<n;)this.add(e[t])}J0.prototype.add=J0.prototype.push=Wce;J0.prototype.has=zce;bF.exports=J0});var EF=C((bRe,wF)=>{function Hce(e,t){for(var n=-1,r=e==null?0:e.length;++n<r;)if(t(e[n],n,e))return!0;return!1}wF.exports=Hce});var CF=C((vRe,AF)=>{function Kce(e,t){return e.has(t)}AF.exports=Kce});var oS=C((wRe,SF)=>{var Jce=vF(),Yce=EF(),Qce=CF(),Xce=1,Zce=2;function ede(e,t,n,r,i,o){var a=n&Xce,s=e.length,u=t.length;if(s!=u&&!(a&&u>s))return!1;var l=o.get(e),c=o.get(t);if(l&&c)return l==t&&c==e;var d=-1,f=!0,p=n&Zce?new Jce:void 0;for(o.set(e,t),o.set(t,e);++d<s;){var m=e[d],h=t[d];if(r)var g=a?r(h,m,d,t,e,o):r(m,h,d,e,t,o);if(g!==void 0){if(g)continue;f=!1;break}if(p){if(!Yce(t,function(y,b){if(!Qce(p,b)&&(m===y||i(m,y,n,r,o)))return p.push(b)})){f=!1;break}}else if(!(m===h||i(m,h,n,r,o))){f=!1;break}}return o.delete(e),o.delete(t),f}SF.exports=ede});var aS=C((ERe,NF)=>{var tde=Oo(),nde=tde.Uint8Array;NF.exports=nde});var IF=C((ARe,_F)=>{function rde(e){var t=-1,n=Array(e.size);return e.forEach(function(r,i){n[++t]=[i,r]}),n}_F.exports=rde});var OF=C((CRe,TF)=>{function ide(e){var t=-1,n=Array(e.size);return e.forEach(function(r){n[++t]=r}),n}TF.exports=ide});var $F=C((SRe,kF)=>{var DF=Hp(),PF=aS(),ode=ad(),ade=oS(),sde=IF(),ude=OF(),lde=1,cde=2,dde="[object Boolean]",fde="[object Date]",pde="[object Error]",mde="[object Map]",hde="[object Number]",gde="[object RegExp]",yde="[object Set]",bde="[object String]",vde="[object Symbol]",wde="[object ArrayBuffer]",Ede="[object DataView]",RF=DF?DF.prototype:void 0,sS=RF?RF.valueOf:void 0;function Ade(e,t,n,r,i,o,a){switch(n){case Ede:if(e.byteLength!=t.byteLength||e.byteOffset!=t.byteOffset)return!1;e=e.buffer,t=t.buffer;case wde:return!(e.byteLength!=t.byteLength||!o(new PF(e),new PF(t)));case dde:case fde:case hde:return ode(+e,+t);case pde:return e.name==t.name&&e.message==t.message;case gde:case bde:return e==t+"";case mde:var s=sde;case yde:var u=r&lde;if(s||(s=ude),e.size!=t.size&&!u)return!1;var l=a.get(e);if(l)return l==t;r|=cde,a.set(e,t);var c=ade(s(e),s(t),r,i,o,a);return a.delete(e),c;case vde:if(sS)return sS.call(e)==sS.call(t)}return!1}kF.exports=Ade});var MF=C((NRe,LF)=>{function Cde(e,t){for(var n=-1,r=t.length,i=e.length;++n<r;)e[i+n]=t[n];return e}LF.exports=Cde});var du=C((_Re,xF)=>{var Sde=Array.isArray;xF.exports=Sde});var UF=C((IRe,FF)=>{var Nde=MF(),_de=du();function Ide(e,t,n){var r=t(e);return _de(e)?r:Nde(r,n(e))}FF.exports=Ide});var BF=C((TRe,qF)=>{function Tde(e,t){for(var n=-1,r=e==null?0:e.length,i=0,o=[];++n<r;){var a=e[n];t(a,n,e)&&(o[i++]=a)}return o}qF.exports=Tde});var GF=C((ORe,VF)=>{function Ode(){return[]}VF.exports=Ode});var zF=C((DRe,WF)=>{var Dde=BF(),Pde=GF(),Rde=Object.prototype,kde=Rde.propertyIsEnumerable,jF=Object.getOwnPropertySymbols,$de=jF?function(e){return e==null?[]:(e=Object(e),Dde(jF(e),function(t){return kde.call(e,t)}))}:Pde;WF.exports=$de});var KF=C((PRe,HF)=>{function Lde(e,t){for(var n=-1,r=Array(e);++n<e;)r[n]=t(n);return r}HF.exports=Lde});var fu=C((RRe,JF)=>{function Mde(e){return e!=null&&typeof e=="object"}JF.exports=Mde});var QF=C((kRe,YF)=>{var xde=Sl(),Fde=fu(),Ude="[object Arguments]";function qde(e){return Fde(e)&&xde(e)==Ude}YF.exports=qde});var uS=C(($Re,eU)=>{var XF=QF(),Bde=fu(),ZF=Object.prototype,Vde=ZF.hasOwnProperty,Gde=ZF.propertyIsEnumerable,jde=XF((function(){return arguments})())?XF:function(e){return Bde(e)&&Vde.call(e,"callee")&&!Gde.call(e,"callee")};eU.exports=jde});var nU=C((LRe,tU)=>{function Wde(){return!1}tU.exports=Wde});var Y0=C((Qp,dd)=>{var zde=Oo(),Hde=nU(),oU=typeof Qp=="object"&&Qp&&!Qp.nodeType&&Qp,rU=oU&&typeof dd=="object"&&dd&&!dd.nodeType&&dd,Kde=rU&&rU.exports===oU,iU=Kde?zde.Buffer:void 0,Jde=iU?iU.isBuffer:void 0,Yde=Jde||Hde;dd.exports=Yde});var Q0=C((MRe,aU)=>{var Qde=9007199254740991,Xde=/^(?:0|[1-9]\d*)$/;function Zde(e,t){var n=typeof e;return t=t??Qde,!!t&&(n=="number"||n!="symbol"&&Xde.test(e))&&e>-1&&e%1==0&&e<t}aU.exports=Zde});var lS=C((xRe,sU)=>{var efe=9007199254740991;function tfe(e){return typeof e=="number"&&e>-1&&e%1==0&&e<=efe}sU.exports=tfe});var lU=C((FRe,uU)=>{var nfe=Sl(),rfe=lS(),ife=fu(),ofe="[object Arguments]",afe="[object Array]",sfe="[object Boolean]",ufe="[object Date]",lfe="[object Error]",cfe="[object Function]",dfe="[object Map]",ffe="[object Number]",pfe="[object Object]",mfe="[object RegExp]",hfe="[object Set]",gfe="[object String]",yfe="[object WeakMap]",bfe="[object ArrayBuffer]",vfe="[object DataView]",wfe="[object Float32Array]",Efe="[object Float64Array]",Afe="[object Int8Array]",Cfe="[object Int16Array]",Sfe="[object Int32Array]",Nfe="[object Uint8Array]",_fe="[object Uint8ClampedArray]",Ife="[object Uint16Array]",Tfe="[object Uint32Array]",It={};It[wfe]=It[Efe]=It[Afe]=It[Cfe]=It[Sfe]=It[Nfe]=It[_fe]=It[Ife]=It[Tfe]=!0;It[ofe]=It[afe]=It[bfe]=It[sfe]=It[vfe]=It[ufe]=It[lfe]=It[cfe]=It[dfe]=It[ffe]=It[pfe]=It[mfe]=It[hfe]=It[gfe]=It[yfe]=!1;function Ofe(e){return ife(e)&&rfe(e.length)&&!!It[nfe(e)]}uU.exports=Ofe});var dU=C((URe,cU)=>{function Dfe(e){return function(t){return e(t)}}cU.exports=Dfe});var pU=C((Xp,fd)=>{var Pfe=tS(),fU=typeof Xp=="object"&&Xp&&!Xp.nodeType&&Xp,Zp=fU&&typeof fd=="object"&&fd&&!fd.nodeType&&fd,Rfe=Zp&&Zp.exports===fU,cS=Rfe&&Pfe.process,kfe=(function(){try{var e=Zp&&Zp.require&&Zp.require("util").types;return e||cS&&cS.binding&&cS.binding("util")}catch{}})();fd.exports=kfe});var X0=C((qRe,gU)=>{var $fe=lU(),Lfe=dU(),mU=pU(),hU=mU&&mU.isTypedArray,Mfe=hU?Lfe(hU):$fe;gU.exports=Mfe});var dS=C((BRe,yU)=>{var xfe=KF(),Ffe=uS(),Ufe=du(),qfe=Y0(),Bfe=Q0(),Vfe=X0(),Gfe=Object.prototype,jfe=Gfe.hasOwnProperty;function Wfe(e,t){var n=Ufe(e),r=!n&&Ffe(e),i=!n&&!r&&qfe(e),o=!n&&!r&&!i&&Vfe(e),a=n||r||i||o,s=a?xfe(e.length,String):[],u=s.length;for(var l in e)(t||jfe.call(e,l))&&!(a&&(l=="length"||i&&(l=="offset"||l=="parent")||o&&(l=="buffer"||l=="byteLength"||l=="byteOffset")||Bfe(l,u)))&&s.push(l);return s}yU.exports=Wfe});var Z0=C((VRe,bU)=>{var zfe=Object.prototype;function Hfe(e){var t=e&&e.constructor,n=typeof t=="function"&&t.prototype||zfe;return e===n}bU.exports=Hfe});var fS=C((GRe,vU)=>{function Kfe(e,t){return function(n){return e(t(n))}}vU.exports=Kfe});var EU=C((jRe,wU)=>{var Jfe=fS(),Yfe=Jfe(Object.keys,Object);wU.exports=Yfe});var CU=C((WRe,AU)=>{var Qfe=Z0(),Xfe=EU(),Zfe=Object.prototype,epe=Zfe.hasOwnProperty;function tpe(e){if(!Qfe(e))return Xfe(e);var t=[];for(var n in Object(e))epe.call(e,n)&&n!="constructor"&&t.push(n);return t}AU.exports=tpe});var em=C((zRe,SU)=>{var npe=z0(),rpe=lS();function ipe(e){return e!=null&&rpe(e.length)&&!npe(e)}SU.exports=ipe});var _U=C((HRe,NU)=>{var ope=dS(),ape=CU(),spe=em();function upe(e){return spe(e)?ope(e):ape(e)}NU.exports=upe});var TU=C((KRe,IU)=>{var lpe=UF(),cpe=zF(),dpe=_U();function fpe(e){return lpe(e,dpe,cpe)}IU.exports=fpe});var PU=C((JRe,DU)=>{var OU=TU(),ppe=1,mpe=Object.prototype,hpe=mpe.hasOwnProperty;function gpe(e,t,n,r,i,o){var a=n&ppe,s=OU(e),u=s.length,l=OU(t),c=l.length;if(u!=c&&!a)return!1;for(var d=u;d--;){var f=s[d];if(!(a?f in t:hpe.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<u;){f=s[d];var y=e[f],b=t[f];if(r)var E=a?r(b,y,f,t,e,o):r(y,b,f,e,t,o);if(!(E===void 0?y===b||i(y,b,n,r,o):E)){h=!1;break}g||(g=f=="constructor")}if(h&&!g){var w=e.constructor,_=t.constructor;w!=_&&"constructor"in e&&"constructor"in t&&!(typeof w=="function"&&w instanceof w&&typeof _=="function"&&_ instanceof _)&&(h=!1)}return o.delete(e),o.delete(t),h}DU.exports=gpe});var kU=C((YRe,RU)=>{var ype=cu(),bpe=Oo(),vpe=ype(bpe,"DataView");RU.exports=vpe});var LU=C((QRe,$U)=>{var wpe=cu(),Epe=Oo(),Ape=wpe(Epe,"Promise");$U.exports=Ape});var xU=C((XRe,MU)=>{var Cpe=cu(),Spe=Oo(),Npe=Cpe(Spe,"Set");MU.exports=Npe});var UU=C((ZRe,FU)=>{var _pe=cu(),Ipe=Oo(),Tpe=_pe(Ipe,"WeakMap");FU.exports=Tpe});var HU=C((eke,zU)=>{var pS=kU(),mS=H0(),hS=LU(),gS=xU(),yS=UU(),WU=Sl(),pd=rS(),qU="[object Map]",Ope="[object Object]",BU="[object Promise]",VU="[object Set]",GU="[object WeakMap]",jU="[object DataView]",Dpe=pd(pS),Ppe=pd(mS),Rpe=pd(hS),kpe=pd(gS),$pe=pd(yS),Nl=WU;(pS&&Nl(new pS(new ArrayBuffer(1)))!=jU||mS&&Nl(new mS)!=qU||hS&&Nl(hS.resolve())!=BU||gS&&Nl(new gS)!=VU||yS&&Nl(new yS)!=GU)&&(Nl=function(e){var t=WU(e),n=t==Ope?e.constructor:void 0,r=n?pd(n):"";if(r)switch(r){case Dpe:return jU;case Ppe:return qU;case Rpe:return BU;case kpe:return VU;case $pe:return GU}return t});zU.exports=Nl});var tq=C((tke,eq)=>{var bS=iS(),Lpe=oS(),Mpe=$F(),xpe=PU(),KU=HU(),JU=du(),YU=Y0(),Fpe=X0(),Upe=1,QU="[object Arguments]",XU="[object Array]",ey="[object Object]",qpe=Object.prototype,ZU=qpe.hasOwnProperty;function Bpe(e,t,n,r,i,o){var a=JU(e),s=JU(t),u=a?XU:KU(e),l=s?XU:KU(t);u=u==QU?ey:u,l=l==QU?ey:l;var c=u==ey,d=l==ey,f=u==l;if(f&&YU(e)){if(!YU(t))return!1;a=!0,c=!1}if(f&&!c)return o||(o=new bS),a||Fpe(e)?Lpe(e,t,n,r,i,o):Mpe(e,t,u,n,r,i,o);if(!(n&Upe)){var p=c&&ZU.call(e,"__wrapped__"),m=d&&ZU.call(t,"__wrapped__");if(p||m){var h=p?e.value():e,g=m?t.value():t;return o||(o=new bS),i(h,g,n,r,o)}}return f?(o||(o=new bS),xpe(e,t,n,r,i,o)):!1}eq.exports=Bpe});var oq=C((nke,iq)=>{var Vpe=tq(),nq=fu();function rq(e,t,n,r,i){return e===t?!0:e==null||t==null||!nq(e)&&!nq(t)?e!==e&&t!==t:Vpe(e,t,n,r,rq,i)}iq.exports=rq});var sq=C((rke,aq)=>{var Gpe=oq();function jpe(e,t){return Gpe(e,t)}aq.exports=jpe});var vS=C((ike,uq)=>{var Wpe=cu(),zpe=(function(){try{var e=Wpe(Object,"defineProperty");return e({},"",{}),e}catch{}})();uq.exports=zpe});var ty=C((oke,cq)=>{var lq=vS();function Hpe(e,t,n){t=="__proto__"&&lq?lq(e,t,{configurable:!0,enumerable:!0,value:n,writable:!0}):e[t]=n}cq.exports=Hpe});var wS=C((ake,dq)=>{var Kpe=ty(),Jpe=ad();function Ype(e,t,n){(n!==void 0&&!Jpe(e[t],n)||n===void 0&&!(t in e))&&Kpe(e,t,n)}dq.exports=Ype});var pq=C((ske,fq)=>{function Qpe(e){return function(t,n,r){for(var i=-1,o=Object(t),a=r(t),s=a.length;s--;){var u=a[e?s:++i];if(n(o[u],u,o)===!1)break}return t}}fq.exports=Qpe});var hq=C((uke,mq)=>{var Xpe=pq(),Zpe=Xpe();mq.exports=Zpe});var wq=C((tm,md)=>{var eme=Oo(),vq=typeof tm=="object"&&tm&&!tm.nodeType&&tm,gq=vq&&typeof md=="object"&&md&&!md.nodeType&&md,tme=gq&&gq.exports===vq,yq=tme?eme.Buffer:void 0,bq=yq?yq.allocUnsafe:void 0;function nme(e,t){if(t)return e.slice();var n=e.length,r=bq?bq(n):new e.constructor(n);return e.copy(r),r}md.exports=nme});var Cq=C((lke,Aq)=>{var Eq=aS();function rme(e){var t=new e.constructor(e.byteLength);return new Eq(t).set(new Eq(e)),t}Aq.exports=rme});var Nq=C((cke,Sq)=>{var ime=Cq();function ome(e,t){var n=t?ime(e.buffer):e.buffer;return new e.constructor(n,e.byteOffset,e.length)}Sq.exports=ome});var Iq=C((dke,_q)=>{function ame(e,t){var n=-1,r=e.length;for(t||(t=Array(r));++n<r;)t[n]=e[n];return t}_q.exports=ame});var Dq=C((fke,Oq)=>{var sme=ds(),Tq=Object.create,ume=(function(){function e(){}return function(t){if(!sme(t))return{};if(Tq)return Tq(t);e.prototype=t;var n=new e;return e.prototype=void 0,n}})();Oq.exports=ume});var ES=C((pke,Pq)=>{var lme=fS(),cme=lme(Object.getPrototypeOf,Object);Pq.exports=cme});var kq=C((mke,Rq)=>{var dme=Dq(),fme=ES(),pme=Z0();function mme(e){return typeof e.constructor=="function"&&!pme(e)?dme(fme(e)):{}}Rq.exports=mme});var Lq=C((hke,$q)=>{var hme=em(),gme=fu();function yme(e){return gme(e)&&hme(e)}$q.exports=yme});var Fq=C((gke,xq)=>{var bme=Sl(),vme=ES(),wme=fu(),Eme="[object Object]",Ame=Function.prototype,Cme=Object.prototype,Mq=Ame.toString,Sme=Cme.hasOwnProperty,Nme=Mq.call(Object);function _me(e){if(!wme(e)||bme(e)!=Eme)return!1;var t=vme(e);if(t===null)return!0;var n=Sme.call(t,"constructor")&&t.constructor;return typeof n=="function"&&n instanceof n&&Mq.call(n)==Nme}xq.exports=_me});var AS=C((yke,Uq)=>{function Ime(e,t){if(!(t==="constructor"&&typeof e[t]=="function")&&t!="__proto__")return e[t]}Uq.exports=Ime});var CS=C((bke,qq)=>{var Tme=ty(),Ome=ad(),Dme=Object.prototype,Pme=Dme.hasOwnProperty;function Rme(e,t,n){var r=e[t];(!(Pme.call(e,t)&&Ome(r,n))||n===void 0&&!(t in e))&&Tme(e,t,n)}qq.exports=Rme});var Vq=C((vke,Bq)=>{var kme=CS(),$me=ty();function Lme(e,t,n,r){var i=!n;n||(n={});for(var o=-1,a=t.length;++o<a;){var s=t[o],u=r?r(n[s],e[s],s,n,e):void 0;u===void 0&&(u=e[s]),i?$me(n,s,u):kme(n,s,u)}return n}Bq.exports=Lme});var jq=C((wke,Gq)=>{function Mme(e){var t=[];if(e!=null)for(var n in Object(e))t.push(n);return t}Gq.exports=Mme});var zq=C((Eke,Wq)=>{var xme=ds(),Fme=Z0(),Ume=jq(),qme=Object.prototype,Bme=qme.hasOwnProperty;function Vme(e){if(!xme(e))return Ume(e);var t=Fme(e),n=[];for(var r in e)r=="constructor"&&(t||!Bme.call(e,r))||n.push(r);return n}Wq.exports=Vme});var SS=C((Ake,Hq)=>{var Gme=dS(),jme=zq(),Wme=em();function zme(e){return Wme(e)?Gme(e,!0):jme(e)}Hq.exports=zme});var Jq=C((Cke,Kq)=>{var Hme=Vq(),Kme=SS();function Jme(e){return Hme(e,Kme(e))}Kq.exports=Jme});var tB=C((Ske,eB)=>{var Yq=wS(),Yme=wq(),Qme=Nq(),Xme=Iq(),Zme=kq(),Qq=uS(),Xq=du(),ehe=Lq(),the=Y0(),nhe=z0(),rhe=ds(),ihe=Fq(),ohe=X0(),Zq=AS(),ahe=Jq();function she(e,t,n,r,i,o,a){var s=Zq(e,n),u=Zq(t,n),l=a.get(u);if(l){Yq(e,n,l);return}var c=o?o(s,u,n+"",e,t,a):void 0,d=c===void 0;if(d){var f=Xq(u),p=!f&&the(u),m=!f&&!p&&ohe(u);c=u,f||p||m?Xq(s)?c=s:ehe(s)?c=Xme(s):p?(d=!1,c=Yme(u,!0)):m?(d=!1,c=Qme(u,!0)):c=[]:ihe(u)||Qq(u)?(c=s,Qq(s)?c=ahe(s):(!rhe(s)||nhe(s))&&(c=Zme(u))):d=!1}d&&(a.set(u,c),i(c,u,r,o,a),a.delete(u)),Yq(e,n,c)}eB.exports=she});var NS=C((Nke,rB)=>{var uhe=iS(),lhe=wS(),che=hq(),dhe=tB(),fhe=ds(),phe=SS(),mhe=AS();function nB(e,t,n,r,i){e!==t&&che(t,function(o,a){if(i||(i=new uhe),fhe(o))dhe(e,t,a,n,nB,r,i);else{var s=r?r(mhe(e,a),o,a+"",e,t,i):void 0;s===void 0&&(s=o),lhe(e,a,s)}},phe)}rB.exports=nB});var _S=C((_ke,iB)=>{function hhe(e){return e}iB.exports=hhe});var aB=C((Ike,oB)=>{function ghe(e,t,n){switch(n.length){case 0:return e.call(t);case 1:return e.call(t,n[0]);case 2:return e.call(t,n[0],n[1]);case 3:return e.call(t,n[0],n[1],n[2])}return e.apply(t,n)}oB.exports=ghe});var lB=C((Tke,uB)=>{var yhe=aB(),sB=Math.max;function bhe(e,t,n){return t=sB(t===void 0?e.length-1:t,0),function(){for(var r=arguments,i=-1,o=sB(r.length-t,0),a=Array(o);++i<o;)a[i]=r[t+i];i=-1;for(var s=Array(t+1);++i<t;)s[i]=r[i];return s[t]=n(a),yhe(e,this,s)}}uB.exports=bhe});var dB=C((Oke,cB)=>{function vhe(e){return function(){return e}}cB.exports=vhe});var mB=C((Dke,pB)=>{var whe=dB(),fB=vS(),Ehe=_S(),Ahe=fB?function(e,t){return fB(e,"toString",{configurable:!0,enumerable:!1,value:whe(t),writable:!0})}:Ehe;pB.exports=Ahe});var gB=C((Pke,hB)=>{var Che=800,She=16,Nhe=Date.now;function _he(e){var t=0,n=0;return function(){var r=Nhe(),i=She-(r-n);if(n=r,i>0){if(++t>=Che)return arguments[0]}else t=0;return e.apply(void 0,arguments)}}hB.exports=_he});var bB=C((Rke,yB)=>{var Ihe=mB(),The=gB(),Ohe=The(Ihe);yB.exports=Ohe});var wB=C((kke,vB)=>{var Dhe=_S(),Phe=lB(),Rhe=bB();function khe(e,t){return Rhe(Phe(e,t,Dhe),e+"")}vB.exports=khe});var AB=C(($ke,EB)=>{var $he=ad(),Lhe=em(),Mhe=Q0(),xhe=ds();function Fhe(e,t,n){if(!xhe(n))return!1;var r=typeof t;return(r=="number"?Lhe(n)&&Mhe(t,n.length):r=="string"&&t in n)?$he(n[t],e):!1}EB.exports=Fhe});var IS=C((Lke,CB)=>{var Uhe=wB(),qhe=AB();function Bhe(e){return Uhe(function(t,n){var r=-1,i=n.length,o=i>1?n[i-1]:void 0,a=i>2?n[2]:void 0;for(o=e.length>3&&typeof o=="function"?(i--,o):void 0,a&&qhe(n[0],n[1],a)&&(o=i<3?void 0:o,i=1),t=Object(t);++r<i;){var s=n[r];s&&e(t,s,r,o)}return t})}CB.exports=Bhe});var NB=C((Mke,SB)=>{var Vhe=NS(),Ghe=IS(),jhe=Ghe(function(e,t,n,r){Vhe(e,t,n,r)});SB.exports=jhe});var eo,nm=B(()=>{"use strict";(function(e){e[e.NotLoaded=0]="NotLoaded",e[e.Initialized=1]="Initialized",e[e.ConfigsLoaded=2]="ConfigsLoaded",e[e.Error=3]="Error"})(eo||(eo={}))});function IB(e,t,n="PROD"){let r=i=>`ShellSettings_ECS_ClientCache_${e}_${_B.EcsConfigType[i]}_${n}`;return{getData:i=>{let o=t.getItem(r(i));return Promise.resolve(o?JSON.parse(o):void 0)},putData:(i,o)=>(t.setItem(r(i),JSON.stringify(o)),Promise.resolve())}}var _B,Whe,TB=B(()=>{"use strict";_B=Xe(eS()),Whe=Xe(ZC());});var TS,OB=B(()=>{"use strict";F0();TS=Fp({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 PB,RB,kB,$B,OS,zhe,ny,DB,DS=B(()=>{"use strict";PB=Xe(ZC()),RB=Xe(q1()),kB=Xe(eS()),$B=Xe(sq()),OS=Xe(NB());nm();TB();OB();zhe=60*1e3,ny=class{clientName;logger;ecsEndpoint;resolveLoadingPromise;loadingPromise=new Promise(t=>this.resolveLoadingPromise=t);_status=eo.NotLoaded;endpointType;clientConfigOverride;get status(){return this._status}constructor(t,n,r="PROD"){this.clientName=t,this.logger=n,this.endpointType=r,this.ecsEndpoint=r==="PROD"?TS.prodEcsEndpoint:TS.integrationEcsEndpoint}client=new RB.default;init=async({clientVersion:t,getFilters:n,cacheStorage:r=PB.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 n();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:[kB.EcsConfigType.Default],hosts:[this.ecsEndpoint],initialAppActiveState:!0,getEcsParameters:a,databaseInterface:IB(this.clientName,r,this.endpointType),...o}),this.client.requestUpdate(),this._status===eo.NotLoaded&&(this._status=eo.Initialized)}catch(s){this._status=eo.Error,this.resolveLoadingPromise(),this.logEvent("FeaturesClient/initializationFailed",{ecsClientName:this.clientName,error:s},"Error")}i&&window.setInterval(()=>this.client.requestUpdate(),i*zhe)};getConfig=t=>{let n=this.getMergedClientConfigByTeamName(t.teamName),r=n?t.extractConfig(n):{};return(0,OS.default)({},t.fallback,r,t.override,DB)};getAllConfigs=()=>this.getMergedClientConfig();getAllConfigsByTeamName=t=>this.getMergedClientConfigByTeamName(t);requestConfigUpdate=()=>{this.client.requestUpdate()};subscribe=(t,n)=>{let r=this.getConfig(t),i=this.client.configUpdated.subscribe(()=>{let o=this.getConfig(t);(0,$B.default)(o,r)||(r={...o},n(o))});return{unsubscribe:()=>i.unsubscribe()}};waitUntilLoaded=async t=>{if(t!==void 0){let n,r=new Promise((i,o)=>{n=window.setTimeout(()=>{o(new Error("Timed out waiting for configuration to load"))},t)});await Promise.race([this.loadingPromise,r]),clearTimeout(n)}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,OS.default)({},this.client.getConfig()?.config,this.clientConfigOverride,DB);getMergedClientConfigByTeamName=t=>this.getMergedClientConfig()?.[t];handleConfigUpdated=()=>{let t=this.client.getConfig();if(t===void 0)return;this.resolveLoadingPromise(),this._status=eo.ConfigsLoaded;let{ConfigIDs:n,Headers:r}=t.config;this.logEvent("FeaturesClient/configUpdated",{ecsClientName:this.clientName,configIDs:n,ETag:r?.ETag})};logEvent=(t,n)=>{this.logger.logEvent(t,{ecsClientName:this.clientName,ecsEndpointType:this.endpointType,...n})}},DB=(e,t)=>{if(Array.isArray(t))return t}});var MB=C((Wke,LB)=>{"use strict";var Hhe=()=>{let e={};return e.promise=new Promise((t,n)=>{e.resolve=t,e.reject=n}),e};LB.exports=Hhe});var PS=C((zke,FB)=>{var rm=new Proxy(function(){return rm},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:rm},apply:function(){return rm},construct:function(){return{}}}),xB=function(){return rm};Object.setPrototypeOf(xB,rm);FB.exports=xB});var BB=C((Hke,qB)=>{var im=new Proxy(function(){return im},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:im},apply:function(){return im},construct:function(){return{}}}),UB=function(){return im};Object.setPrototypeOf(UB,im);qB.exports=UB});var KB=C((Kke,HB)=>{"use strict";var RS=BB(),Khe={childContextTypes:!0,contextType:!0,contextTypes:!0,defaultProps:!0,displayName:!0,getDefaultProps:!0,getDerivedStateFromError:!0,getDerivedStateFromProps:!0,mixins:!0,propTypes:!0,type:!0},Jhe={name:!0,length:!0,prototype:!0,caller:!0,callee:!0,arguments:!0,arity:!0},Yhe={$$typeof:!0,render:!0,defaultProps:!0,displayName:!0,propTypes:!0},WB={$$typeof:!0,compare:!0,defaultProps:!0,displayName:!0,propTypes:!0,type:!0},kS={};kS[RS.ForwardRef]=Yhe;kS[RS.Memo]=WB;function VB(e){return RS.isMemo(e)?WB:kS[e.$$typeof]||Khe}var Qhe=Object.defineProperty,Xhe=Object.getOwnPropertyNames,GB=Object.getOwnPropertySymbols,Zhe=Object.getOwnPropertyDescriptor,ege=Object.getPrototypeOf,jB=Object.prototype;function zB(e,t,n){if(typeof t!="string"){if(jB){var r=ege(t);r&&r!==jB&&zB(e,r,n)}var i=Xhe(t);GB&&(i=i.concat(GB(t)));for(var o=VB(e),a=VB(t),s=0;s<i.length;++s){var u=i[s];if(!Jhe[u]&&!(n&&n[u])&&!(a&&a[u])&&!(o&&o[u])){var l=Zhe(t,u);try{Qhe(e,u,l)}catch{}}}}return e}HB.exports=zB});function YB(e,t,n){let[r,i]=(0,hd.useState)(e.getConfig(t));return(0,hd.useEffect)(()=>{if(!n?.subscribe&&e.status===eo.ConfigsLoaded)return;let o=e.subscribe(t,a=>{i(a),n?.subscribe||o.unsubscribe()});return o?.unsubscribe},[]),r}function QB(e){return function(t,n){return YB(e,t,n)}}function XB(e,t,n,r){let i=o=>{let a=YB(e,t,r),s={...o,...a};return hd.default.createElement(n,{...s})};return(0,JB.default)(i,n),i.displayName=`WithFeature(${n.name})`,i}function ZB(e,t,n,r){return t.reduce((i,o)=>XB(e,o,i,r),n)}function eV(e){return function(t,n,r){return XB(e,t,n,r)}}var JB,hd,$S=B(()=>{"use strict";JB=Xe(KB()),hd=Xe(PS());nm();});var nV=C((Qke,tV)=>{var tge=NS(),nge=IS(),rge=nge(function(e,t,n){tge(e,t,n)});tV.exports=rge});var ry=C((Xke,rV)=>{var ige=Sl(),oge=fu(),age="[object Symbol]";function sge(e){return typeof e=="symbol"||oge(e)&&ige(e)==age}rV.exports=sge});var oV=C((Zke,iV)=>{var uge=du(),lge=ry(),cge=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,dge=/^\w*$/;function fge(e,t){if(uge(e))return!1;var n=typeof e;return n=="number"||n=="symbol"||n=="boolean"||e==null||lge(e)?!0:dge.test(e)||!cge.test(e)||t!=null&&e in Object(t)}iV.exports=fge});var uV=C((e$e,sV)=>{var aV=K0(),pge="Expected a function";function LS(e,t){if(typeof e!="function"||t!=null&&typeof t!="function")throw new TypeError(pge);var n=function(){var r=arguments,i=t?t.apply(this,r):r[0],o=n.cache;if(o.has(i))return o.get(i);var a=e.apply(this,r);return n.cache=o.set(i,a)||o,a};return n.cache=new(LS.Cache||aV),n}LS.Cache=aV;sV.exports=LS});var cV=C((t$e,lV)=>{var mge=uV(),hge=500;function gge(e){var t=mge(e,function(r){return n.size===hge&&n.clear(),r}),n=t.cache;return t}lV.exports=gge});var fV=C((n$e,dV)=>{var yge=cV(),bge=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,vge=/\\(\\)?/g,wge=yge(function(e){var t=[];return e.charCodeAt(0)===46&&t.push(""),e.replace(bge,function(n,r,i,o){t.push(i?o.replace(vge,"$1"):r||n)}),t});dV.exports=wge});var mV=C((r$e,pV)=>{function Ege(e,t){for(var n=-1,r=e==null?0:e.length,i=Array(r);++n<r;)i[n]=t(e[n],n,e);return i}pV.exports=Ege});var wV=C((i$e,vV)=>{var hV=Hp(),Age=mV(),Cge=du(),Sge=ry(),Nge=1/0,gV=hV?hV.prototype:void 0,yV=gV?gV.toString:void 0;function bV(e){if(typeof e=="string")return e;if(Cge(e))return Age(e,bV)+"";if(Sge(e))return yV?yV.call(e):"";var t=e+"";return t=="0"&&1/e==-Nge?"-0":t}vV.exports=bV});var AV=C((o$e,EV)=>{var _ge=wV();function Ige(e){return e==null?"":_ge(e)}EV.exports=Ige});var SV=C((a$e,CV)=>{var Tge=du(),Oge=oV(),Dge=fV(),Pge=AV();function Rge(e,t){return Tge(e)?e:Oge(e,t)?[e]:Dge(Pge(e))}CV.exports=Rge});var _V=C((s$e,NV)=>{var kge=ry(),$ge=1/0;function Lge(e){if(typeof e=="string"||kge(e))return e;var t=e+"";return t=="0"&&1/e==-$ge?"-0":t}NV.exports=Lge});var OV=C((u$e,TV)=>{var Mge=CS(),xge=SV(),Fge=Q0(),IV=ds(),Uge=_V();function qge(e,t,n,r){if(!IV(e))return e;t=xge(t,e);for(var i=-1,o=t.length,a=o-1,s=e;s!=null&&++i<o;){var u=Uge(t[i]),l=n;if(u==="__proto__"||u==="constructor"||u==="prototype")return e;if(i!=a){var c=s[u];l=r?r(c,u,s):void 0,l===void 0&&(l=IV(c)?c:Fge(t[i+1])?[]:{})}Mge(s,u,l),s=s[u]}return e}TV.exports=qge});var PV=C((l$e,DV)=>{var Bge=OV();function Vge(e,t,n){return e==null?e:Bge(e,t,n)}DV.exports=Vge});function LV(e){let{query:t}=(0,$V.default)(window.location.href,!0);return jge(e,t),e}function jge(e,t){let n=Gge+e.clientName,r=Object.keys(t).filter(o=>o.startsWith(n));if(!r)return;let i={};r.forEach(o=>{let a=t[o];if(a)try{let s=JSON.parse(a),u=n+MV,l={};if(o===n)l=s;else if(o.startsWith(u)){let c=o.substring(u.length);(0,kV.default)(l,c,s)}(0,RV.default)(i,l)}catch{}}),Object.keys(i).length>0&&e.overrideClientConfig(i)}var RV,kV,$V,MV,Gge,xV=B(()=>{"use strict";RV=Xe(nV()),kV=Xe(PV()),$V=Xe(BC());MV=".",Gge="ecs"+MV});function oy(e,t,n){let r=LV(new ny(e,t,n));function i(o){(0,iy.useEffect)(()=>{r.init(o)},[])}return{featuresClient:r,createFeature:zge(r),useFeaturesClientInitParams:i,withFeatures:(o,a,s)=>ZB(r,o,a,s)}}function zge(e){let t=QB(e),n=eV(e);return function(i){let o=L1(i);return o.getConfig=()=>e.getConfig(o),o.isLoaded=()=>e.status===eo.ConfigsLoaded,jC.register(o,e.clientName),{useFeature:a=>t(o,a),withFeature:(a,s)=>n(o,a,s),feature:o}}}var Wge,iy,MS=B(()=>{"use strict";Wge=Xe(MB()),iy=Xe(PS());XC();DS();nm();$S();xV();WC();});var FV=B(()=>{"use strict";XC();DS();MS();nm();$S();V0();zC();});function ay(e){return{logEvent:(t,n,r)=>{switch(r){case"Error":(0,gd.trackErrorTrace)(e,{eventName:t,eventData:n});break;case"Warning":(0,gd.trackWarningTrace)(e,{eventName:t,eventData:n});break;default:(0,gd.trackInfoTrace)(e,{eventName:t,eventData:n});break}}}}var gd,xS=B(()=>{"use strict";gd=Xe(vl());});var O$e,D$e,P$e,UV=B(()=>{"use strict";FV();xS();({featuresClient:O$e,createFeature:D$e,useFeaturesClientInitParams:P$e}=oy("PowerApps-Shell-Test",ay("shell-features")))});var VV=C((k$e,BV)=>{var om=new Proxy(function(){return om},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:om},apply:function(){return om},construct:function(){return{}}}),qV=function(){return om};Object.setPrototypeOf(qV,om);BV.exports=qV});var Hge,Kge,GV=B(()=>{"use strict";Lp();Hge=Xe(VV()),Kge=Xe(vl());});var jV=B(()=>{"use strict";UV();xS();GV();});var V$e,yd,G$e,WV=B(()=>{"use strict";jV();MS();({featuresClient:V$e,createFeature:yd,useFeaturesClientInitParams:G$e}=oy("PowerApps-MakerPortal",ay("powerapps-features")))});var zV,HV,H$e,K$e,J$e,Y$e,FS=B(()=>{"use strict";$1();WV();({feature:zV}=yd({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:od.enableAutoInsertionOfCellInRow}})),{feature:HV}=yd({teamName:"MakerPortal",owners:["aansu"],description:"Enable the one grid events for form designer",createdOn:"08/21/2024",fallback:{enableOneGridEventsForFormDesigner:od.enableOneGridEvents}}),{feature:H$e}=yd({teamName:"MakerPortal",owners:["adekulkarni"],description:"Disables PBI components and cleans them up from the form",createdOn:"01/03/2023",fallback:{enableFallbackFormTemplate:od.disablePBIComponents}}),{feature:K$e}=yd({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:od.enableAgentResponse}}),{feature:J$e,useFeature:Y$e}=yd({teamName:"MakerPortal",owners:["aansu"],description:"Enables delayed localization of custom control",createdOn:"06/08/2025",fallback:{enableDelayedLocalizationForCustomControls:od.enableDelayedLocalizationForCustomControls}})});var YV=C((X$e,JV)=>{var am=new Proxy(function(){return am},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:am},apply:function(){return am},construct:function(){return{}}}),KV=function(){return am};Object.setPrototypeOf(KV,am);JV.exports=KV});var Nr,pu=B(()=>{"use strict";Dn();En();Sr();Bp();Re();Jn();Nr=class extends Se{static HighestUsedIndexByClass=new Map;get colspan(){let t=this.getProperty(A.colspan);return F.IsNullOrUndefined(t)?null:parseInt(t,10)}set colspan(t){F.IsNullOrUndefined(t)||this.setProperty(A.colspan,String(t))}constructor(t,n){super(t,n)}get id(){let t=this.getProperty(A.id);return t==null?null:t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"?new H(t.substr(1,t.length-2)):new H(t)}set id(t){this.setProperty(A.id,`{${t.ToString()}}`)}set labelId(t){this.setProperty(A.labelId,`{${t.ToString()}}`)}get labelId(){let t=this.getProperty(A.labelId);return t&&t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"?new H(t.substr(1,t.length-2)):new H(t)}get Name(){return this.getProperty(A.Name)}set Name(t){this.setProperty(A.Name,t)}setDisplayName(t,n){for(let i of this.getAllLabels())if(+i.getProperty(A.languagecode)===n){i.setProperty(A.description,t);return}let r=new Se(D.formLabel,null);r.setProperty(A.description,t),r.setProperty(A.languagecode,String(n)),this.addGrandChild("labels",r)}getDisplayName(t){for(let n of this.getAllLabels())if(+n.getProperty(A.languagecode)===t)return n.getProperty(A.description)}getAllLabels(){let t=this.getChildren("labels");return t.length!==1?[]:t[0].getChildren("label")}get isLocked(){return+this.getProperty(A.locklevel)==1}set isLocked(t){!this.IsUnboundControl&&this.setProperty(A.locklevel,t?"1":"0")}get availableforphone(){return this.getProcessedValue(A.availableforphone)}set availableforphone(t){F.IsNullOrUndefined(t)||!this.IsAllowedUBCForAvailableOnPhone()||this.setProperty(A.availableforphone,String(t))}get visible(){return this.getProcessedValue(A.visible)}set visible(t){F.IsNullOrUndefined(t)||!this.IsAllowedUBCForVisibleByDefault()||this.setProperty(A.visible,String(t))}isLockLevelSettable(){return!this.IsUnboundControl}get showlabel(){return this.getProcessedValue(A.showlabel)}set showlabel(t){F.IsNullOrUndefined(t)||this.setProperty(A.showlabel,String(t))}isAvailableForPhoneSettable(){return this.IsAllowedUBCForAvailableOnPhone()}isVisibleSettable(){return this.IsAllowedUBCForVisibleByDefault()}getProcessedValue(t){let n=this.getProperty(t);return F.IsNullOrUndefined(n)||this.getProperty(t)==="true"}get readonly(){let t=this.getFirstChild(D.formControl);return t?t.disabled:!1}set readonly(t){let n=this.getFirstChild(D.formControl);n&&(n.disabled=t)}get allowfilteroff(){let t=this.getFirstChild(D.formControl);if(t)return t.getParam(A.AllowFilterOff)==="true"}set allowfilteroff(t){let n=this.getFirstChild(D.formControl);n&&!this.IsUnboundControl&&n.setParameter(A.AllowFilterOff,t)}get autoresolve(){let t=this.getFirstChild(D.formControl);if(t)return t.getParam(A.AutoResolve)==="true"}set autoresolve(t){let n=this.getFirstChild(D.formControl);n&&!this.IsUnboundControl&&n.setParameter(A.AutoResolve,t)}get defaultviewid(){let t=this.getFirstChild(D.formControl);return t?t.getParam(A.DefaultViewId):Q.EmptyString}set defaultviewid(t){let n=this.getFirstChild(D.formControl);n&&!this.IsUnboundControl&&n.setParameter(A.DefaultViewId,t)}get dependentattributename(){let t=this.getFirstChild(D.formControl);return t?t.getParam(A.DependentAttributeName):Q.EmptyString}set dependentattributename(t){let n=this.getFirstChild(D.formControl);n&&!this.IsUnboundControl&&n.setParameter(A.DependentAttributeName,t)}get dependentattributetype(){let t=this.getFirstChild(D.formControl);return t?t.getParam(A.DependentAttributeType):Q.EmptyString}set dependentattributetype(t){let n=this.getFirstChild(D.formControl);n&&!this.IsUnboundControl&&n.setParameter(A.DependentAttributeType,t)}get disablequickfind(){let t=this.getFirstChild(D.formControl);if(t)return t.getParam(A.DisableQuickFind)==="true"}set disablequickfind(t){let n=this.getFirstChild(D.formControl);n&&!this.IsUnboundControl&&n.setParameter(A.DisableQuickFind,t)}get disableviewpicker(){let t=this.getFirstChild(D.formControl);if(t)return t.getParam(A.DisableViewPicker)==="true"}set disableviewpicker(t){let n=this.getFirstChild(D.formControl);n&&!this.IsUnboundControl&&n.setParameter(A.DisableViewPicker,t)}get filterrelationshipname(){let t=this.getFirstChild(D.formControl);return t?t.getParam(A.FilterRelationshipName):Q.EmptyString}set filterrelationshipname(t){let n=this.getFirstChild(D.formControl);n&&!this.IsUnboundControl&&n.setParameter(A.FilterRelationshipName,t)}get availableviewids(){let t=this.getFirstChild(D.formControl);return t?t.getParam(A.AvailableViewIds):Q.EmptyString}set availableviewids(t){let n=this.getFirstChild(D.formControl);n&&!this.IsUnboundControl&&n.setParameter(A.AvailableViewIds,t)}get IsUnboundControl(){let t=this.getFirstChild(D.formControl);if(t&&t.ClassId){let n=An.getUniqueIdentifierForControl(t);return!F.IsNullOrUndefined(n)&&An.isUnboundFormControlByIdentifier(n)}else return!1}IsAllowedUBCForAvailableOnPhone(){let t=this.getFirstChild(D.formControl);if(t){let r=An.getUniqueIdentifierForControl(t).guidString,i=r===te.GridControl||r===te.TimeLineControl||r===te.TimeLineControlUC;return this.IsUnboundControl?i:!0}return this.NodeName===D.formSection||this.NodeName===D.formTab}IsAllowedUBCForVisibleByDefault(){let t=this.getFirstChild(D.formControl);if(t){let r=An.getUniqueIdentifierForControl(t).guidString,i=r===te.MapsControl||r===te.WebResourceHtmlControl||r===te.WebResourceImageControl||r===te.IframeControl||r===te.SocialInsightControl;return this.IsUnboundControl?i:!0}else return!0}get events(){let t=this.getChildren(D.formEvents);return t.length===1?t[0].getAllChildren():[]}addEvent(t){this.addGrandChild(D.formEvents,t)}getUsedNodeNameSet(t){return null}getHighestIndexById(t,n){return null}}});var bd,US=B(()=>{"use strict";Sr();Re();Jn();bd=class extends Se{constructor(t,n){super(D.dependency,t),Q.IsNullOrEmpty(n)||this.setDefaultProperties(n)}set id(t){this.setProperty(A.id,t)}get id(){return this.getProperty(A.id)}setDefaultProperties(t){this.id=t}}});var QV,vd,qS=B(()=>{"use strict";En();US();Re();Jn();pu();(function(e){e[e.Form=0]="Form",e[e.Cell=1]="Cell",e[e.Tab=2]="Tab",e[e.Control=3]="Control"})(QV||(QV={}));vd=class extends Nr{constructor(t,n){super(D.formEvent,t),n&&(this.eventName=n,this.application="false",this.active="false")}set eventName(t){this.setProperty(A.Name,t)}get eventName(){return this.getProperty(A.Name)}set application(t){this.setProperty(A.application,t)}get application(){return this.getProperty(A.application)}set attribute(t){this.setProperty(A.EventAttribute,t)}get attribute(){return this.getProperty(A.EventAttribute)}set relationship(t){this.setProperty(A.Relationship,t)}get relationship(){return this.getProperty(A.Relationship)}set control(t){this.setProperty(A.Control,t)}get control(){return this.getProperty(A.Control)}set active(t){this.setProperty(A.EventActive,t)}get active(){return this.getProperty(A.EventActive)}getAllHandlers(){let t=this.getChildren(D.EventHandlers);return t&&t.length?t[0].getChildren(D.handler):[]}getAllDependencies(){let t=this.getChildren(D.formDependencies);return t.length===0?[]:t[0].getAllChildren()}setDependencies(t){let n=this.getFirstChild(D.formDependencies);if(F.IsNullOrUndefined(n)){if(t.length===0)return;this.addChild(new Se(D.formDependencies,this)),n=this.getFirstChild(D.formDependencies)}if(t.length===0)n.getParentNode().deleteChild(n);else{n.deleteAllChildren();for(let r of t)n.addChild(new bd(n,r.toString()))}}}});var Do,sm=B(()=>{"use strict";Dn();bp();En();bl();Re();Jn();Io();Do=class extends Se{previewVersion;constructor(t){super(D.formControl,t)}updatePreview(){this.previewVersion=Date.now()}get ClassId(){let t=this.getProperty(A.classid);return t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"&&(t=t.substr(1,t.length-2)),new H(t)}set ClassId(t){this.setProperty(A.classid,`{${t.ToString()}}`)}get dataFieldName(){return this.getProperty(A.datafieldname)}set dataFieldName(t){this.setProperty(A.datafieldname,t)}set id(t){this.setProperty(A.id,t)}get id(){return this.getProperty(A.id)}get UniqueId(){let t=this.getProperty(A.uniqueid);return F.IsNullOrUndefined(t)?null:(t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"&&(t=t.substr(1,t.length-2)),new H(t))}set UniqueId(t){this.setProperty(A.uniqueid,`{${t.ToString()}}`)}get isRequired(){return this.getProperty(A.isRequired)==="true"}set isRequired(t){F.IsNullOrUndefined(t)||this.setProperty(A.isRequired,String(t))}get disableMru(){return this.getParam(A.DisableMru)==="true"}set disableMru(t){F.IsNullOrUndefined(t)||this.setParameter(A.DisableMru,t)}get useMFDForCreate(){return this.getParam(A.UseMFDForCreate)==="true"}set useMFDForCreate(t){F.IsNullOrUndefined(t)||this.setParameter(A.UseMFDForCreate,t)}get useMFDForEdit(){return this.getParam(A.UseMFDForEdit)==="true"}set useMFDForEdit(t){F.IsNullOrUndefined(t)||this.setParameter(A.UseMFDForEdit,t)}get disabled(){return this.getProperty(A.disabled)==="true"}set disabled(t){F.IsNullOrUndefined(t)||this.setProperty(A.disabled,String(t))}get indicationOfSubgrid(){return this.getProperty(A.indicationOfSubgrid)==="true"}set indicationOfSubgrid(t){this.setProperty(A.indicationOfSubgrid,String(t))}getAllParameters(){let t=new qr,n=this.getFirstChild(A.parameters);return n&&n.getAllChildren().forEach(r=>{if(r){let i=r.getAllChildren(),o=i&&i.length>0&&i[0];o&&t.add(r.getNodeName(),o.getNodeName())}}),t}setParameter(t,n){let r=!1;n===null&&(r=!0);let i=(cs.StartTag+n).toString(),o=this.parametersNode;if(o){let a=o.findFirst(s=>s&&s.getNodeName()===t);if(a)if(r){this.deleteFirstGrandChildOfName(D.controlParameters,a);return}else{let s=a.getAllChildren();s&&s.length>0&&s[0]?s[0].setNodeName(i):a.addChild(new Se(i,a))}else r||(a=new Se(t,o),a.addChild(new Se(i,a)),o.addChild(a))}else if(!r){o=new Se("parameters",this);let a=new Se(t,o);a.addChild(new Se(i,a)),o.addChild(a),this.addChild(o)}}getParam(t){if(this.parametersNode){let n=this.parametersNode.findFirst(r=>r&&r.getNodeName()===t);if(n){let r=n.getAllChildren(),i=r&&r.length>0&&r[0];if(i){let o=i.getNodeName();return o.charAt(0)===cs.StartTag?o.substring(1):o}}}return null}get parametersNode(){let t=this.getChildren(A.parameters);return t.length===0?null:t[0]}async serializeParameters(t,n){let r=new qr;switch(this.ClassId.guidString.toUpperCase()){case k.LookupControl:if(t&&t.getKeys())if(t.getKeys().forEach(a=>{r.add(a,this.getParam(a))}),t&&t.containsKey("DefaultViewId")){let a=this.getParam("DefaultViewId").replace("{","").replace("}","");r.upsert("DefaultViewId",a)}else{let a=this.getParent(),s=await n.formModelService.lookupControlService.populateDefaultView(this,a.getParentForm().entityName);s&&s.id&&r.upsert("DefaultViewId",s.id.replace("{","").replace("}",""))}break;default:t&&t.getKeys()&&t.getKeys().forEach(a=>{r.add(a,this.getParam(a))});break}let i=r.getInternalObject(),o=[];for(let a in i)i.hasOwnProperty(a)&&o.push({Name:a,Value:i[a]});return o}getIsUnbound(){return this.getProperty(A.isUnbound)==="true"}getAttributeTypeFromClassId(t){if(t)switch(t.toUpperCase()){case k.BooleanControl:case k.CheckboxControl:return 0;case k.DateTimeControl:return 2;case k.DecimalControl:return 3;case k.FloatingNumberControl:return 4;case k.IntegerControl:case k.DurationControl:case k.LanguageControl:case k.TimezoneControl:return 5;case k.LookupControl:return 6;case k.CurrencyControl:return 8;case k.PartyListControl:return 10;case k.ChoiceControl:case k.RelationshipRoleChoiceControl:return 11;case k.ChoiceStatusControl:return 13;case k.TextAreaControl:case k.TextboxControl:case k.LabelControl:case k.EmailAddressControl:case k.UrlControl:case k.TickerControl:case k.ButtonControl:case k.PhoneNumberControl:return 14;case k.ChoicesControl:return 24;default:return}return 14}async toJSON(t){let n=this.getParent(),r=t&&t.formModelService&&t.formModelService.getFormType()===Pn.QuickViewForm?!0:this.disabled,i=await this.serializeParameters(this.getAllParameters(),t);return{ClassId:this.ClassId&&this.ClassId.guidString,Parameters:i,Disabled:r,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:n.getDisplayName(t.langCode),LabelId:n.labelId&&n.labelId.guidString,Name:null,ShowLabel:n.showlabel,PreviewId:n&&n.id.guidString,Visible:n.visible||t.formModelService.showHiddenElements}}}});var wd,BS=B(()=>{"use strict";Sr();cl();sm();Re();Jn();wd=class extends Do{constructor(t){super(t)}get targetEntityType(){return this.getParam(A.targetEntityType)||Q.EmptyString}set targetEntityType(t){this.setParameter(A.targetEntityType,t)}get viewId(){return Q.StripBraces(this.getParam(A.viewId))||Q.EmptyString}set viewId(t){this.setParameter(A.viewId,Q.AddBraces(t))}get viewIds(){return this.getParam(A.viewIds)||Q.EmptyString}set viewIds(t){this.setParameter(A.viewIds,t)}get relationshipName(){return this.getParam(A.RelationshipName)||Q.EmptyString}set relationshipName(t){this.setParameter(A.RelationshipName,t)}get isUserView(){return Q.IsStrictTrue(this.getParam(A.isUserView))}set isUserView(t){this.setParameter(A.isUserView,t.toString())}get enableViewPicker(){return Q.IsStrictTrue(this.getParam(A.enableViewPicker))}set enableViewPicker(t){this.setParameter(A.enableViewPicker,t)}get autoExpand(){return this.getParent().autoexpand&&this.getParam(A.autoExpand)===A.Auto}set autoExpand(t){let n=this.getParent();this.setParameter(A.autoExpand,t?A.Auto:A.Fixed),n.autoexpand=t}get recordsPerPage(){return this.getParam(A.recordsPerPage)?Number(this.getParam(A.recordsPerPage)):Number(A.RecordsPerPageRAControlDefault)}set recordsPerPage(t){this.setParameter(A.recordsPerPage,String(t))}get enableQuickFind(){return Q.IsStrictTrue(this.getParam(A.enableQuickFind))}set enableQuickFind(t){this.setParameter(A.enableQuickFind,t)}get teamTemplateId(){return Q.StripBraces(this.getParam(A.teamTemplateId))||Q.EmptyString}set teamTemplateId(t){this.setParameter(A.teamTemplateId,Q.AddBraces(t))}get chartId(){return this.getParam(A.visualizationId)||Q.EmptyString}set chartId(t){this.setParameter(A.visualizationId,t)}get enableChartPicker(){return Q.IsStrictTrue(this.getParam(A.enableChartPicker))}set enableChartPicker(t){this.setParameter(A.enableChartPicker,t)}get chartGridMode(){switch(this.getParam(A.chartGridMode)){case Zi.Chart:return Zi.Chart;case Zi.Grid:return Zi.Grid;default:return Zi.All}}set chartGridMode(t){this.setParameter(A.chartGridMode,t)}updateChartGridMode(t){t?this.chartGridMode=Zi.Chart:this.chartGridMode=this.enableChartPicker?Zi.All:Zi.Grid}updateDefaultProperties(t,n){for(let r of t)switch(r.getNodeName()){case A.targetEntityType:r.getAllChildren()[0].setNodeName("<"+n.targetEntityType);break;case A.viewId:r.getAllChildren()[0].setNodeName("<"+Q.AddBraces(n.viewId));break;case A.isUserView:r.getAllChildren()[0].setNodeName("<"+n.isUserView);break;case A.enableViewPicker:r.getAllChildren()[0].setNodeName("<"+n.enableViewPicker);break;case A.RelationshipName:let i=r.getAllChildren(),o="<"+n.relationshipName;i.length?r.getAllChildren()[0].setNodeName(o):r.addChild(new Se(o,r));break;default:break}}updateControlDescription(t){let n=t.getControlDescriptionByForControl(this.UniqueId);if(n){let r=n.customControls;for(let i=0;i<r.length;i++){let o=r[i].getParameters().get(vr.dataset)?r[i].getParameters().get(vr.dataset)[0]:null;if(o){let a=o.getAllChildren();this.updateDefaultProperties(a,this)}else{let a=r[i].getAllChildren()[0].getAllChildren();this.updateDefaultProperties(a,this)}}}}}});var Ed,VS=B(()=>{"use strict";Sr();cl();sm();Re();Ed=class extends Do{constructor(t){super(t)}get defaultViewId(){return Q.StripBraces(this.getParam(A.DefaultViewId))||Q.EmptyString}set defaultViewId(t){this.setParameter(A.DefaultViewId,Q.AddBraces(t))}get autoResolve(){return Q.IsStrictTrue(this.getParam(A.AutoResolve))}set autoResolve(t){this.setParameter(A.AutoResolve,t)}get disableQuickFind(){return Q.IsStrictTrue(this.getParam(A.DisableQuickFind))}set disableQuickFind(t){this.setParameter(A.DisableQuickFind,t)}get disableViewPicker(){return Q.IsStrictTrue(this.getParam(A.DisableViewPicker))}set disableViewPicker(t){this.setParameter(A.DisableViewPicker,t)}get allowFilterOff(){return Q.IsStrictTrue(this.getParam(A.AllowFilterOff))}set allowFilterOff(t){this.setParameter(A.AllowFilterOff,t)}get disableMru(){return Q.IsStrictTrue(this.getParam(A.DisableMru))}set disableMru(t){this.setParameter(A.DisableMru,t)}get dependentAttributeName(){return this.getParam(A.DependentAttributeName)||Q.EmptyString}set dependentAttributeName(t){this.setParameter(A.DependentAttributeName,t)}get dependentAttributeType(){return this.getParam(A.DependentAttributeType)||Q.EmptyString}set dependentAttributeType(t){this.setParameter(A.DependentAttributeType,t)}get filterRelationshipName(){return this.getParam(A.FilterRelationshipName)||Q.EmptyString}set filterRelationshipName(t){this.setParameter(A.FilterRelationshipName,t)}get availableViewIds(){return this.getParam(A.AvailableViewIds)||Q.EmptyString}set availableViewIds(t){this.setParameter(A.AvailableViewIds,t)}updateDefaultProperties(t,n){for(let r of t)switch(r.getNodeName()){case A.datafieldname:case A.bindAttribute:r.getAllChildren()[0].setNodeName("<"+n.dataFieldName);break;case A.DefaultViewId:r.getAllChildren()[0].setNodeName("<"+Q.AddBraces(n.defaultViewId));break;case A.AllowFilterOff:r.getAllChildren()[0].setNodeName("<"+n.allowFilterOff);break;case A.DisableQuickFind:r.getAllChildren()[0].setNodeName("<"+n.disableQuickFind);break;case A.DisableViewPicker:r.getAllChildren()[0].setNodeName("<"+n.disableViewPicker);break;case A.FilterRelationshipName:r.getAllChildren()[0].setNodeName("<"+n.filterRelationshipName);break;case A.DependentAttributeName:r.getAllChildren()[0].setNodeName("<"+n.dependentAttributeName);break;case A.DependentAttributeType:r.getAllChildren()[0].setNodeName("<"+n.dependentAttributeType);break;case A.AvailableViewIds:r.getAllChildren()[0].setNodeName("<"+n.availableViewIds);break;case A.DisableMru:r.getAllChildren()[0].setNodeName("<"+n.disableMru);break;case A.AutoResolve:r.getAllChildren()[0].setNodeName("<"+n.autoResolve);break;default:break}}updateControlDescription(t){let n=t.getControlDescriptionByForControl(this.UniqueId);if(n){let r=n.customControls;for(let i=0;i<r.length;i++){let o=r[i].getParameters().get(vr.value)?r[i].getParameters().get(vr.value)[0]:null;if(o){let a=o.getAllChildren();this.updateDefaultProperties(a,this)}else{let a=r[i].getAllChildren()[0].getAllChildren();this.updateDefaultProperties(a,this)}}}}}});var XV,GS,gi,um=B(()=>{"use strict";XV=Xe(YV());pu();Re();En();Dn();qS();sm();Bp();YC();PC();Io();bl();td();BS();VS();jS();xc();GS="_",gi=class e extends Nr{fieldPlaceholder;fieldRequiredLevel;isNewField;cellColType;dependentFields=[];constructor(t){super(D.formCell,t),this.isNewField=!1}get cellType(){return this.cellColType}set cellType(t){this.cellColType=t}setDefaultProperties(t){this.showlabel=t,this.isLocked=!1,F.IsNullOrUndefined(this.getProperty(A.id))&&(this.id=new H(H.NewGuid()))}addControl(t,n,r,i,o,a,s){r instanceof Do?this.addChild(r):r instanceof H&&this.addChild(this.getControlWithControlSpecificProperties(t,n,r,i,o,a,s))}removeControl(){return this.deleteChild(this.control)>=0}get isIndependent(){if(!F.IsNullOrUndefined(this.control))return F.IsNullOrUndefined(this.control.dataFieldName)?F.IsNullOrUndefined(this.control.id)?!0:!wl.dependencyFieldCount.containsKey(this.control.id):!wl.dependencyFieldCount.containsKey(this.control.dataFieldName)}createOnLoadEvent(){this.addEvent(new vd(this,kp.onLoad))}get dependencies(){let t=this.getChildren(D.formEvents);for(let n of t){let r=n.getChildren(D.formEvent);for(let i of r)this.buildDependencyList(i,this.dependentFields)}return this.dependentFields}getNextAvailableControlName(t,n,r,i){let o;if(i&&k0[i])o=k0[i].replace(/ /g,GS)+GS;else{o="Control_";let l=new Error("Control class id does not exist or is undefined");(0,XV.trackErrorTrace)(Vr,{eventName:`${Y2}/getNextAvailableControlName`},l)}let a="new_",s=this.getHighestIndexById(t,i)+1,u=`${o}${a}${s}`;for(;r.has(u);)s++,u=`${o}${a}${s}`;return u}getUnboundControlProperties(t){e.prototype.setProperty.call(t,A.isUnbound,"true"),e.prototype.setProperty.call(t,A.isRequired,"false")}getControlWithControlSpecificProperties(t,n,r,i,o,a,s){let u;o===to.Grid?(u=new wd(this),u.indicationOfSubgrid=!0):o===to.Lookup?u=new Ed(this):u=new Do(this);let l=r.guidString,c=a||this.getNextAvailableControlName(t,i,this.getUsedNodeNameSet(t),l);if(e.prototype.setProperty.call(u,A.id,c),u.ClassId=r,!F.IsNullOrUndefined(s)&&(u.UniqueId=s),!a&&n)this.getUnboundControlProperties(u);else{let d=An.getUniqueIdentifierForControl(u);F.IsNullOrUndefined(d)||(An.getControlDataTypeByControlOrUniqueId(d)===be.QuickFormCollectionControl||!An.isUnboundFormControlByIdentifier(d)?o!==to.Grid&&a&&l!==k.IframeControl&&l!==k.SubgridControl&&l!==k.ReferencePanelSubgridControl&&(u.dataFieldName=a,e.prototype.setProperty.call(u,A.disabled,"false")):(this.rowspan=An.GetRowSpan(u),(An.getControlDataTypeByControlOrUniqueId(d)===be.NotesControl||An.getControlDataTypeByControlOrUniqueId(d)===be.TimeLineControl)&&(e.prototype.setProperty.call(u,A.disabled,"false"),u.id=be.NotesControl)),(An.getUnboundControlNameFromIdentifier(r)===be.SubGridControl||An.getUnboundControlNameFromIdentifier(r)===be.NotesControl||An.getUnboundControlNameFromIdentifier(r)===be.TimeLineControl)&&(this.availableforphone=!0))}return u}buildDependencyList(t,n){if(F.IsNullOrUndefined(t))return;let r=t.getAllChildren();for(let i of r){let o=i.getAllChildren();for(let a of o){let s=a.GetPropertyByParameter(A.id);a.getNodeName()===D.dependency&&s?n.push(s):this.buildDependencyList(a,n)}}}get control(){return this.getFirstChild(D.formControl)}set rowspan(t){this.setProperty(A.rowspan,String(t))}get rowspan(){let t=this.getProperty(A.rowspan);return F.IsNullOrUndefined(t)?1:parseInt(t,10)}set autoexpand(t){this.setProperty(A.auto,String(t))}get autoexpand(){return this.getProperty(A.auto)==="true"}set colspan(t){let n=Number(KC.ONE_COLUMN),r=Number(KC.FOUR_COLUMN);F.IsNullOrUndefined(t)||t>r||t<n||this.setProperty(A.colspan,String(t))}get colspan(){let t=this.getProperty(A.colspan);return F.IsNullOrUndefined(t)?1:parseInt(t,10)}getParentRow(){return this.getAncestor(D.formRow)}getParentSection(){return this.getAncestor(D.formSection)}getParentTab(){return this.getAncestor(D.formTab)}getParentForm(){return this.getAncestor(D.form)}isInHeader(){let t=this.getAncestor(D.formHeader);return!F.IsNullOrUndefined(t)}isInFooter(){let t=this.getAncestor(D.formFooter);return!F.IsNullOrUndefined(t)}isEmpty(){return F.IsNullOrUndefined(this.control)&&!this.IsUserSpacer}getHeaderFooter(){return this.isInHeader()?this.getAncestor(D.formHeader):this.isInFooter()?this.getAncestor(D.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(A.userspacer);return F.IsNullOrUndefined(t)?!1:t==="true"}SetUserSpacer(){this.setProperty(A.userspacer,"true")}ClearUserSpacer(){this.setProperty(A.userspacer,"false")}get columns(){let t=this.getProperty(A.columnName);return F.IsNullOrUndefined(t)?null:parseInt(t,10)}getColumnLayoutValue(t){let n;switch(t){case Vt.TWO_COLUMN:n="11";break;case Vt.THREE_COLUMN:n="111";break;case Vt.FOUR_COLUMN:n="1111";break;default:n="1"}return n}findRowIndexByCellId(t){let n=this.getParentRow().cells.indexOf(this);for(let r=0;r<t.rows.length;r++)if(!F.IsNullOrUndefined(t.rows[r].cells[n])&&this.id.ToString()===t.rows[r].cells[n].id.ToString())return r;return-1}setAutoExpandDetailsForTab(){let t=this.getParentTab();F.IsNullOrUndefined(t)||(t.autoExpandCell=this,t.tabContainsAutoExpandControl=!0)}isCellRequiredOrLocked(t,n,r){let i=this.getParentForm();if(this?.control){if(this.IsUserSpacer)return!1;{if(this.isLocked||n().has(this.control.dataFieldName))return!0;let o=i.isDuplicateCell(this,r),a=this.getRequiredLevel(t);if((a===tu.ApplicationRequired||a===tu.SystemRequired)&&!o||this.isCellLockedByExternal(t)&&!o)return!0}}return!1}getRequiredLevel(t){return!this.control?.dataFieldName||!this.control?.id||this.IsNewField||!this.control?.ClassId?tu.None:t.getEntityAttributeByName(this.control.dataFieldName)?.requiredLevel?.toString()??tu.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 n=new Set;return t&&t.visit(r=>{if(r.getNodeName()===D.formCell){let i=r;i.control&&i!==this&&n.add(r.control.id)}return!1}),n}getHighestIndexById(t,n){let r=t.findAll(o=>o.getNodeName()===D.formCell&&o.control&&o.control.ClassId.guidString===n),i=0;return r.forEach(o=>{i=Math.max(this.parseControlNameIndex(o.control.id),i)}),i}parseControlNameIndex(t){let n=t.length-1,r=0;for(;n>0&&parseInt(t.charAt(n),10);)n--;return n>0&&n!==t.length-1&&t.charAt(n)===GS&&(n++,r=parseInt(t.substr(n,t.length-n),10)),r}}});var Ad,WS=B(()=>{"use strict";Sr();Re();Jn();Ad=class extends Se{isInternal;constructor(t,n,r,i){super(D.library,t),this.isInternal=!!i,Q.IsNullOrEmpty(r)||(this.name=n,this.libraryUniqueId=r)}get libraryUniqueId(){let t=this.getProperty(A.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(A.libraryUniqueId,t)}get name(){return this.getProperty(A.libraryName)}set name(t){this.setProperty(A.libraryName,t)}get displayName(){return this.getProperty(A.displayName)}set displayName(t){this.setProperty(A.displayName,t)}get description(){return this.getProperty(A.description)}set description(t){this.setProperty(A.description,t)}}});var _l,zS=B(()=>{"use strict";En();um();Re();Jn();_l=class extends Se{isRowAddedOnDragOver;constructor(t){super(D.formRow,t)}addCell(t){this.addChild(t)}appendCells(t){for(let n of t)this.addChild(n)}updateCell(t,n){return this.updateChild(t,n)}removeCell(t){return F.IsNullOrUndefined(t)?!1:this.deleteChild(t)>=0}insertCellAtIndex(t,n){return F.IsNullOrUndefined(t)?!1:(this.insertChildAtIndex(t,n),!0)}isEmpty(){return!this.cells||this.cells.every(t=>t.isEmpty())}getParentSection(){return this.getAncestor(D.formSection)}insertPaddingCellAtIndex(t){let n=new gi(this);n.setDefaultProperties(),this.insertCellAtIndex(n,t)}get firstCell(){let t=this.cells;return t.length>0?t[0]:null}get cells(){return this.getChildren(D.formCell)}get rowColspan(){return this.cells.reduce((t,n)=>t+n.colspan,0)}set IsRowAddedOnDragOver(t){this.isRowAddedOnDragOver=t}get IsRowAddedOnDragOver(){return this.isRowAddedOnDragOver}async getCellsJSON(t){let n=[],r=[];if(this.cells){for(let i of this.cells)r.push(i.toJSON(t));for(let i of r)n.push(await i)}return n}async toJSON(t){return{Cells:await this.getCellsJSON(t),Visible:!0,Height:"0"}}}});function Jge(e){switch(e){case El.Left:return Cl.Left;case El.Right:return Cl.Right;case El.Center:return Cl.Center;default:return Cl.Left}}function Yge(e){switch(e){case rd.Left:return id.Left;case rd.Top:return id.Top;default:return id.Left}}function ZV(e){switch(e){case 1:return 1;case 2:return 11;case 3:return 111;case 4:return 1111;default:return 1}}var Qge,ga,lm=B(()=>{"use strict";QC();Dn();En();Sr();FS();um();Re();Io();pu();zS();Qge=115,ga=class e extends Nr{colSpan=1;constructor(t,n){super(t,n)}getSectionType(){let t;switch(this.columns){case 1:t=Vt.ONE_COLUMN;break;case 11:t=Vt.TWO_COLUMN;break;case 111:t=Vt.THREE_COLUMN;break;case 1111:t=Vt.FOUR_COLUMN;break;default:t=this.colSpan-1}return t}setUniqueName(){let t=this.getParentTab(),n=xt.namePrefix;if(t){let r=t.Name,i=t.TotalSectionsCount+1;n=r+xt.namePrefix+i.toString()}else n+=Math.floor(Math.random()*1e3);this.setProperty(A.Name,n)}initializeDefaultProperties(t,n,r){if(r===Vt.REFERENCE_PANEL){this.addProperty(A.rowheight,"25");let i=`${xt.referencePanelNamePrefix}${H.NewGuid()}${xt.namePrefix}`;this.addProperty(A.Name,i)}else this.setUniqueName();if(this.addProperty(A.id,new H(H.NewGuid()).guidString),this.addProperty(A.IsUserDefined,xt.IsUserDefined),this.addProperty(A.locklevel,xt.LockLevel),this.addProperty(A.showlabel,xt.ShowLabel),this.addProperty(A.showbar,xt.ShowBar),this.addProperty(A.layout,xt.Layout),this.addProperty(A.Fieldlabelalignment,xt.labelAlignment),this.addProperty(A.Fieldlabelposition,xt.labelPosition),F.IsNullOrUndefined(r))this.addProperty(A.columnName,xt.columns);else{let i=this.getColumnLayoutValue(r);this.addProperty(A.columnName,i)}this.addProperty(A.LabelWidth,xt.LabelWidth),this.setDisplayName(n,t)}getColumnLayoutValue(t){let n;switch(t){case Vt.TWO_COLUMN:n="11";break;case Vt.THREE_COLUMN:n="111";break;case Vt.FOUR_COLUMN:n="1111";break;default:n="1"}return n}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 F.IsNullOrUndefined(this.columns)?t=this.ColSpan:this.columns.toString().split(Q.EmptyString).forEach(n=>{t+=parseInt(n,10)}),t}get ColSpan(){return this.colSpan}initializeRow(t){if(t>0&&t<5){let n=new _l(null);if(this.addGrandChild(D.formRows,n),zV.getConfig().enableAutoInsertionOfCellInRow)for(let r=0;r<t;r++){let i=new gi(n);i.setDefaultProperties(!1),n.addCell(i)}}}initialize(t,n,r){this.initializeDefaultProperties(t,n,r),r===Vt.REFERENCE_PANEL&&(r=Vt.ONE_COLUMN),this.initializeRow(r+1)}setColSpan(t){this.colSpan=t}appendRow(t){this.addGrandChild(D.formRows,t)}insertRowAtIndex(t,n){this.addGrandChildAtIndex(D.formRows,t,n)}insertRowsAtIndex(t,n){if(t&&t.length>0)for(let r=0;r<t.length;r++)this.addGrandChildAtIndex(D.formRows,t[r],n+r)}indexOfRow(t){return this.rows.indexOf(t)}deleteRow(t){return this.deleteFirstGrandChildOfName(D.formRows,t)}deleteRows(t,n){this.deleteGrandChildren(D.formRows,t,n)}get rows(){return this.getRows()}getRows(){let t=this.getChildren(D.formRows);return t.length===0?[]:t[0].getChildren(D.formRow)}get columns(){let t=this.getProperty(A.columnName),n=F.IsNullOrUndefined(t)?NaN:parseInt(t,10);if(isNaN(n)){let r=1;for(let i of this.rows)r=Math.max(r,i.cells.length);return ZV(r)}return n}set columns(t){F.IsNullOrUndefined(t)||this.setProperty(A.columnName,String(t))}get rowHeight(){let t=this.getProperty(A.rowheight);return F.IsNullOrUndefined(t)?null:parseInt(t,10)}set rowHeight(t){this.setProperty(A.rowheight,String(t))}set autoexpand(t){this.setProperty(A.autoExpand.toLowerCase(),String(t))}get autoexpand(){return this.getProperty(A.autoExpand.toLowerCase())==="true"}get isUserDefined(){return+this.getProperty(A.IsUserDefined)!=0}set isUserDefined(t){t?this.setProperty(A.IsUserDefined,"1"):this.setProperty(A.IsUserDefined,"0")}getParentColumn(){return this.getAncestor(D.formColumn)}getParentTab(){return this.getAncestor(D.formTab)}get hasMultiColumnRow(){return this.getColumnCountValue()>1}get showlabel(){return this.getProperty(A.showlabel)==="true"}set showlabel(t){F.IsNullOrUndefined(t)||this.setProperty(A.showlabel,String(t))}get fieldLabelAlignment(){let t=xt.labelAlignment,n=this.getProperty(A.Fieldlabelalignment);return F.IsNullOrUndefined(n)?t:n}set fieldLabelAlignment(t){F.IsNullOrUndefined(t)||this.setProperty(A.Fieldlabelalignment,t)}get fieldLabelPosition(){let t=this.getProperty(A.Fieldlabelposition);return F.IsNullOrUndefined(t)?xt.labelPosition:t}set fieldLabelPosition(t){F.IsNullOrUndefined(t)||this.setProperty(A.Fieldlabelposition,String(t))}get showbar(){return this.getProperty(A.showbar)==="true"}set showbar(t){F.IsNullOrUndefined(t)||this.setProperty(A.showbar,String(t))}get labelwidth(){let t=+this.getProperty(A.LabelWidth);return t===0?Qge:t}set labelwidth(t){F.IsNullOrUndefined(t)||t>283&&t<57||this.setProperty(A.LabelWidth,t.toString())}async getRowsJSON(t){let n=[],r=[];if(this.rows){for(let i of this.rows)r.push(i.toJSON(t));for(let i of r)n.push(await i)}return n}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:Jge(this.fieldLabelAlignment),Position:Yge(this.fieldLabelPosition)},Columns:ZV(this.getColumnCountValue()),AvailableForPhone:this.availableforphone,Height:this.rowHeight&&this.rowHeight.toString()}}getUsedNodeNameSet(t){let n=new Set;return t&&t.visit(r=>{if(r.getNodeName()===D.formSection){let i=r;i.Name&&!Q.GuidStringEquals(i.id.guidString,this.id.guidString)&&n.add(r.Name)}return!1}),n}isReferencePanelSection(){return!F.IsNullOrUndefined(this)&&!F.IsNullOrUndefined(this.Name)&&this.Name.indexOf(xt.referencePanelNamePrefix)===0}getAllMultiRowCells(){return this.findAll(t=>{if(t.getNodeName()===D.formCell){let n=t;return!n.isEmpty()&&n.rowspan>1}return!1})}isHeaderOrFooterSection(){return this.NodeName===D.formFooter||this.NodeName===D.formHeader}}});var mu,sy=B(()=>{"use strict";Re();Jn();lm();mu=class e extends Se{constructor(t){super(D.formColumn,t)}initializeDefaultProperties(t){this.addProperty(A.width,t.toString()+"%")}insertSectionAtIndex(t,n){this.addGrandChildAtIndex(D.formSections,t,n)}static createAndInitNewSection(t,n,r){let i=new ga(D.formSection,null);return i.initialize(t,n,r),i}addSectionAtIndex(t,n){this.addGrandChildAtIndex(D.formSections,t,n)}initialize(t,n,r,i=Vt.ONE_COLUMN){this.initializeDefaultProperties(t);let o=e.createAndInitNewSection(n,r,i);this.addSectionAtIndex(o,this.sections.length),o.setUniqueName()}get parentTab(){return this.getAncestor(D.formTab)}get sections(){let t=this.getChildren("sections");return t.length!==1?[]:t[0].getChildren(D.formSection)}get width(){return this.getProperty(A.width)}set width(t){this.setProperty(A.width,t)}deleteSection(t){return this.deleteFirstGrandChildOfName(D.formSections,t)}async getSectionsJSON(t){let n=[];if(this.sections)for(let r of this.sections)n.push(await r.toJSON(t));return n}async toJSON(t){return{Name:this.getProperty(A.Name),Id:this.getProperty(A.id),Label:null,ShowLabel:!1,Visible:!0,LabelId:null,PreviewId:this.getProperty(A.id),Sections:await this.getSectionsJSON(t),Width:this.width}}}});var uy,eG=B(()=>{"use strict";Dn();Re();Io();lm();uy=class extends ga{initializeNavArea(t,n,r){this.initializeNavAreaProps(t,n,r)}get AreaName(){return this.Name}initializeNavAreaProps(t,n,r){this.addProperty(A.Name,r),this.addProperty(A.id,new H(H.NewGuid()).guidString),this.addProperty(A.columnName,xt.columns),this.setDisplayName(n,t)}}});var ly,tG=B(()=>{"use strict";sy();Re();eG();ly=class extends mu{addAndIntializeNavBarSection(t,n,r,i){let o=new uy(D.formSection,null);return o.initializeNavArea(t,n,i),this.addGrandChildAtIndex(D.formSections,o,r),o}}});var fs,cy=B(()=>{"use strict";Dn();En();Sr();sy();Re();Jn();pu();fs=class extends Nr{tabContainsAutoExpandControl;autoExpandCell;constructor(t,n){super(D.formTab,t),this.tabContainsAutoExpandControl=!1}getParentForm(){return this.getAncestor(D.form)}getTabLayoutType(){let t;switch(this.columns.length){case 1:t=Bt.ONE_COLUMN;break;case 2:if(parseInt(this.columns[0].width,10)===50&&parseInt(this.columns[1].width,10)===50){t=Bt.TWO_COLUMN_EQUAL;break}if(parseInt(this.columns[0].width,10)===67&&parseInt(this.columns[1].width,10)===33){t=Bt.TWO_COLUMN_WIDER_LEFT;break}if(parseInt(this.columns[0].width,10)===34&&parseInt(this.columns[1].width,10)===66){t=Bt.TWO_COLUMN_WIDER_RIGHT;break}t=Bt.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=Bt.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=Bt.THREE_COLUMN_WIDER_MID;break}t=Bt.THREE_COLUMN_CUSTOM_LAYOUT;break;default:}return t}initializeProperties(t,n,r){this.addProperty(A.Name,uu.namePrefix+t.toString()),this.addProperty(A.id,new H(H.NewGuid()).guidString),this.addProperty(A.IsUserDefined,uu.IsUserDefined),this.addProperty(A.locklevel,uu.LockLevel),this.addProperty(A.showlabel,uu.ShowLabel),this.setDisplayName(r,n)}get TotalSectionsCount(){let t=0;for(let n of this.columns)t+=n.sections.length;return t}initializeColumns(t,n,r,i=Vt.ONE_COLUMN,o=!0,a){let s=this.getChildren(D.formColumns)[0],u=[];switch(t){case Bt.ONE_COLUMN:u.push(100);break;case Bt.TWO_COLUMN_EQUAL:u.push(50),u.push(50);break;case Bt.TWO_COLUMN_WIDER_LEFT:u.push(67),u.push(33);break;case Bt.TWO_COLUMN_WIDER_RIGHT:u.push(34),u.push(66);break;case Bt.THREE_COLUMN_EQUAL:u.push(34),u.push(33),u.push(33);break;case Bt.THREE_COLUMN_WIDER_MID:u.push(28),u.push(44),u.push(28);break;default:}for(let l of u){let c=new mu(s);c.initialize(l,n,r,i),this.addGrandChild(D.formColumns,c)}}initialize(t,n,r,i,o,a=Vt.ONE_COLUMN,s=!0,u){this.addChild(new Se(D.formColumns,this)),this.initializeProperties(n,r,i),this.initializeColumns(t,r,o,a,s,u)}get columns(){let t=this.getChildren(D.formColumns);return t.length!==1?[]:t[0].getChildren(D.formColumn)}get expanded(){return this.getProcessedValue(A.expanded)}set expanded(t){F.IsNullOrUndefined(t)||this.setProperty(A.expanded,String(t))}get groupName(){return this.getProperty(A.groupName)}get contentType(){return this.getProperty(A.contentType)}set contentType(t){this.setProperty(A.contentType,t)}insertNewColumnAtIndex(t,n,r,i,o){t.initialize(r,i,o),this.addGrandChildAtIndex(D.formColumns,t,n)}insertColumnAtIndex(t,n){this.addGrandChildAtIndex(D.formColumns,t,n)}deleteColumn(t){return this.deleteFirstGrandChildOfName(D.formColumns,t)}async getColumnsJSON(t){let n=[],r=[];if(this.columns){for(let i of this.columns)r.push(i.toJSON(t));for(let i of r)n.push(await i)}return n}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 n=new Set;return t&&t.visit(r=>{if(r.getNodeName()===D.formTab){let i=r;i.Name&&!Q.GuidStringEquals(i.id.guidString,this.id.guidString)&&n.add(r.Name)}return!1}),n}}});var Il,HS=B(()=>{"use strict";Dn();Re();Jn();Io();tG();cy();Il=class extends fs{constructor(t,n,r){super(t,Bt.THREE_COLUMN_EQUAL),this.setDisplayName(n,r),this.id=new H(H.NewGuid())}initializeDefaultProps(){this.addChild(new Se(D.formColumns,this)),this.initializeFiveColumns()}get columns(){let t=this.getChildren("columns");return t.length!==1?[]:t[0].getChildren(D.formColumn)}getNavSectionForArea(t){for(let n of this.columns)for(let r of n.sections)if(r.AreaName===t)return r;return null}getNavCellFromNavId(t){for(let n of this.columns)for(let r of n.sections)for(let i of r.rows)for(let o of i.cells)if(o.NavId===t)return o;return null}initializeFiveColumns(){for(let t=0;t<G0.FIVE_COLUMN;t++){let n=new ly(this.getChildren(D.formColumns)[0]);n.initializeDefaultProperties(E1.FiveEqColumn),this.addGrandChild(D.formColumns,n)}}}});function Zge(e){switch(e){case Pn.Main:return lu.Main;case Pn.QuickCreate:return lu.QuickCreate;case Pn.QuickViewForm:return lu.Quick;case Pn.Dialog:return lu.Dialog;default:return lu.None}}function e0e(e,t){if(t===Pn.Main){if(e)switch(e.toLowerCase()){case"low":return su.Low;case"highreadonlyvalues":return su.HighReadOnlyValues;default:return su.HighWithControls}return su.Low}}var fy,Xge,dy,nG=B(()=>{"use strict";O1();fy=Xe(vl());QC();En();Sr();td();FS();Re();cl();bC();bl();um();Re();pu();WS();HS();cy();Xge="1920";dy=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,n,r,i,o,a,s,u,l){super(D.form,null),this._formUniqueName=o,this._formId=t,this._entityName=n,this._status=r,this._formName=i,this._description=u,this._formType=a,this._formPresentation=s,this._formactivationstate=l,this._changeTracker=new O0,this._metadataChangeEvent=new W0}get FormLibraries(){let t=this.getFirstChild(D.formLibraries),n=t?t.getAllChildren():[],r=this._getInternalLibraries();return n.concat(r)}getAllEvents(){let t=[],n=this.events;n&&(t=t.concat(n));for(let r of this.tabs){let i=r.events;i&&(t=t.concat(i)),r.findAll(o=>o instanceof gi).forEach(o=>{let a=o.events;a&&(t=t.concat(a))})}return t}getEventsForNode(t){if(t instanceof e){let n=t.events;return n?n.filter(r=>!r.control&&!r.attribute):null}else if(t instanceof gi){if(t.control?.dataFieldName){let n=this.events;return n?n.filter(r=>r.attribute&&t.control.dataFieldName===r.attribute):null}else if(this.isCellEditableGridControl(t)){let n=this.events;return n?n.filter(r=>r.control&&t.control.id===r.control):null}}return t?.events}_getInternalLibraries(){let t=this.findAll(i=>i.getNodeName()===D.internalLibraries),n=[],r="src";return t.length>0&&(n=t.map(i=>{let o=i.GetPropertyByParameter(r).replace("$webresource:",""),a=new Ad(void 0,void 0,"",!0);return a.name=o,a.displayName=o,a})),n}getDependentFields(){let t=this.getAllEvents(),n=new Set;return t.forEach(r=>{try{r.getAllDependencies().forEach(o=>{n.add(o.id)})}catch(i){throw(0,fy.trackErrorTrace)(Q2,{eventName:"GetDependentFields_MissingDependencies",eventData:{Message:`Failed get dependencies for form event in form ${this.formId.guidString}.`,Attribute:r.attribute,EventName:r.eventName}}),i}}),n}get Parameters(){return this.parameters}set Parameters(t){this.parameters=t}get ShowImagecheck(){return Q.IsNullOrEmpty(this.getProperty(A.ShowImage))?!0:this.getProperty(A.ShowImage)!=="false"}set ShowImagecheck(t){t?this.setProperty(A.ShowImage,String(t)):this.setProperty(A.ShowImage,"false")}get ShowNavigation(){return Q.IsNullOrEmpty(this.getProperty(A.ShowNavigationbar))?!0:this.getProperty(A.ShowNavigationbar)!=="false"}set ShowNavigation(t){t?this.setProperty(A.ShowNavigationbar,String(t)):this.setProperty(A.ShowNavigationbar,"false")}get MaxWidth(){return Q.IsNullOrEmpty(this.getProperty(A.MaxWidth))?Xge:this.getProperty(A.MaxWidth)}set MaxWidth(t){this.setProperty(A.MaxWidth,t)}get headerDensityType(){return this.getProperty(A.HeaderDensityType)}set headerDensityType(t){t&&this.formType===Pn.Main?this.setProperty(A.HeaderDensityType,t):this.formType!==Pn.Main&&this.headerDensityType&&this.removeProperty(A.HeaderDensityType)}IsMainOrQuickCreateForm(){return this.formType===Pn.Main||this.formType===Pn.QuickCreate}get FormPresentation(){return this._formPresentation}get LanguageCode(){return this._langCode}set LanguageCode(t){this._langCode=t}get header(){let t=this.getChildren(D.formHeader);return t.length!==1?null:t[0]}set header(t){F.IsNullOrUndefined(t)||(this.deleteChild(this.header),this.addChild(t))}getAllDependencies(){return this.getChildren(D.quickFormDependencies).length===0?[]:this.ConvertModelToArray(this.getChildren(D.quickFormDependencies)[0].getAllChildren())}ConvertModelToArray(t){let n=[];return F.IsNullOrUndefined(t)||t.forEach(r=>{n.push(r.id)}),n}get footer(){let t=this.getChildren(D.formFooter);return t.length!==1?null:t[0]}set footer(t){F.IsNullOrUndefined(t)||(this.deleteChild(this.footer),this.addChild(t))}createAndInitNewTab(t,n,r){let i=new fs(null,t),o=this.getNextTabCounter(this.tabs.length+1);return i.initialize(t,o,this.LanguageCode,n,r),i}addTabAtIndex(t,n){this.addGrandChildAtIndex(D.formTabs,t,n)}createAndInitNewTabWithMarginalControl(t,n,r,i,o){let a=new fs(null,Bt.ONE_COLUMN),s=this.getNextTabCounter(this.tabs.length+1);a.initialize(Bt.ONE_COLUMN,s,this.LanguageCode,n,r,o,!1),this.addGrandChildAtIndex(D.formTabs,a,i);let u=a.columns[0].sections[0];for(let l=0;l<t.rows.length;l++)u.appendRow(t.rows[l])}getNextTabCounter(t){for(let n=0;n<this.tabs.length;n++)if(this.tabs[n].Name===uu.namePrefix+t.toString())return this.getNextTabCounter(t+1);return t}get allTabs(){let t=this.getChildren(D.formTabs);return t.length!==1?[]:t[0].getChildren(D.formTab)}get CanvasNavigationTab(){if(this.tabs.length>0){let t=this.tabs[this.tabs.length-1];if(t instanceof Il)return t}return null}get NavigationNode(){let t=this.getChildren(D.formNavigation);return t.length!==1?null:t[0]}set NavigationNode(t){let r=this.getAllChildren().indexOf(this.NavigationNode);r>=0&&(this.deleteChild(this.NavigationNode),this.insertChildAtIndex(t,r))}addNavigatioNode(t){this.addChild(t)}get tabs(){return this.allTabs}deleteTab(t){return this.deleteFirstGrandChildOfName(D.formTabs,t)}insertTabAtIndex(t,n){this.addGrandChildAtIndex(D.formTabs,t,n)}insertRelatedTab(t){let n=this.getAllGrandChildren(D.formTabs);if(!F.IsNullOrUndefined(n)){let r=n.length;this.insertTabAtIndex(t,r)}}get isfooterPresent(){return this.getChildren(D.formFooter).length>0}get displayCondition(){let t=this.getChildren(D.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(D.formTabs).indexOf(t)}get ControlDescriptions(){return this.getAllGrandChildren(D.controlDescriptions)}addControlDescriptionNode(t){this.addGrandChild(D.controlDescriptions,t)}deleteControlDescByForControlId(t){let n=this.getControlDescriptionByForControl(t);F.IsNullOrUndefined(n)||this.deleteFirstGrandChildOfName(D.controlDescriptions,n)}getControlDescriptionByForControl(t){if(!t)return null;for(let n of this.ControlDescriptions)if(n.forControl.guidString===t.guidString)return n;return null}cellHasCustomControlWithName(t,n){if(!t?.control||!n)return!1;let r=this.getControlDescriptionByForControl(t.control.UniqueId);return r?!!r.customControls.find(i=>i.name===n):!1}isDuplicateCell(t,n){return!!this.findFirst(i=>{if(!(i instanceof gi))return!1;let o=!0;return n==="Tab"?o=i.getParentTab()!==t.getParentTab():n==="Section"?o=i.getParentSection()!==t.getParentSection():o=i!==t,i instanceof gi&&i.control&&t.control&&o&&i.control.dataFieldName===t.control.dataFieldName})}isCellEditableGridControl(t){return!t?.control?.indicationOfSubgrid||t.control.ClassId.guidString.toUpperCase()!==k.CustomControl?!1:this.cellHasCustomControlWithName(t,is.EditableGridControl)||HV.getConfig()?.enableOneGridEventsForFormDesigner&&this.cellHasCustomControlWithName(t,is.PowerAppsOneGrid)}isCellCanvasAppControl(t){return t?.control?.ClassId.guidString.toUpperCase()===k.CustomControl&&this.cellHasCustomControlWithName(t,is.CanvasAppControl)}findFormNodeById(t,n=this){return n===null?null:n.findFirst(r=>{if(r===this&&t===this.formId.ToString()||r.id?.ToString?.()===t)return!0})}findFormCellByClassId(t,n=this){return n?n.findFirst(r=>{if(r.getNodeName()===D.formCell){let i=r;return i&&i.control&&i.control.ClassId.guidString===t}return!1}):null}async getTabsJSON(t){let n=this.tabs,r=[],i=[];if(n){for(let o of n)if(!(o instanceof Il)){let a=o.toJSON(t);r.push(a)}for(let o of r)i.push(await o)}return i}async getControlDescriptionsToJSON(t){let n=[];for(let r of this.ControlDescriptions){let i=await r.toJSON(t);i&&n.push(i)}return n}async toJSON(t){let n=[];n=await this.getControlDescriptionsToJSON(t);let r=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,fy.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===Pn.Main?{HeaderDensity:e0e(this.headerDensityType,this.formType)}:{},InlineEditGridRow:[],InlineQuickForms:[],QuickFormEntities:[],EventHandlers:[],LinkControlSections:[],FormType:Zge(this.formType),SubGrids:[],Views:void 0,Charts:void 0,CustomControlConfigurations:n,BusinessLogic:void 0,FormLibraries:[],Navigation:r,ShowNavigationBar:this.ShowNavigation||t.formModelService.showHiddenElements,ClientResources:[]}}changeTracker(){return this._changeTracker}onMetadataChange=t=>this._metadataChangeEvent.on(t);raiseMetadataChange(t){this._metadataChangeEvent.emit(t)}}});var py,KS,rG=B(()=>{"use strict";Dn();En();Re();Jn();pu();py=class extends Nr{constructor(t){super(D.formDisplayConditions,t)}get Order(){let t=this.getProperty(A.Order);return F.IsNullOrUndefined(t)?null:parseInt(t,10)}set Order(t){this.setProperty(A.Order,t.toString())}get FallbackForm(){return this.getProperty(A.FallbackForm)==="true"}set FallbackForm(t){this.setProperty(A.FallbackForm,t.toString())}addRoles(t){this.deleteAllChildren();for(let n=0;n<t.length;n++)this.addChild(t[n])}isRoleEveryone(){return!!(this.getChildren(D.formEveryOne)&&this.getChildren(D.formEveryOne)[0])}setRoleEveryone(){this.deleteAllChildren(),this.addChild(new KS(this))}},KS=class extends Se{constructor(t){super(D.formEveryOne,t)}}});var my,iG=B(()=>{"use strict";Re();Jn();my=class extends Se{constructor(t,n){super(D.Handler,n),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(A.HandlerUniqueId)}set HandlerUniqueID(t){this.setProperty(A.HandlerUniqueId,t)}get FunctionName(){return this.getProperty(A.functionName)}set FunctionName(t){this.setProperty(A.functionName,t)}get LibraryName(){return this.getProperty(A.libraryNameEventHandler)}set LibraryName(t){this.setProperty(A.libraryNameEventHandler,t)}get Enabled(){return this.getProperty(A.enabledForField)}set Enabled(t){this.setProperty(A.enabledForField,t)}get PassExecutionContext(){return this.getProperty(A.passExecutionContext)}set PassExecutionContext(t){this.setProperty(A.passExecutionContext,t)}get Parameters(){return this.getProperty(A.parameters)}set Parameters(t){this.setProperty(A.parameters,t)}}});var Cd,JS=B(()=>{"use strict";Re();lm();Cd=class extends ga{constructor(t,n){super(t,n)}get cells(){let t=this.getRows(),n=[];if(this.rows&&t.length){for(let r of this.rows)if(r.cells){let i=r.getChildren(D.formCell);for(let o of i)n.push(o)}}return n}get occupiedCells(){return this.cells.filter(t=>!t.isEmpty())}get maxColumns(){return super.getColumnCountValue()}}});var cm,oG=B(()=>{"use strict";Re();JS();cm=class extends Cd{_customFooter;constructor(t,n){super(D.formFooter,t),this._customFooter=n}get customFooter(){return this._customFooter}set customFooter(t){this._customFooter=t}async getControls(t){let n=[];if(this.rows){for(let r of this.rows)if(r.cells)for(let i of r.cells)i.control&&n.push(await i.control.toJSON(t))}return n}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 dm,aG=B(()=>{"use strict";Re();JS();dm=class extends Cd{_customHeader;constructor(t,n){super(D.formHeader,t),this._customHeader=n}get customHeader(){return this._customHeader}set customHeader(t){this._customHeader=t}get showCommandBar(){return this.getProcessedValue(A.showCommandBar)}set showCommandBar(t){t!=null&&this.setProperty(A.showCommandBar,String(t))}get showBody(){return this.getProcessedValue(A.showBody)}set showBody(t){t!=null&&this.setProperty(A.showBody,String(t))}get showTabNavigator(){return this.getProcessedValue(A.showTabNavigator)}set showTabNavigator(t){t!=null&&this.setProperty(A.showTabNavigator,String(t))}async getControls(t){let n=[];if(this.rows){for(let r of this.rows)if(r.cells)for(let i of r.cells)i.control&&n.push(await i.control.toJSON(t))}return n}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 yi,Tl=B(()=>{"use strict";Dn();Sr();Re();pu();yi=class e extends Nr{constructor(t,n){super(t,n)}getTitle(t){for(let n of this.getAllTitles())if(+n.getProperty(A.LCID)===t)return n.getProperty(A.text);return null}getAllTitles(){let t=this.getChildren(D.Titles);return t.length===0?[]:t[0].getChildren(D.Title)}setTitle(t,n){for(let i of this.getAllTitles())if(+i.getProperty(A.LCID)===n){i.setProperty(A.text,t);return}let r=new e(D.Title,null);r.setProperty(A.text,t),r.setProperty(A.LCID,String(n)),this.addGrandChild(D.Titles,r)}get Sequence(){return+this.getProperty(A.Sequence)}set Sequence(t){this.setProperty(A.Sequence,t.toString())}get Area(){return this.getProperty(A.Area)}set Area(t){this.setProperty(A.Area,t)}set Id(t){this.setProperty(A.Id,t)}get Id(){return this.getProperty(A.Id)}get id(){return new H(this.Id??"",!0)}set id(t){this.Id=t.guidString}get Show(){return!0}get Icon(){return this.getProperty(A.icon)}set Icon(t){t=t||Q.EmptyString,this.setProperty(A.icon,t)}updateCommonProperties(t,n){this.Area=t.Area,this.Sequence=t.Sequence,this.setTitle(t.getDisplayName(n),n)}}});var fm,sG=B(()=>{"use strict";(function(e){e[e.NavLinkNotAvailable=-1]="NavLinkNotAvailable",e[e.NavLinkIdConflict=-2]="NavLinkIdConflict",e[e.NavBarNotAvailable=-3]="NavBarNotAvailable"})(fm||(fm={}))});var hy,uG=B(()=>{"use strict";En();Re();Tl();sG();hy=class extends yi{constructor(t){super(D.formNavBar,t)}addChildElement(t){this.addChild(t)}getAllActiveNavBarChildren(){return this.getAllChildren().filter(r=>r.Show)}getAllInActiveActiveNavBarChildren(){return this.getAllChildren().filter(r=>!r.Show)}get AllRelationShipItems(){return this.getChildren("NavBarByRelationshipItem")}get AllNavLinkItems(){return this.getChildren("NavBarItem")}removeNavLink(t){let n=this.getNavBarLinkItemById(t);return F.IsNullOrUndefined(n)?fm.NavLinkNotAvailable:n.length===1?this.deleteChild(n[0]):fm.NavLinkIdConflict}getRelationShipItemsByArea(t){let n=this.AllRelationShipItems,r=[];for(let i of n)i.Area===t&&i.Show===!0&&r.push(i);return r}getNavBarRelationShipItemsByNavId(t){return this.AllRelationShipItems.filter(r=>r.Id===t)}getNavBarLinkItemById(t){let n=this.AllNavLinkItems.filter(r=>r.Id===t);return n.length>0?n:null}getAllActiveChildrenForGivenArea(t){let n=this.getAllChildren(),r=[];for(let i of n)i.Area===t&&i.Show&&r.push(i);return r}}});var Tt,t0e,lG,B2e,Sd,YS=B(()=>{"use strict";Dn();Re();Tl();(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"})(Tt||(Tt={}));t0e=new Map([[Tt.Info,"Info"],[Tt.Sales,"Sales"],[Tt.Service,"Service"],[Tt.Marketing,"Marketing"],[Tt.ProcessCenter,"ProcessCenter"]]),lG=new Map([["Info",Tt.Info],["Sales",Tt.Sales],["Service",Tt.Service],["Marketing",Tt.Marketing],["ProcessCenter",Tt.ProcessCenter]]),B2e=new Map([[Tt.Info,9e3],[Tt.Sales,9200],[Tt.Service,9400],[Tt.Marketing,9600],[Tt.ProcessCenter,9800],[Tt.InternetMarketing,1e4],[Tt.Async,10200]]),Sd=class extends yi{constructor(t,n){super(D.formNavBarArea,n)}setDefaultPropertiesByType(t,n,r){this.AreaId=t0e.get(t);let i=r?.(`navBarArea.title.${this.AreaId}`)??this.AreaId;this.setTitle(i,n)}get ParentNavigation(){return this.getAncestor(D.formNavigation)}get AreaId(){return this.getProperty(A.Id)}set AreaId(t){this.setProperty(A.Id,t)}get id(){return new H(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 Nd,QS=B(()=>{"use strict";Re();Tl();Nd=class extends yi{constructor(t,n){super(D.formNavBarAreas,n)}get AllNavBarAreaItems(){return this.getChildren(D.formNavBarArea)}get ParentNavigation(){return this.getAncestor(D.formNavigation)}addNavBarArea(t){this.addChild(t)}}});var gy,cG=B(()=>{"use strict";En();Re();Tl();gy=class extends yi{RelationshipNameUCIRuntime;constructor(t){super(D.formNavBarByRelationshipItem,t)}get RelationshipName(){return this.getProperty(A.RelationshipName)}set RelationshipName(t){this.setProperty(A.RelationshipName,t)}set Show(t){this.setProperty(A.Show,String(t))}get Show(){let t=this.getProperty(A.Show);return F.IsNullOrUndefined(t)||t==="true"}get TitleResourceId(){return this.getProperty(A.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 yy,dG=B(()=>{"use strict";Re();Tl();yy=class extends yi{constructor(t){super(D.formNavBarItem,t)}get Url(){return this.getProperty(A.url)}set Url(t){this.setProperty(A.url,t)}}});var by,fG=B(()=>{"use strict";Dn();Re();YS();QS();Tl();by=class extends yi{constructor(t,n){super(t,n)}getNavBarAreaByAreaName(t){let n=this.navBarAreas.AllNavBarAreaItems.filter(r=>r.AreaId===t);return n.length===0?null:n[0]}get navBarAreas(){return this.getFirstChild(D.formNavBarAreas)}setDefaultNavBarAreas(t,n){let r=[Tt.Info,Tt.Sales,Tt.Service,Tt.Marketing,Tt.ProcessCenter];if(this.navBarAreas){let i=this.navBarAreas?.AllNavBarAreaItems;if(i&&i.length>0){let o=new Set(i.map(a=>lG.get(a.AreaId)));r=r.filter(a=>!o.has(a))}}else{let i=new Nd(D.formNavBarAreas,this);i.isTransient=!0,this.addChild(i)}return r.length>0?(r.forEach(i=>{let o=new Sd(D.formNavBarArea,this.navBarAreas);o.setDefaultPropertiesByType(i,t,n),this.navBarAreas.addNavBarArea(o)}),!0):!1}get navBar(){return this.getFirstChild(D.formNavBar)}get id(){return new H(DC,!0)}replaceNavAreaToGivenIndex(t,n){this.navBarAreas?.AllNavBarAreaItems.indexOf(n)!==-1&&(this.deleteFirstGrandChildOfName(D.formNavBarAreas,n),this.addGrandChildAtIndex(D.formNavBarAreas,n,t))}async getNavBarAreasJSON(t){let n=[],r=[];if(this.navBarAreas?.AllNavBarAreaItems){for(let o of this.navBarAreas.AllNavBarAreaItems)r.push(o.toJSON(t));n=await Promise.all(r)}return n}async getNavBarRelationshipItemsJSON(t){let n=[],r=[];if(this.navBar?.AllRelationShipItems){for(let i of this.navBar.AllRelationShipItems)r.push(i.toJSON(t));n=await Promise.all(r)}return n}async toJSON(t){let n=await this.getNavBarAreasJSON(t),r=await this.getNavBarRelationshipItemsJSON(t);return{NavBarAreas:{NavBarAreas:n},NavBarByRelationshipItems:r,NavBarItems:[],NavPaneIsvItems:{NavBarIsvItems:[]},ShowEmptyNavBarAreas:t.formModelService.showHiddenElements}}}});var pG={};Fi(pG,{ControlType:()=>to,DeserializationService:()=>eN,DeserializationServiceScope:()=>ZS,DeserializedFormElementNode:()=>bi});var XS,bi,ZS,to,eN,jS=B(()=>{"use strict";XS=Xe(vl());Dn();En();Sr();td();PC();bl();X2();I1();Bp();nG();um();sy();sm();US();Re();Re();rG();Jn();Io();qS();iG();oG();BS();VS();aG();WS();zS();lm();cy();uG();YS();QS();cG();dG();fG();bi=class extends Se{constructor(t,n){super(t,n)}insertProperty(t,n){this.addProperty(t,n)}insertChild(t){this.addChild(t)}},ZS="DeserializationService";(function(e){e.Grid="Grid",e.Lookup="Lookup",e.Base="Base"})(to||(to={}));eN=class{lcid;constructor(t){this.lcid=t}deSerializeFormXml(t,n,r,i,o,a,s,u,l,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,XS.trackErrorTrace)(Vr,{eventName:ZS,eventData:{error:p}}),new Error(p)}let f=this.createFormModel(d.item(0),n,r,i,o,a,s,u,l,c);return F.IsNullOrUndefined(f.displayCondition)&&s!==Pn.Dialog&&this.appendDefaultDisplayCondition(f),f}upsertFieldCount(t,n){let r=wl.getNecessaryLookUpTable(n),i=1;r.containsKey(t)&&(i+=r.getValue(t)),r.upsert(t,i)}appendDefaultDisplayCondition(t){let n='<DisplayConditions Order="0" FallbackForm="true"><Everyone/></DisplayConditions>';if(!F.IsNullOrUndefined(t)){let r=F.ParseXml(n);r!==null&&this.populateElementChildren(t,r.childNodes)}}createFormModel(t,n,r,i,o,a,s,u,l,c){let d=new dy(n,r,i,o,a,s,u,l,c);return this.populateElementProperties(d,t.attributes),this.populateElementChildren(d,t.childNodes),s===Pn.Main&&(this.insertHeaderFooterElementProperties(D.formHeader,d,d.header),this.insertHeaderFooterElementProperties(D.formFooter,d,d.footer)),d}insertHeaderFooterElementProperties(t,n,r){if(F.IsNullOrUndefined(r)){let i=t===D.formHeader?new dm(n,!0):new cm(n,!0);bi.prototype.insertProperty.call(i,A.id,"{"+H.NewGuid()+"}"),bi.prototype.insertProperty.call(i,A.Fieldlabelposition,"Top"),bi.prototype.insertProperty.call(i,A.columnName,xt.MarginalControlColumns),bi.prototype.insertProperty.call(i,A.LabelWidth,xt.LabelWidth),bi.prototype.insertProperty.call(i,A.Fieldlabelalignment,"Left");let o=null,a=new _l(o);for(let s=0;s<i.maxColumns;s++){let u=new gi(a);bi.prototype.insertProperty.call(u,A.id,"{"+H.NewGuid()+"}"),u.setDisplayName(Q.EmptyString,this.lcid),bi.prototype.insertProperty.call(u,A.showlabel,"false"),a.addCell(u)}i.appendRow(a),t===D.formHeader?n.header=i:n.footer=i}}deSerializeFormXmlNode(t,n){if(t&&t.nodeValue&&(t.nodeType===Node.TEXT_NODE||t.nodeType===Node.CDATA_SECTION_NODE))return new bi(`<${t.nodeValue}`,n);if(t.nodeType===Node.COMMENT_NODE)return;let r=this.createModelNode(t,n);return this.populateElementProperties(r,t.attributes),this.populateElementChildren(r,t.childNodes),r}populateElementProperties(t,n){if(!n){let r="attributes is undefined for element: "+t.getNodeName();throw(0,XS.trackErrorTrace)(Vr,{eventName:ZS,eventData:{error:r}}),new Error(r)}for(let r=0;r<n.length;r++){let i=n.item(r);i&&(bi.prototype.insertProperty.call(t,i.name,i.value),t.getNodeName()===D.formCell&&i.name===A.auto&&i.value==="true"&&t.setAutoExpandDetailsForTab())}}populateElementChildren(t,n){for(let r=0;r<n.length;r++){let i=n.item(r),o=this.deSerializeFormXmlNode(i,t);o&&bi.prototype.insertChild.call(t,o)}}createModelNode(t,n){switch(t.nodeName){case D.form:throw new Error("Form node shouldn't be created using this method");case D.formTab:return new fs(n);case D.formColumn:return new mu(n);case D.formHeader:return new dm(n,!1);case D.formFooter:return new cm(n,!1);case D.formSection:return new ga(D.formSection,n);case D.formRow:return new _l(n);case D.formCell:return new gi(n);case D.formControl:let r=t.attributes,i=t.childNodes.length>0?t.childNodes[0].childNodes:null,o;for(let s=0;s<r.length;s++){let u=r.item(s);if(u.name===A.indicationOfSubgrid&&u.value==="true"||u.name===A.classid&&(u.value?.toLocaleUpperCase()===`{${k.SubgridControl}}`||u.value?.toLocaleUpperCase()===`{${k.ReferencePanelSubgridControl}}`))o=to.Grid;else if(u.name===A.classid&&u.value?.toLocaleUpperCase()===`{${k.LookupControl}}`)o=to.Lookup;else if(u.name===A.classid&&u.value?.toLocaleUpperCase()===`{${k.CustomControl}}`)for(let l=0;l<i?.length;l++)i[l].nodeName===A.DefaultViewId&&(o=to.Lookup)}return o===to.Grid?new wd(n):o===to.Lookup?new Ed(n):new Do(n);case D.formEvent:return new vd(n,Q.EmptyString);case D.dependency:return this.populateDependencyTable(t),new bd(n,Q.EmptyString);case D.Handler:let a=[];return new my(a,n);case D.formNavigation:return new by(t.nodeName,n);case D.formNavBarArea:return new Sd(t.nodeName,n);case D.formNavBarAreas:return new Nd(t.nodeName,n);case D.formNavBar:return new hy(n);case D.formNavBarByRelationshipItem:return new gy(n);case D.formNavBarItem:return new yy(n);case D.formDisplayConditions:return new py(n);case D.library:return new Ad(n,Q.EmptyString,Q.EmptyString);case D.controlDescription:return new $0(n);case D.customControl:return this.populateCustomControlConfigurationId(t),new j0(n);default:return new bi(t.nodeName,n)}}populateDependencyTable(t){let n=t.attributes;for(let r=0;r<n.length;r++){let i=n.item(r);i.name===A.id&&this.upsertFieldCount(i.value,fa.DependencyFieldTable)}}populateCustomControlConfigurationId(t){let n=t.attributes;for(let r=0;r<n.length;r++){let i=n.item(r);if(i.name===A.id){let o=new H(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===A.ForControl){let u=s.value.substr(1,i.value.length-2);An.CustomControlIdMap.upsert(u,o);break}}break}}}}});var mG={};Fi(mG,{SerializationService:()=>tN,SerializationServiceScope:()=>n0e,SerializedFormElementNode:()=>_d});var n0e,_d,tN,hG=B(()=>{"use strict";Sr();Jn();Io();HS();n0e="SerializationService",_d=class extends Se{fetchNodeName(){return this.getNodeName()}enumerateProperties(){return this.getAllProperties()}enumerateChildren(){return this.getAllChildren()}},tN=class{langCode;constructor(t){this.langCode=t}serializeFormXmlNode(t){let n=_d.prototype.fetchNodeName.call(t);if(n.charAt(0)===cs.StartTag)return Q.EscapeXml(n.substr(1),!1);if(t.isTransient&&!t.isDirty())return Q.EmptyString;let r=_d.prototype.enumerateProperties.call(t),i=_d.prototype.enumerateChildren.call(t);if(!(t instanceof Il)){let o=`<${n}`;if(r.length!==0&&(o+=` ${this.getPropertiesString(r)}`),i.length===0)o+=" />";else{let a=Q.EmptyString;for(let s of i)a+=this.serializeFormXmlNode(s);o+=`>${a}</${n}>`}return o}return Q.EmptyString}getPropertiesString(t){let n=Q.EmptyString;return t.forEach((r,i)=>{i!==0&&(n+=" "),n+=`${r.key}="${Q.EscapeXml(r.value,!0)}"`}),n}}});var vy=C(Id=>{"use strict";Object.defineProperty(Id,"__esModule",{value:!0});Id.completeRecordAsStored=Id.completeLabelsAsStored=void 0;var nN=ja(),r0e="E7A81278-8635-4D9E-8D4D-59480B391C5B",i0e=new Set(["tab","section","cell"]);function Po(e){let t=[];for(let n=e.firstChild;n;n=n.nextSibling)n.nodeType===1&&t.push(n);return t}function hu(e,t){return Po(e).find(n=>n.tagName===t)}function bG(e,t){return e.length===t.length&&e.every((n,r)=>n.tagName===t[r].tagName)}function rN(e){let t=hu(e,"control");return t?(t.getAttribute("datafieldname")||"")!==""?!0:(t.getAttribute("classid")||"").replace(/[{}]/g,"").toUpperCase()===r0e:!1}function iN(e,t){var n,r;let i=((n=hu(e,"control"))===null||n===void 0?void 0:n.getAttribute("id"))||"";return i!==""&&i===(((r=hu(t,"control"))===null||r===void 0?void 0:r.getAttribute("id"))||"")}function o0e(e,t,n){if(hu(e,"labels"))return;let r=Po(e),i=Po(t),o=i[0];if(!o||o.tagName!=="labels"||i.length!==r.length+1||!bG(r,i.slice(1)))return;let a=Po(o);if(!(a.length===0||a.some(u=>u.tagName!=="label"||!u.hasAttribute("description")||!u.hasAttribute("languagecode"))||!(!n&&e.tagName==="cell"&&rN(e)&&iN(e,t))&&a.some(u=>u.getAttribute("description")!=="")))return o}function a0e(e,t){let n=s0e(e.ownerDocument,t),r=Po(e)[0];r?e.insertBefore(n,r):e.appendChild(n)}function s0e(e,t){let n=e.createElement("labels");for(let r of Po(t))n.appendChild(vG(e,r));return n}function vG(e,t){let n=e.createElement("label");for(let r=0;r<t.attributes.length;r+=1){let{name:i,value:o}=t.attributes[r];(i==="description"||i==="languagecode")&&n.setAttribute(i,o)}return n}function gG(e,t){let n=hu(e,"labels");return n?Po(n).find(r=>r.tagName==="label"&&r.getAttribute("languagecode")===String(t)):void 0}function u0e(e,t,n){if(e.tagName!=="cell"||!rN(e)||!iN(e,t))return!1;let r=gG(e,n),i=gG(t,n),o=i?.getAttribute("description")||"";return!r||!r.hasAttribute("description")||(r.getAttribute("description")||"")!==""||o===""?!1:(r.setAttribute("description",o),!0)}function l0e(e,t){if(e.tagName!=="cell"||!rN(e)||!iN(e,t))return;let n=hu(e,"labels"),r=hu(t,"labels");if(!n||!r)return;let i=Po(n),o=Po(r),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 u=new Set,l=0,c=[],d=[];for(let f of o){let p=f.getAttribute("languagecode")||"";if(u.has(p))return;u.add(p);let m=s.get(p);if(!m){d.push(f);continue}if((m.getAttribute("description")||"")!==(f.getAttribute("description")||""))return;l+=1,c.push(...d.map(h=>({label:h,before:m}))),d=[]}return c.push(...d.map(f=>({label:f}))),l===i.length?c:void 0}function wG(e,t,n,r,i){if(e.tagName===t.tagName){if(i0e.has(e.tagName)){let o=o0e(e,t,i);if(o&&(a0e(e,o),r.changed=!0),i){yG(e,t,n,r,i);return}u0e(e,t,n)&&(r.changed=!0);let a=l0e(e,t),s=hu(e,"labels");if(a&&s){for(let{label:u,before:l}of a){let c=vG(e.ownerDocument,u);l?s.insertBefore(c,l):s.appendChild(c)}r.changed=!0}}yG(e,t,n,r,i)}}function yG(e,t,n,r,i){let o=Po(e),a=Po(t);bG(o,a)&&o.forEach((s,u)=>wG(s,a[u],n,r,i))}function EG(e,t,n,r={}){if(e===t)return e;let i,o;try{i=(0,nN.parseXmlRoot)(e,""),o=(0,nN.parseXmlRoot)(t,"")}catch{return e}let a={changed:!1};return wG(i,o,n,a,r.emptyInsertionsOnly===!0),a.changed?(0,nN.serializeNode)(i):e}Id.completeLabelsAsStored=EG;function c0e(e,t,n){let r=e?.formxml,i=t?.formxml;if(typeof r!="string"||typeof i!="string")return e;let o=EG(r,i,n);return o===r?e:{...e,formxml:o}}Id.completeRecordAsStored=c0e});var BG=C(ke=>{"use strict";Object.defineProperty(ke,"__esModule",{value:!0});ke.pcfReadIssues=ke.pcfBindingIssues=ke.commitPcfState=ke.mayCommitPcfState=ke.reconcilePcfDescriptions=ke.customControlNeeds=ke.mintPcfIdentity=ke.planPcfBinding=ke.projectPcfBindings=ke.supportsPcfFormType=ke.storedBindingOf=ke.hasCustomControl=ke.sameAsStored=ke.readPcfDescription=ke.newPcfDescription=ke.editorText=ke.nativeClassFor=ke.pcfEntryLayout=void 0;var d0e=(Bp(),_i(T1)),f0e=Y(),AG=ft(),ee=dg(),p0e=kA(),Ye=Vi(),hs=["web","phone","tablet"],pm={web:"2",phone:"0",tablet:"1"},IG=new Map([["2","web"],["0","phone"],["1","tablet"]]),m0e=["phone","web","tablet"];function Ey(e){let t=new Set(e),n=m0e.filter(r=>!t.has(r));return{defaults:n.length===0?[null]:n,named:hs.filter(r=>t.has(r))}}ke.pcfEntryLayout=Ey;function Gr(e){return Array.isArray(e)?e:[]}function Cn(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function mm(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function aN(e){return{n:`<${e}`,a:[],c:[]}}function TG(e){return typeof e?.n=="string"&&e.n.startsWith("<")}function CG(e){let t=Gr(e.c);return t.length===1&&TG(t[0])&&(0,ee.rawText)(e)!==""?(0,ee.rawText)(e):void 0}function ro(e,t){return JSON.stringify(e)===JSON.stringify(t)}function OG(e){return`{${e.replace(/^\{|\}$/g,"").toUpperCase()}}`}function sN(e){try{let t=(0,d0e.mapFieldTypeToControl)(e.attributeTypeName,e.format);return t?OG(String(t)):void 0}catch{return}}ke.nativeClassFor=sN;var uN=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}]]),DG=new Set(["TwoOptions","Boolean"]),PG=new Set(["SingleLine.Text","SingleLine.TextArea","SingleLine.Email","SingleLine.Phone","SingleLine.URL","SingleLine.Ticker","Multiple"]),h0e=new Map([...[...PG].map(e=>[e,100]),["SingleLine.TextArea",2e3],["Multiple",1048576]]),g0e=/^[A-Za-z_][A-Za-z0-9_.-]*$/;function RG(e){return g0e.test(e)&&e!=="__proto__"}function lN(e){return e!==void 0&&(e==="Enum"||uN.has(e)||DG.has(e)||PG.has(e))}function kG(e){return typeof e=="number"?e:e!==""&&!Number.isNaN(Number(e))?Number(e):void 0}function hm(e,t){let n=e!==void 0?uN.get(e):void 0;if(n&&typeof t!="boolean"){let r=kG(t);if(r!==void 0)return r.toFixed(n.digits)}return typeof t=="boolean"?t?"true":"false":String(t)}ke.editorText=hm;function y0e(e,t,n){var r;let i=[];for(let o of e.properties){let a=o.name,s;if(o.isPrimary?s=t:o.usage==="input"&&mm(n,a)?s=hm(o.defaultType,n[a]):s=(r=o.defaultValue)!==null&&r!==void 0?r:"",s==="")continue;let u=[];o.defaultType&&u.push(["type",o.defaultType]),!o.isPrimary&&(o.defaultType==="Enum"||o.usage==="input")&&u.push(["static","true"]),i.push({n:a,a:u,c:[aN(s)]})}return i}function $G(e,t,n,r,i){var o,a;let s=(o=r.formFactors)!==null&&o!==void 0?o:hs.filter(d=>cN(i).has(d)),u=Ey(s),l=y0e(i,t,(a=r.parameters)!==null&&a!==void 0?a:{}),c=d=>JSON.parse(JSON.stringify(d));return{n:"controlDescription",a:[["forControl",e]],c:[...u.defaults.map(d=>({n:"customControl",a:d===null?[["id",n]]:[["id",n],["formFactor",pm[d]]],c:[{n:"parameters",a:[],c:[{n:"datafieldname",a:[],c:[aN(t)]}]}]})),...u.named.map(d=>({n:"customControl",a:[["name",r.name],["formFactor",pm[d]]],c:[{n:"parameters",a:[],c:c(l)}]}))]}}ke.newPcfDescription=$G;function cN(e){return new Set(hs.filter(t=>e.availableOn[t]))}function wy(e){var t;let n=Gr(e.c);if(n.length!==1||((t=n[0])===null||t===void 0?void 0:t.n)!=="parameters"||Gr(n[0].a).length>0)return;let r=Gr(n[0].c);return r.every(i=>Cn(i)&&!TG(i))?r:void 0}function Ol(e){let t=Gr(e?.c);if(t.length===0||!t.every(m=>Cn(m)&&m.n==="customControl"))return;let n=t.findIndex(m=>(0,ee.rawAttr)(m,"name")!==void 0);if(n<=0)return;let r=t.slice(n),i=(0,ee.rawAttr)(r[0],"name"),o=[];for(let m of r){let h=Gr(m.a),g=h.length===2?IG.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=Ey(o);if(!ro(a.named,o)||i==="")return;let s=wy(r[0]);if(!s||!r.every(m=>ro(wy(m),s)))return;let u=t.slice(0,n);if(u.length!==a.defaults.length)return;let l=(0,ee.rawAttr)(u[0],"id"),c;for(let m=0;m<u.length;m+=1){let h=a.defaults[m],g=h===null?[["id",l??""]]:[["id",l??""],["formFactor",pm[h]]],y=wy(u[m]),b=y?.length===1&&y[0].n==="datafieldname"&&Gr(y[0].a).length===0?CG(y[0]):void 0;if(!l||!ro(Gr(u[m].a),g)||b===void 0||c!==void 0&&b!==c)return;c=b}let d={},f={},p;for(let m of s){let h=Gr(m.a),g=CG(m),y=h.map(b=>b[0]);if(g===void 0||!RG(m.n)||mm(d,m.n)||m.n===p)return;if((0,ee.rawAttr)(m,"static")===void 0){if(p!==void 0||g!==c||!(y.length===0||ro(y,["type"])))return;p=m.n;continue}if((0,ee.rawAttr)(m,"static")!=="true"||!(ro(y,["static"])||ro(y,["type","static"])))return;d[m.n]=g,f[m.n]=(0,ee.rawAttr)(m,"type")}if(!(p===void 0||c===void 0||l===void 0))return{binding:{name:i,...Object.keys(d).length>0?{parameters:d}:{},...o.length===hs.length?{}:{formFactors:o}},fieldName:c,nativeClass:l,parameterTypes:f,boundProperty:p}}ke.readPcfDescription=Ol;function LG(e,t,n){return e===t?!0:typeof e!="string"&&(t===String(e)||t===hm(n,e))}function MG(e){let t=e.formFactors;return t===void 0?[...hs]:Array.isArray(t)?hs.filter(n=>t.includes(n)):[]}function oN(e,t){var n,r,i;if(e.name!==t.binding.name||!ro(MG(e),(n=t.binding.formFactors)!==null&&n!==void 0?n:hs))return!1;let o=(r=e.parameters)!==null&&r!==void 0?r:{},a=(i=t.binding.parameters)!==null&&i!==void 0?i:{},s=Object.keys(o);return s.length!==Object.keys(a).length?!1:s.every(u=>mm(a,u)&&LG(o[u],a[u],t.parameterTypes[u]))}ke.sameAsStored=oN;function Rn(e){return Cn(e)&&e.customControl!==void 0}ke.hasCustomControl=Rn;function ms(e,t){var n;return t?Gr((n=(0,ee.descriptionsRegion)(e))===null||n===void 0?void 0:n.node.c).filter(r=>r?.n==="controlDescription"&&(0,ee.normGuid)((0,ee.rawAttr)(r,"forControl"))===t):[]}function dN(e,t){let n=ms(e.bag,(0,ee.controlUniqueId)(t));return n.length===1?Ol(n[0]):void 0}ke.storedBindingOf=dN;function fN(e){let t=(0,ee.effectiveFormType)(e);return t==="Main"||t==="QuickCreate"}ke.supportsPcfFormType=fN;function b0e(e){if(!fN(e))return;let t=(0,ee.controlUniqueIds)(e);for(let{cell:n}of(0,ee.typedCellSites)(e)){let r=n.control;if(!Cn(r)||!r.fieldName||!ps(r.classId)||t.get((0,ee.controlUniqueId)(r))!==1)continue;let i=dN(e,r);i&&i.fieldName===r.fieldName&&(r.customControl=JSON.parse(JSON.stringify(i.binding)))}}ke.projectPcfBindings=b0e;function ps(e){return typeof e=="string"&&e.replace(/^\{|\}$/g,"").toUpperCase()===ee.CUSTOM_CONTROL_CLASS_ID}var no=(e,t)=>({kind:"refused",rule:e,message:t});function v0e(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)&&!ps(e)}function SG(e,t,n){var r,i;let o=Ol(n);if(!o)return no("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 no("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 no("pcf-binding-control-swap",`the binding uses "${o.binding.name}": to use another control, remove customControl, push, then add it`);let a=Cn(t.parameters)?t.parameters:{},s=(r=o.binding.parameters)!==null&&r!==void 0?r:{},u=Object.keys(a).sort();if(!ro(u,Object.keys(s).sort()))return no("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 l=u.filter(g=>!LG(a[g],s[g],o.parameterTypes[g])),c=l.find(g=>hm(o.parameterTypes[g],a[g]).trim()==="");if(c!==void 0)return no("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=MG(t),f=(i=o.binding.formFactors)!==null&&i!==void 0?i:[...hs],p=d.filter(g=>!f.includes(g)),m=f.filter(g=>!d.includes(g));if(l.length===0&&p.length===0&&m.length===0)return{kind:"unchanged"};let h=l.find(g=>!lN(o.parameterTypes[g]));if(h!==void 0){let g=o.parameterTypes[h];return no("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)&&!v0e(o.nativeClass)?no("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:n,stored:o,changed:l,factors:d,added:p,removed:m}}function w0e(e,t){return t&&(0,ee.typedCellSites)(e).find(({cell:r})=>Rn(r.control)&&(0,ee.controlUniqueId)(r.control)===t)?{descriptions:ms(e.bag,t)}:void 0}function xG(e,t){let n=new Map,r=E0e(e),i=new Set,o=new Map,a=l=>{let c=o.get(l);return c||(c={before:[],now:[]},o.set(l,c)),c},s=(l,c)=>({cell:S0e(l),uid:(0,ee.controlUniqueId)(c),bound:Rn(c)});for(let{cell:l}of(0,ee.typedCellSites)(e)){let c=l.control;Cn(c)&&typeof c.id=="string"&&c.id&&a(c.id).now.push({...s(l,c),control:c})}for(let{cell:l}of(0,ee.typedCellSites)(t)){let c=l.control;if(!Cn(c))continue;let d=s(l,c);d.bound&&d.uid&&i.add(d.uid),typeof c.id=="string"&&c.id&&a(c.id).before.push(d)}let u=(l,c)=>{let d=l.filter(f=>f.cell===c);return d.length===1?d[0]:void 0};for(let[l,{before:c,now:d}]of o){let f=c.filter(O=>O.bound&&O.uid!==""&&!r.has(O.uid));if(f.length===0||d.length===0)continue;let p=[...c],m=O=>{let v=p.findIndex(O);return v<0?void 0:p.splice(v,1)[0]},g=d.filter(O=>!O.bound||O.uid===""?!0:m(v=>v.bound&&v.uid===O.uid)!==void 0?!1:!i.has(O.uid)).filter(O=>{let v=O.cell?u(c,O.cell):void 0;return!v||!u(d,O.cell)||!p.includes(v)?!0:(p.splice(p.indexOf(v),1),f.includes(v)&&O.uid!==v.uid&&NG(O.control)&&n.set(O.control,_G(v.uid)),!1)}),y=[],b=(O,v)=>{let N=O.uid===""?void 0:m(S=>S.uid===O.uid&&(!v||S.bound===O.bound));return N&&f.includes(N)&&y.push(N),N!==void 0},w=g.filter(O=>!b(O,!0)).filter(O=>!b(O,!1)&&NG(O.control)),_=f.filter(O=>p.includes(O));if(w.length===0||_.length===0&&y.length===0)continue;let I=[..._,...y],T=_.length===1&&w.length===1&&p.length===1?_G(_[0].uid):`the controls with id "${l}" cannot all be matched to those last synced \u2014 their cells do not tell them apart \u2014 and ${I.map(O=>`{${O.uid}}`).join(", ")} no longer ${I.length===1?"names":"name"} a control: which control held ${I.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 O of w)n.set(O.control,T)}return n}function E0e(e){let t=(0,ee.controlUniqueIds)(e),n=new Map;for(let{cell:i}of(0,ee.typedCellSites)(e)){let o=Cn(i.control)?(0,ee.controlUniqueId)(i.control):"";o&&!n.has(o)&&n.set(o,i.control)}let r=new Set;for(let[i,o]of t){let a=n.get(i);(a===void 0||Rn(a)||o>1)&&r.add(i)}return r}function NG(e){return Rn(e)||e.genPage===void 0&&ps((0,ee.effectiveClassId)(e))}function A0e(e,t){let n=o=>(0,ee.typedCellSites)(o).flatMap(({cell:a,pointer:s})=>{let u=a.control;if(!Cn(u)||Rn(u)||u.genPage!==void 0||!ps((0,ee.effectiveClassId)(u)))return[];let l=(0,ee.controlUniqueId)(u);return l===""||ms(o.bag,l).length===0?[{control:u,pointer:`${s}/control`}]:[]}),r=o=>`${String(o.id)}\0${(0,ee.controlUniqueId)(o)}`,i=n(t).map(({control:o})=>r(o));return n(e).filter(({control:o})=>{let a=i.indexOf(r(o));return a<0?!0:(i.splice(a,1),!1)})}var C0e="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 _G(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 S0e(e){let t=typeof e.id=="string"?e.id.trim():"";return(0,ee.normGuid)(t)||t.toLowerCase()}function gm(e,t,n,r){let i=t.customControl,o=(0,ee.controlUniqueId)(t),a=ms(e.bag,o),s=n?xG(e,n).get(t):void 0;if(s!==void 0)return no("pcf-binding-unique-id",s);let u=n?w0e(n,o):void 0;if(u){let c=u.descriptions,d=c.length===1?Ol(c[0]):void 0;if(d&&d.fieldName!==t.fieldName)return no("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&&ro(c[0],a[0]))return SG(t,i,a[0]);let f=a.length===1?Ol(a[0]):void 0;return d&&f&&f.fieldName===t.fieldName&&oN(i,d)&&oN(i,f)?{kind:"unchanged"}:no("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 no("pcf-binding-other-control","the control already has a description the SDK cannot read as a binding; adding would replace it");let l=SG(t,i,a[0]);return r&&(l.kind==="edit"||l.kind==="unchanged")?l.kind==="unchanged"?l:no("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"):l}ke.planPcfBinding=gm;function FG(e){return e.kind==="edit"&&(e.changed.length>0||e.added.length>0)}function N0e(e){let t=r=>Rn(r.control)&&(!r.control.id||!r.id||(0,ee.authoredUniqueId)(r.control)===void 0);if(!(0,ee.typedCellSites)(e).some(({cell:r})=>t(r)))return e;let n=JSON.parse(JSON.stringify(e));for(let{cell:r}of(0,ee.typedCellSites)(n)){if(!t(r))continue;let i=r.control;i.id||(i.id=(0,AG.newId)()),r.id||(r.id=(0,AG.newId)()),(0,ee.authoredUniqueId)(i)===void 0&&(0,ee.setUniqueId)(i)}return n}ke.mintPcfIdentity=N0e;function _0e(e,t){let n=new Set,r=new Set;for(let{cell:i}of(0,ee.typedCellSites)(e)){let o=i.control;if(!Rn(o)||!Cn(o.customControl))continue;let a=o.customControl.name;if(typeof a!="string"||a===""||typeof o.fieldName!="string"||!o.fieldName)continue;let s=gm(e,o,t,!0);s.kind==="new"?(n.add(a),r.add(o.fieldName)):FG(s)&&n.add(a)}return{controls:[...n],columns:[...r],...r.size>0&&(0,ee.effectiveFormType)(e)==="QuickCreate"?{requireCreateEligibility:!0}:{}}}ke.customControlNeeds=_0e;function I0e(e,t,n){var r,i,o,a,s,u;let l=e.bag,c=new Map;for(let{cell:f,pointer:p}of(0,ee.typedCellSites)(e)){let m=f.control;if(!Rn(m)||!Cn(m.customControl))continue;let h=(0,ee.controlUniqueId)(m);h&&ms(l,h).length>0&&c.set(m,{plan:gm(e,m,t,!0),pointer:`${p}/control/customControl`})}let d=(0,ee.descriptionsRegion)(l);if(d&&t){let f=(0,ee.controlUniqueIds)(e),p=new Set,m=new Map;for(let{cell:h}of(0,ee.typedCellSites)(e)){let g=Cn(h.control)?(0,ee.controlUniqueId)(h.control):"";g&&!m.has(g)&&m.set(g,h.control)}for(let{cell:h}of(0,ee.typedCellSites)(t)){let g=h.control;if(!Rn(g))continue;let y=(0,ee.controlUniqueId)(g),b=ms(t.bag,y),E=ms(l,y);if(b.length!==1||E.length!==1||!ro(b[0],E[0])||!Ol(E[0]))continue;let w=m.get(y);if(w&&!Rn(w)){if(((r=f.get(y))!==null&&r!==void 0?r:0)>1)continue;let _=(o=(i=Ol(E[0]))===null||i===void 0?void 0:i.nativeClass)!==null&&o!==void 0?o:"";w.classId=_.replace(/^\{|\}$/g,"").toUpperCase(),T0e(w,"uniqueid"),p.add(y)}else!w&&!f.has(y)&&p.add(y)}p.size>0&&(d.node.c=Gr(d.node.c).filter(h=>!(h?.n==="controlDescription"&&p.has((0,ee.normGuid)((0,ee.rawAttr)(h,"forControl"))))))}for(let{cell:f}of(0,ee.typedCellSites)(e)){let p=f.control;if(!Rn(p)||!Cn(p.customControl))continue;ps(p.classId)||(p.classId=ee.CUSTOM_CONTROL_CLASS_ID);let m=(0,ee.controlUniqueId)(p);if(!m){if((0,ee.authoredUniqueId)(p)!==void 0)continue;m=(0,ee.setUniqueId)(p)}let h=c.get(p);if(h){if(h.plan.kind==="refused")throw new f0e.ValidationError("form",e.id,[(0,Ye.issue)(h.pointer,h.plan.rule,h.plan.message)]);h.plan.kind==="edit"&&O0e(h.plan,p.customControl);continue}let g=n?.control(p.customControl.name),y=n?.column(e.entityLogicalName,p.fieldName),b=y?.kind==="found"?sN(y.value):void 0;if(g?.kind!=="found"||!b)continue;d||(d={i:(0,ee.embedAppendIndex)(l),node:{n:"controlDescriptions",a:[],c:[]}},l.c.push(d));let E=((u=(s=Gr((a=p.bag)===null||a===void 0?void 0:a.a).find(_=>_[0]==="uniqueid"))===null||s===void 0?void 0:s[1])!==null&&u!==void 0?u:"").trim(),w=E.startsWith("{")?E:`{${m}}`;d.node.c.push($G(w,p.fieldName,b,p.customControl,g.value))}}ke.reconcilePcfDescriptions=I0e;function T0e(e,t){Cn(e.bag)&&(e.bag.a=Gr(e.bag.a).filter(n=>n[0]!==t))}function O0e(e,t){var n,r;let i=Gr(e.description.c),o=i.findIndex(g=>(0,ee.rawAttr)(g,"name")!==void 0),a=i.slice(0,o),s=i.slice(o),u=(n=t.parameters)!==null&&n!==void 0?n:{};for(let g of s)for(let y of(r=wy(g))!==null&&r!==void 0?r:[])e.changed.includes(y.n)&&(y.c=[aN(hm(e.stored.parameterTypes[y.n],u[y.n]))]);if(e.added.length===0&&e.removed.length===0)return;let l=g=>JSON.parse(JSON.stringify(g)),c=g=>{var y;let b=(0,ee.rawAttr)(g,"formFactor");return b===void 0?null:(y=IG.get(b))!==null&&y!==void 0?y:null},d=(0,ee.rawAttr)(a[0],"id"),f=(0,ee.rawAttr)(s[0],"name"),p=Ey(e.factors),m=p.defaults.map(g=>{let y=a.find(E=>c(E)===g);if(y)return y;let b=l(a[0]);return b.a=g===null?[["id",d]]:[["id",d],["formFactor",pm[g]]],b}),h=p.named.map(g=>{let y=s.find(E=>c(E)===g);if(y)return y;let b=l(s[0]);return b.a=[["name",f],["formFactor",pm[g]]],b});e.description.c=[...m,...h]}function D0e(e){return(0,ee.typedCellSites)(e).some(({cell:t})=>Rn(t.control))}ke.mayCommitPcfState=D0e;function P0e(e,t){var n;let r=JSON.parse(JSON.stringify(e)),i=!1;for(let{cell:o}of(0,ee.typedCellSites)(r)){let a=o.control;if(!Rn(a))continue;let s=dN(r,a);if(!s||s.fieldName!==a.fieldName)continue;let u=t(ee.CUSTOM_CONTROL_CLASS_ID),l=Gr((n=a.bag)===null||n===void 0?void 0:n.a).find(c=>c[0]==="classid");(!ps(a.classId)||a.type!==u||l!==void 0&&!ps(l[1])||!ro(a.customControl,s.binding))&&(ps(a.classId)||(a.classId=ee.CUSTOM_CONTROL_CLASS_ID),a.type=u,l&&!ps(l[1])&&(l[1]=OG(ee.CUSTOM_CONTROL_CLASS_ID)),a.customControl=JSON.parse(JSON.stringify(s.binding)),i=!0)}return i?r:e}ke.commitPcfState=P0e;var R0e=new Set(["name","parameters","formFactors"]);function k0e(e,t,n){let r=[],i=(0,ee.controlUniqueIds)(e);for(let{cell:o,pointer:a}of(0,ee.typedCellSites)(e)){let s=o.control;Rn(s)&&L0e(e,s,`${a}/control`,i,r,t,n?.atPush===!0)}return t&&M0e(e,t,r),r}ke.pcfBindingIssues=k0e;function $0e(e,t,n){let r=n.length;if(!Cn(e))return n.push((0,Ye.issue)(t,"pcf-binding-shape","customControl must be an object")),!1;for(let i of Object.keys(e))R0e.has(i)||n.push((0,Ye.issue)(`${t}/${i}`,"pcf-binding-unknown-key",`customControl has no "${i}"`));if((typeof e.name!="string"||e.name.trim()==="")&&n.push((0,Ye.issue)(`${t}/name`,"pcf-binding-shape","name must be the control's non-empty customcontrols name")),e.parameters!==void 0)if(!Cn(e.parameters))n.push((0,Ye.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)||n.push((0,Ye.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"&&hs.includes(a))&&new Set(i).size===i.length||n.push((0,Ye.issue)(`${t}/formFactors`,"pcf-binding-shape","formFactors must be distinct 'web', 'phone' and 'tablet', at least one"))}return n.length===r}function L0e(e,t,n,r,i,o,a){var s;let u=`${n}/customControl`,l=$0e(t.customControl,u,i);t.fieldName||i.push((0,Ye.issue)(u,"pcf-binding-unbound","a PCF binding needs a control bound to a column (fieldName)")),t.genPage!==void 0&&i.push((0,Ye.issue)(u,"pcf-binding-with-genpage","a control cannot embed a page and bind a PCF control")),fN(e)||i.push((0,Ye.issue)(u,"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,Ye.issue)(`${n}/classId`,"pcf-binding-class-id","classId must be a string"));let c=(0,ee.authoredUniqueId)(t),d=(0,ee.controlUniqueId)(t);if(c!==void 0&&!d?i.push((0,Ye.issue)(`${n}/bag`,"pcf-binding-unique-id","the control's uniqueid must be a GUID")):d&&((s=r.get(d))!==null&&s!==void 0?s:0)>1&&i.push((0,Ye.issue)(`${n}/bag`,"pcf-binding-unique-id","another control carries the same uniqueid")),!l)return;let f=gm(e,t,o,a);f.kind==="refused"&&i.push((0,Ye.issue)(u,f.rule,f.message))}function M0e(e,t,n){var r;let i=new Map,o=xG(e,t);for(let{cell:u,pointer:l}of(0,ee.typedCellSites)(e)){let c=Cn(u.control)?(0,ee.controlUniqueId)(u.control):"";if(c&&!i.has(c)&&i.set(c,{control:u.control,pointer:`${l}/control`}),Cn(u.control)&&!Rn(u.control)){let d=o.get(u.control);d!==void 0&&n.push((0,Ye.issue)(`${l}/control`,"pcf-binding-unique-id",d))}}let a=(0,ee.controlUniqueIds)(e);for(let{cell:u}of(0,ee.typedCellSites)(t)){if(!Rn(u.control))continue;let l=(0,ee.controlUniqueId)(u.control),c=i.get(l);!c||Rn(c.control)||(((r=a.get(l))!==null&&r!==void 0?r:0)>1?n.push((0,Ye.issue)(c.pointer,"pcf-binding-unique-id","another control carries this binding\u2019s uniqueid; removing the binding would delete its description too")):ro(ms(t.bag,l),ms(e.bag,l))?c.control.fieldName!==u.control.fieldName&&n.push((0,Ye.issue)(c.pointer,"pcf-binding-rebind","remove the binding, push, then bind the new column")):n.push((0,Ye.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(n.map(u=>u.pointer));for(let{pointer:u}of A0e(e,t))s.has(u)||n.push((0,Ye.issue)(u,"pcf-binding-unique-id",C0e))}var x0e=new Set(["Form.Card"]),F0e="MscrmControls.ModelForm.ModelFormControl";function UG(e,t){var n;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 r=e.properties;if(r.filter(s=>s.usage==="bound").length!==1)return"it has more than one bound property";let i=r.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=>!RG(s));if(o!==void 0)return`the property name "${o}" cannot be written as an element`;if(t===F0e||r.some(s=>s.defaultType!==void 0&&x0e.has(s.defaultType)))return"a property needs a special encoding";if(r.some(s=>s.usage==="output"&&s.defaultValue!==null&&s.defaultValue!==""))return"an output property has a default";let a=r.find(s=>s.usage==="input"&&!lN(s.defaultType));return a?`input "${a.name}" has a type the property editor does not write as text (${(n=a.defaultType)!==null&&n!==void 0?n:"none"})`:void 0}function U0e(e){return e.ofType!==null?[e.ofType]:e.ofTypeGroup}function qG(e,t,n=e.defaultType){if(n==="Enum")return e.enumValues.some(o=>o.value===String(t))?void 0:`must be one of ${e.enumValues.map(o=>`"${o.value}"`).join(", ")}`;let r=n!==void 0?uN.get(n):void 0;if(r){let o=typeof t=="boolean"?void 0:kG(t);return o===void 0||o<r.min||o>r.max?`must be a number from ${r.min.toFixed(r.digits)} through ${r.max.toFixed(r.digits)}`:void 0}if(n!==void 0&&DG.has(n))return t===!0||t===!1||t==="true"||t==="false"?void 0:"must be true or false";let i=n!==void 0?h0e.get(n):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 q0e(e,t,n){var r,i,o,a;let s={issues:[]},u=s.issues;for(let{cell:l,pointer:c}of(0,ee.typedCellSites)(e)){let d=l.control;if(!Rn(d)||!d.fieldName)continue;let f=d.customControl;if(!Cn(f)||typeof f.name!="string")continue;let p=`${c}/control/customControl`,m=gm(e,d,n,!0);if(m.kind==="edit"){FG(m)&&G0e(m,f,p,t,s);continue}if(m.kind!=="new")continue;let h=t?.control(f.name),g=t?.column((r=e.entityLogicalName)!==null&&r!==void 0?r:"",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"){u.push((0,Ye.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 y=UG(h.value,f.name);if(y){u.push((0,Ye.issue)(`${p}/name`,"pcf-binding-unsupported-control",`"${f.name}" is not supported: ${y}`));continue}let b=h.value.properties.find(N=>N.isPrimary),E=g.kind==="found"?g.value:void 0,w=E?(a=(0,p0e.manifestTypesForColumn)(E.attributeTypeName,E.format,E.formatName))!==null&&a!==void 0?a:[]:[];E!==void 0&&!E.isPrimaryId&&E.isValidForForm&&sN(E)!==void 0&&U0e(b).some(N=>w.includes(N))?(0,ee.effectiveFormType)(e)==="QuickCreate"&&E?.isValidForCreate!==!0&&u.push((0,Ye.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`)):u.push((0,Ye.issue)(p,"pcf-binding-incompatible-column",`"${f.name}" cannot be bound to "${d.fieldName}"`));let I=new Map(h.value.properties.filter(N=>N.usage==="input").map(N=>[N.name,N])),T=Cn(f.parameters)?f.parameters:{};for(let[N,S]of Object.entries(T)){let R=I.get(N);if(!R){u.push((0,Ye.issue)(`${p}/parameters/${N}`,"pcf-binding-unknown-parameter",`"${f.name}" has no input "${N}"`));continue}let x=qG(R,S);x&&u.push((0,Ye.issue)(`${p}/parameters/${N}`,"pcf-binding-parameter-value",`"${N}" ${x}`))}for(let N of I.values())N.required&&!mm(T,N.name)&&!N.defaultValue&&u.push((0,Ye.issue)(`${p}/parameters`,"pcf-binding-missing-parameter",`"${N.name}" is required`));let O=cN(h.value),v=Array.isArray(f.formFactors)?f.formFactors:void 0;(v?v.some(N=>!O.has(N)):O.size===0)&&u.push((0,Ye.issue)(`${p}/formFactors`,"pcf-binding-form-factor",`"${f.name}" is available on ${O.size===0?"no form factor":[...O].join(", ")}`))}return s}ke.pcfReadIssues=q0e;function B0e(e,t){return t===void 0||!lN(t)?!1:e.ofType!==null?e.ofType===t:e.ofTypeGroup.includes(t)}function V0e(e,t,n){var r,i;let o=UG(e,t);if(o)return`it is no longer supported (${o})`;let a=e.properties.find(d=>d.isPrimary);if(a?.name!==n.boundProperty)return`its bound property is now "${(r=a?.name)!==null&&r!==void 0?r:"none"}", not "${n.boundProperty}"`;let s=(i=n.binding.parameters)!==null&&i!==void 0?i:{},u=new Set(e.properties.filter(d=>d.usage==="input").map(d=>d.name)),l=Object.keys(s).find(d=>!u.has(d));if(l!==void 0)return`"${l}" is no longer one of its inputs`;let c=e.properties.find(d=>d.usage==="input"&&d.required&&!d.defaultValue&&!mm(s,d.name));return c?`it now requires "${c.name}", which the binding does not store`:void 0}function G0e(e,t,n,r,i){var o,a,s;let u=i.issues,l=r?.control(t.name);if(!l||l.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`,...l?.kind==="unavailable"?{cause:l.error}:{}});return}if(l.kind!=="found"){u.push((0,Ye.issue)(`${n}/name`,"PCF_CONTROL_NOT_FOUND",`no single installed control is named "${t.name}" (${l.kind})`));return}let c=V0e(l.value,t.name,e.stored);if(c){u.push((0,Ye.issue)(n,"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(l.value.properties.filter(h=>h.usage==="input").map(h=>[h.name,h])),f=u.length;for(let h of Object.keys((a=e.stored.binding.parameters)!==null&&a!==void 0?a:{})){let g=e.stored.parameterTypes[h];B0e(d.get(h),g)||u.push((0,Ye.issue)(`${n}/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(u.length>f)return;let p=(s=t.parameters)!==null&&s!==void 0?s:{};for(let h of e.changed){let g=qG(d.get(h),p[h],e.stored.parameterTypes[h]);g&&u.push((0,Ye.issue)(`${n}/parameters/${h}`,"pcf-binding-parameter-value",`"${h}" ${g}`))}let m=cN(l.value);e.added.some(h=>!m.has(h))&&u.push((0,Ye.issue)(`${n}/formFactors`,"pcf-binding-form-factor",`"${t.name}" is available on ${m.size===0?"no form factor":[...m].join(", ")}`))}});var r4=C(wi=>{"use strict";Object.defineProperty(wi,"__esModule",{value:!0});wi.classIdForAttributeType=wi.QUICK_VIEW_CLASS_ID=wi.NOTES_CLASS_ID=wi.SUBGRID_CLASS_ID=wi.formRegistration=wi.FormAdapter=void 0;var gs=(Dn(),_i(G2)),VG=(En(),_i(j2)),j0e=(Jn(),_i(z2)),kn=(Re(),_i(W2)),cn=(bl(),_i(H2)),W0e=(jS(),_i(pG)),z0e=(hG(),_i(mG)),$n=Us(),GG=mo(),vi=Vi(),H0e=mg(),Od=ft(),K0e=vy(),_r=dg(),ya=BG(),Td=Y(),bN=ae(),pN=Ga(),JG=fl(),J0e={[kn.FormType.Main]:"Main",[kn.FormType.QuickCreate]:"QuickCreate",[kn.FormType.QuickViewForm]:"QuickView",[kn.FormType.Card]:"Card"},Ay={Main:kn.FormType.Main,QuickCreate:kn.FormType.QuickCreate,QuickView:kn.FormType.QuickViewForm,Card:kn.FormType.Card},Y0e=new Map(Object.entries(cn.ControlClassId).map(([e,t])=>[String(t).toUpperCase(),e]));function vN(e){var t;return e&&(t=Y0e.get(e.toUpperCase()))!==null&&t!==void 0?t:"Unknown"}function ym(e){return e.getAllProperties().map(t=>[t.key,t.value])}function Dl(e){let t=new Map;for(let n of e.getAllProperties())t.has(n.key)||t.set(n.key,n.value);return t}function YG(e,t){return e.getAllChildren().find(n=>n.getNodeName()===t)}function wN(e,t){var n,r;let i=YG(e,"labels");if(!i)return"";let o=i.getAllChildren().filter(s=>s.getNodeName()==="label"),a=(n=o.find(s=>Dl(s).get("languagecode")===String(t)))!==null&&n!==void 0?n:o[0];return a&&(r=Dl(a).get("description"))!==null&&r!==void 0?r:""}function Q0e(e){let t=YG(e,"parameters"),n={};if(!t)return n;for(let r of t.getAllChildren()){let i=r.getNodeName();if(i.charAt(0)==="<"||i.charAt(0)==="#")continue;let o=r.getAllChildren()[0],a=o?o.getNodeName():"";a.charAt(0)==="<"&&(a=a.substring(1)),n[i]=a}return n}function QG(e){return/^1+$/.test(e)&&e.length>=1&&e.length<=4?e.length:1}function mN(e){let t=Math.min(Math.max(Math.trunc(e),1),4);return"1".repeat(t)}function bm(e){return String(e??"").replace(/[{}]/g,"")}function hN(e){return`{${bm(e)}}`}function gN(e,t){if(e===void 0||e==="")return t;let n=Number(e);return Number.isNaN(n)?t:n}function Sy(e,t,n){let r=e.getAllChildren(),i=r.findIndex(l=>l.getNodeName()===t),o=[];if(r.forEach((l,c)=>{c!==i&&o.push({i:c,node:(0,$n.rawFromNode)(l)})}),i<0)return{modeled:[],bag:{a:ym(e),c:o}};let a=r[i],s=[],u=[];return a.getAllChildren().forEach((l,c)=>{l.getNodeName()===n?s.push(l):u.push({i:c,node:(0,$n.rawFromNode)(l)})}),{modeled:s,bag:{a:ym(e),c:o,w:{n:a.getNodeName(),a:ym(a),c:u}}}}function XG(e,t,n){let r=[],i=[];return e.getAllChildren().forEach((o,a)=>{o.getNodeName()===t&&(!n||r.length===0)?r.push(o):i.push({i:a,node:(0,$n.rawFromNode)(o)})}),{modeled:r,bag:{a:ym(e),c:i}}}function jG(e,t){let{modeled:n,bag:r}=Sy(e,"tabs","tab");return{tabs:n.map(i=>X0e(i,t)),bag:r}}function X0e(e,t){var n,r;let i=Dl(e),{modeled:o,bag:a}=Sy(e,"columns","column");return{id:(n=i.get("id"))!==null&&n!==void 0?n:"",name:(r=i.get("name"))!==null&&r!==void 0?r:"",label:wN(e,t),expanded:i.get("expanded")==="true",visible:i.has("visible")?i.get("visible")==="true":!0,columns:o.map(s=>Z0e(s,t)),bag:a}}function Z0e(e,t){let n=Dl(e),{modeled:r,bag:i}=Sy(e,"sections","section");return{width:n.get("width"),sections:r.map(o=>eye(o,t)),bag:i}}function eye(e,t){var n,r,i;let o=Dl(e),{modeled:a,bag:s}=Sy(e,"rows","row");return{id:(n=o.get("id"))!==null&&n!==void 0?n:"",name:(r=o.get("name"))!==null&&r!==void 0?r:"",label:wN(e,t),visible:o.has("visible")?o.get("visible")==="true":!0,showLabel:o.get("showlabel")==="true",columns:QG((i=o.get("columns"))!==null&&i!==void 0?i:"1"),rows:a.map(u=>tye(u,t)),bag:s}}function tye(e,t){let{modeled:n,bag:r}=XG(e,"cell",!1);return{cells:n.map(i=>nye(i,t)),bag:r}}function nye(e,t){var n;let r=Dl(e),{modeled:i,bag:o}=XG(e,"control",!0),a=wN(e,t),s=r.get("showlabel")==="true",u=i[0]?rye(i[0],a,s):null;return{id:(n=r.get("id"))!==null&&n!==void 0?n:"",visible:r.has("visible")?r.get("visible")==="true":!0,colspan:gN(r.get("colspan"),1),rowspan:gN(r.get("rowspan"),1),control:u,bag:o}}function rye(e,t,n){var r,i;let o=Dl(e),a=bm((r=o.get("classid"))!==null&&r!==void 0?r:""),s=o.get("datafieldname");return{id:(i=o.get("id"))!==null&&i!==void 0?i:"",classId:a,fieldName:s||null,type:vN(a),isRequired:o.get("isrequired")==="true",isReadOnly:o.get("disabled")==="true",label:t,showLabel:n,parameters:Q0e(e),bag:{a:ym(e),c:e.getAllChildren().map((u,l)=>({i:l,node:(0,$n.rawFromNode)(u)}))}}}function bu(e){return e.a.length===0&&e.c.length===0&&!e.w}function ZG(e,t){let n=e.a.find(r=>r[0]===t);return n?n[1]:void 0}function Pl(e,t){var n;let r=new Set(e.a.map(a=>a[0])),i=bu(e),o=[];for(let a of t)if(r.has(a.key)){let s=(n=ZG(e,a.key))!==null&&n!==void 0?n:"";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,$n.mergeAttrs)(e.a,o)}var gu=(e,t)=>({key:e,matches:n=>n===t,render:()=>t,absentDefault:""}),yu=(e,t,n=!1)=>({key:e,matches:r=>r==="true"===t,render:()=>String(t),absentDefault:String(n)}),WG=(e,t,n=1)=>({key:e,matches:r=>gN(r,n)===t,render:()=>String(t),absentDefault:String(n)});function EN(e,t){return{n:"labels",a:[],c:[{n:"label",a:[["description",e],["languagecode",String(t)]],c:[]}]}}function yN(e){return{n:"parameters",a:[],c:Object.keys(e).map(t=>{var n;return{n:(0,bN.assertXmlName)(t,"Form control parameter name"),a:[],c:[{n:`<${(n=e[t])!==null&&n!==void 0?n:""}`,a:[],c:[]}]}})}}function iye(e,t){var n,r;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(r=(n=o?.a.find(a=>a[0]==="description"))===null||n===void 0?void 0:n[1])!==null&&r!==void 0?r:""}function oye(e,t,n){let r=!1,i=e.c.map(o=>o.n!=="label"||!o.a.some(s=>s[0]==="languagecode"&&s[1]===String(n))?o:(r=!0,{...o,a:o.a.map(s=>s[0]==="description"?["description",t]:s)}));return r||i.push({n:"label",a:[["description",t],["languagecode",String(n)]],c:[]}),{...e,c:i}}function AN(e,t,n){let r=e.c.findIndex(o=>o.node.n==="labels");if(r<0){if(!t||bu(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:EN(t,n)},...a]}}if(iye(e.c[r].node,n)===t)return e;let i=oye(e.c[r].node,t,n);return{...e,c:e.c.map((o,a)=>a===r?{...o,node:i}:o)}}function aye(e){let t={};for(let n of e.c){let r=n.n;if(r.charAt(0)==="<"||r.charAt(0)==="#")continue;let i=n.c[0],o=i?i.n:"";o.charAt(0)==="<"&&(o=o.substring(1)),t[r]=o}return t}function sye(e,t){let n=Object.keys(e),r=Object.keys(t);return n.length===r.length&&n.every(i=>e[i]===t[i])}function uye(e,t){return e.a.some(n=>n[0]===t)?{...e,a:e.a.filter(n=>n[0]!==t)}:e}function lye(e,t){let n=e.c.findIndex(i=>i.node.n==="parameters");if(n<0){if(Object.keys(t).length===0||bu(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:yN(t)}]}}if(sye(aye(e.c[n].node),t))return e;let r=yN(t);return{...e,c:e.c.map((i,o)=>o===n?{...i,node:r}:i)}}function Ny(e,t,n,r){if(e.w){let a={n:e.w.n,a:e.w.a.map(s=>[s[0],s[1]]),c:(0,$n.spliceChildren)(e.w.c,n)};return(0,$n.spliceChildren)(e.c,[a])}let i=r(),o={n:t,a:[],c:n};return e.c.length===0?[...i,o]:(0,$n.spliceChildren)(e.c,[...i,o])}function cye(e,t){let n=e.tabs.map(r=>dye(r,t));return{n:"form",a:Pl(e.bag,[]),c:e.tabs.length===0&&bu(e.bag)?[]:Ny(e.bag,"tabs",n,()=>[])}}function e4(e,t,n){return t&&!e.c.some(r=>r.node.n==="labels")?[EN(t,n)]:[]}function dye(e,t){let n=[gu("id",e.id),gu("name",e.name),yu("expanded",e.expanded),yu("visible",e.visible,!0)],r=e.columns.map(o=>fye(o,t)),i=AN(e.bag,e.label,t);return{n:"tab",a:Pl(i,n),c:Ny(i,"columns",r,()=>e4(i,e.label,t))}}function fye(e,t){let n=e.width!==void 0?[gu("width",e.width)]:[],r=e.sections.map(i=>pye(i,t));return{n:"column",a:Pl(e.bag,n),c:Ny(e.bag,"sections",r,()=>[])}}function pye(e,t){let n=[gu("id",e.id),gu("name",e.name),yu("showlabel",e.showLabel),yu("visible",e.visible,!0),{key:"columns",matches:o=>QG(o)===e.columns,render:()=>mN(e.columns),absentDefault:mN(1)}],r=e.rows.map(o=>mye(o,t)),i=AN(e.bag,e.label,t);return{n:"section",a:Pl(i,n),c:Ny(i,"rows",r,()=>e4(i,e.label,t))}}function mye(e,t){let n=e.cells.map(r=>hye(r,t));return{n:"row",a:Pl(e.bag,[]),c:bu(e.bag)?n:(0,$n.assembleChildren)(e.bag,n)}}function hye(e,t){let n=e.control?e.control.showLabel:ZG(e.bag,"showlabel")==="true",r=[gu("id",e.id),yu("showlabel",n),yu("visible",e.visible,!0),WG("colspan",e.colspan),WG("rowspan",e.rowspan)],i=e.control?[gye(e.control)]:[],o;if(bu(e.bag))o=[...e.control&&e.control.label?[EN(e.control.label,t)]:[],...i];else{let a=e.control?AN(e.bag,e.control.label,t):e.bag;o=(0,$n.assembleChildren)(a,i)}return{n:"cell",a:Pl(e.bag,r),c:o}}function gye(e){let t=[gu("id",e.id),{key:"classid",matches:i=>bm(i)===e.classId,render:()=>hN(e.classId||String(cn.ControlClassId.TextboxControl)),absentDefault:""}];e.fieldName!==null&&t.push(gu("datafieldname",e.fieldName)),t.push(yu("disabled",e.isReadOnly)),t.push(yu("isrequired",e.isRequired));let n=e.fieldName===null?uye(e.bag,"datafieldname"):e.bag,r;return bu(n)?r=Object.keys(e.parameters).length>0?[yN(e.parameters)]:[]:r=(0,$n.assembleChildren)(lye(n,e.parameters),[]),{n:"control",a:Pl(n,t),c:r}}var yye={make:(e,t)=>new j0e.FormElementNode(e,t),setProp:(e,t,n)=>e.setProperty(t,n),addChild:(e,t)=>e.addChild(t)};function zG(e,t,n,r){(0,pN.installDomShim)();let i=vye(e,n);(0,_r.reconcileEmbedDescriptions)(i,r),(0,ya.reconcilePcfDescriptions)(i,r,n?.pcf);let o=(0,$n.rebuildRaw)(cye(i,t),yye,null);return new z0e.SerializationService(t).serializeFormXmlNode(o)}function bye(e){return JSON.parse(JSON.stringify(e))}function vye(e,t){let n=bye(e);n.bag||(n.bag=(0,$n.emptyBag)()),n.tabs||(n.tabs=[]),Iye(n.bag),t&&wye(n,t);for(let r of n.tabs)Eye(r);return n}function wye(e,t){var n;let r=(n=e.entityLogicalName)!==null&&n!==void 0?n:"";CN(e,i=>{let o=i.fieldName,a=i;if(!o||a.label!==void 0&&a.classId!==void 0)return;let s=t.resolveField(r,o);s&&(a.label===void 0&&s.displayName&&(a.label=s.displayName),a.classId===void 0&&s.attributeType&&(a.classId=n4(s.attributeType)))})}function HG(e){let t=[];return CN(e,n=>t.push(n)),t}function CN(e,t){var n,r,i,o,a;for(let s of(n=e.tabs)!==null&&n!==void 0?n:[])for(let u of(r=s.columns)!==null&&r!==void 0?r:[])for(let l of(i=u.sections)!==null&&i!==void 0?i:[])for(let c of(o=l.rows)!==null&&o!==void 0?o:[])for(let d of(a=c.cells)!==null&&a!==void 0?a:[])d.control&&t(d.control)}function Eye(e){e.id||(e.id=gs.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)Aye(t);e.bag||(e.bag=(0,$n.emptyBag)())}function Aye(e){e.sections||(e.sections=[]);for(let t of e.sections)Cye(t);e.bag||(e.bag=(0,$n.emptyBag)()),e.width===void 0&&bu(e.bag)&&(e.width="100%")}function Cye(e){e.id||(e.id=gs.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)Sye(t);e.bag||(e.bag=(0,$n.emptyBag)())}function Sye(e){e.cells||(e.cells=[]);for(let t of e.cells)Nye(t);e.bag||(e.bag=(0,$n.emptyBag)())}function Nye(e){(0,_r.hasGenPage)(e.control)&&(0,_r.applyEmbedCellDefaults)(e),e.id||(e.id=gs.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&&_ye(e.control),e.bag||(e.bag=(0,$n.emptyBag)())}function _ye(e){var t;(0,_r.hasGenPage)(e)&&(0,_r.applyEmbedControlDefaults)(e),e.id||(e.id=gs.Guid.NewGuid()),(e.classId===void 0||e.classId===null)&&(e.classId=String(cn.ControlClassId.TextboxControl)),e.fieldName===void 0&&(e.fieldName=null),e.type===void 0&&(e.type=e.fieldName?"Field":vN(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 n of Object.keys(e.parameters))(0,bN.assertXmlName)(n,"Form control parameter name");e.bag||(e.bag=(0,$n.emptyBag)())}function Iye(e){for(let t of e.c){let n=t.node;if(n.n==="events"){for(let r of n.c)if(r.n==="event"){for(let i of r.c)if(i.n==="Handlers")for(let o of i.c)o.n==="Handler"&&!KG(o,"handlerUniqueId")&&o.a.push(["handlerUniqueId",hN(gs.Guid.NewGuid())])}}else if(n.n==="formLibraries")for(let r of n.c)r.n==="Library"&&!KG(r,"libraryUniqueId")&&r.a.push(["libraryUniqueId",hN(gs.Guid.NewGuid())])}}var Cy=class{constructor(t=JG.DEFAULT_LCID){this.lcid=t}toArtifact(t,n){var r,i,o;let{tabs:a,bag:s}=jG(t,this.lcid),u={id:t.formId?t.formId.guidString:"",name:(r=t.formName)!==null&&r!==void 0?r:"",entityLogicalName:(i=t.entityName)!==null&&i!==void 0?i:"",formType:(o=J0e[t.formType])!==null&&o!==void 0?o:"Main",status:this.readActivationStatus(t),...n!==void 0&&n!==""?{description:n}:{},tabs:a,bag:s};return(0,_r.projectGenPageEmbeds)(u),(0,ya.projectPcfBindings)(u),u}fromArtifact(t){var n;return this.deserialize({formxml:zG(t,this.lcid),formid:t.id||(0,Od.newId)(),objecttypecode:t.entityLogicalName,type:Ay[t.formType],name:t.name,uniquename:t.name,description:(n=t.description)!==null&&n!==void 0?n:"",formpresentation:kn.FormPresentation.AirForm,formactivationstate:t.status==="Active"?kn.FormActivationState.Active:kn.FormActivationState.InActive})}fromApiResponse(t){var n,r,i,o,a,s,u;let l=t,c=(n=l.formxml)!==null&&n!==void 0?n:"",d={formxml:c,formid:(r=l.formid)!==null&&r!==void 0?r:(0,Od.newId)(),objecttypecode:(i=l.objecttypecode)!==null&&i!==void 0?i:"",type:l.type,name:(o=l.name)!==null&&o!==void 0?o:"",uniquename:(a=l.uniquename)!==null&&a!==void 0?a:"",description:(s=l.description)!==null&&s!==void 0?s:"",formpresentation:l.formpresentation,formactivationstate:l.formactivationstate};(0,pN.installDomShim)();let f=VG.ScriptUtilities.ParseXml(c),p=Tye(f),m=this.deserializeDocument(d,f);return Oye(this.toArtifact(m,(u=l.description)!==null&&u!==void 0?u:void 0),p)}toApiPayload(t,n,r){let i=(0,_r.genPageEmbedIssues)(t);if(i.length>0)throw new Td.ValidationError("form",t.id,i);let o=(0,ya.pcfBindingIssues)(t,n,{atPush:!0});if(o.length>0)throw new Td.ValidationError("form",t.id,o);let a=(0,ya.pcfReadIssues)(t,r?.pcf,n);if(a.unavailable)throw(0,Td.attachCause)(new Td.SdkError(a.unavailable.code,a.unavailable.message),a.unavailable.cause);if(a.issues.length>0)throw new Td.ValidationError("form",t.id,a.issues);return{formxml:zG(t,this.lcid,r,n),name:t.name,type:Ay[t.formType],objecttypecode:t.entityLogicalName,...t.description!==void 0?{description:t.description}:{}}}metadataNeeds(t){let n=t.entityLogicalName;if(!n)return[];let r=new Map;return CN(t,i=>{var o;let a=i.fieldName,s=i;if(!a||s.label!==void 0&&s.classId!==void 0)return;let u=(o=r.get(a))!==null&&o!==void 0?o:{entityLogicalName:n,fieldName:a};s.label===void 0&&(u.needsLabel=!0),r.set(a,u)}),[...r.values()]}customControlNeeds(t,n){var r;return{entityLogicalName:(r=t.entityLogicalName)!==null&&r!==void 0?r:"",...(0,ya.customControlNeeds)(t,n)}}createDefault(t){var n,r,i,o,a,s,u,l,c,d,f,p;let m=[...(0,_r.genPageEmbedIssues)(t),...(0,ya.pcfBindingIssues)(t)];if(m.length>0)throw new Td.ValidationError("form",t.id||"(new)",m);let h=t.tabs&&t.tabs.length>0?void 0:Uye(this.lcid),g=h!==void 0?h:t.tabs.map(E=>Dye(E,this.lcid)).join(""),y=this.deserialize({formxml:`<form><tabs>${g}</tabs></form>`,formid:t.id||(0,Od.newId)(),objecttypecode:(n=t.entityLogicalName)!==null&&n!==void 0?n:"",type:Ay[(r=t.formType)!==null&&r!==void 0?r:"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:kn.FormPresentation.AirForm,formactivationstate:((s=t.status)!==null&&s!==void 0?s:"Active")==="Active"?kn.FormActivationState.Active:kn.FormActivationState.InActive});(u=y.displayCondition)===null||u===void 0||u.removeProperty(kn.ElementProperties.Order);let b=this.toArtifact(y,t.description);if(t.tabs&&t.tabs.length>0){let E=HG(t);HG(b).forEach((w,_)=>{E[_]&&E[_].label===void 0&&delete w.label,E[_]&&E[_].genPage!==void 0&&(w.genPage=JSON.parse(JSON.stringify(E[_].genPage))),E[_]&&E[_].customControl!==void 0&&(w.customControl=JSON.parse(JSON.stringify(E[_].customControl)))})}return{id:(l=t.id)!==null&&l!==void 0?l:b.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:(p=t.status)!==null&&p!==void 0?p:"Active",...t.description!==void 0?{description:t.description}:{},tabs:b.tabs,bag:b.bag}}assignMissingIds(t){return(0,Od.assignMissingIds)(t)}completeAsStored(t,n){return(0,K0e.completeRecordAsStored)(t,n,this.lcid)}normalize(t){return(0,ya.mintPcfIdentity)((0,_r.mintEmbedIdentity)(t))}committed(t,n){var r,i,o,a,s,u;let l=n?.formxml;if(typeof l!="string"||!((0,_r.mayCommitEmbedState)(t)||(0,ya.mayCommitPcfState)(t)))return{artifact:t,baseline:t};let c=this.deserialize({formxml:l,formid:t.id||(0,Od.newId)(),objecttypecode:(r=t.entityLogicalName)!==null&&r!==void 0?r:"",type:Ay[(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:kn.FormPresentation.AirForm,formactivationstate:kn.FormActivationState.Active}),{bag:d}=jG(c,this.lcid),f=(0,ya.commitPcfState)((0,_r.commitEmbedState)(t,(u=(0,_r.descriptionsRegion)(d))===null||u===void 0?void 0:u.node),vN);return{artifact:f,baseline:f}}validate(t){return Kye(t)}deserialize(t){return(0,pN.installDomShim)(),this.deserializeDocument(t,VG.ScriptUtilities.ParseXml(t.formxml))}deserializeDocument(t,n){let r=new W0e.DeserializationService(this.lcid).deSerializeFormXml(n,new gs.Guid(t.formid),t.objecttypecode,kn.FormState.Draft,t.name,t.uniquename,t.type,t.formpresentation,t.description,t.formactivationstate);if(!r)throw new Error("FormXml could not be deserialized into a Form model.");return r}readActivationStatus(t){return t.formactivationstate===kn.FormActivationState.InActive?"Inactive":"Active"}};wi.FormAdapter=Cy;var t4=["header","footer","DisplayConditions"];function Tye(e){var t;let n=e?.getElementsByTagName("form")[0],r=new Set;for(let i=(t=n?.firstChild)!==null&&t!==void 0?t:null;i;i=i.nextSibling)i.nodeType===1&&t4.includes(i.nodeName)&&r.add(i.nodeName);return r}function Oye(e,t){var n;if(!(!((n=e.bag)===null||n===void 0)&&n.c))return e;let r=t4.filter(o=>!t.has(o)),i=e.bag.c.filter(o=>{var a;return r.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!r.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 Ro(e){return String(e??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function SN(e,t){return e?`<labels><label description="${Ro(e)}" languagecode="${t}" /></labels>`:""}function NN(e){return e&&e.length>0?bm(e):(0,Od.newId)()}function Dye(e,t){var n,r,i,o;let a=(n=e.columns)!==null&&n!==void 0?n:[],s=(a.length>0?a:[Fye()]).map(u=>Pye(u,t)).join("");return`<tab id="{${Ro(NN(e.id))}}" name="${Ro((r=e.name)!==null&&r!==void 0?r:"")}" expanded="${(i=e.expanded)!==null&&i!==void 0?i:!0}" visible="${(o=e.visible)!==null&&o!==void 0?o:!0}">${SN(e.label,t)}<columns>${s}</columns></tab>`}function Pye(e,t){var n,r;let i=((n=e.sections)!==null&&n!==void 0?n:[]).map(o=>Rye(o,t)).join("");return`<column width="${Ro((r=e.width)!==null&&r!==void 0?r:"100%")}"><sections>${i}</sections></column>`}function Rye(e,t){var n,r,i,o,a;let s=((n=e.rows)!==null&&n!==void 0?n:[]).map(u=>kye(u,t)).join("");return`<section id="{${Ro(NN(e.id))}}" name="${Ro((r=e.name)!==null&&r!==void 0?r:"")}" showlabel="${(i=e.showLabel)!==null&&i!==void 0?i:!1}" visible="${(o=e.visible)!==null&&o!==void 0?o:!0}" columns="${mN((a=e.columns)!==null&&a!==void 0?a:1)}">${SN(e.label,t)}<rows>${s}</rows></section>`}function kye(e,t){var n;return`<row>${((n=e.cells)!==null&&n!==void 0?n:[]).map(r=>$ye(r,t)).join("")}</row>`}function $ye(e,t){var n,r,i,o,a;let s=Lye(e),u=s.control,l=u?SN((n=u.label)!==null&&n!==void 0?n:"",t):"",c=u?Mye(u):"";return`<cell id="{${Ro(NN(s.id))}}" showlabel="${u?(r=u.showLabel)!==null&&r!==void 0?r:!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}">${l}${c}</cell>`}function Lye(e){if(!(0,_r.hasGenPage)(e.control))return e;let t={...e.control};(0,_r.applyEmbedControlDefaults)(t);let n={...e,control:t};return(0,_r.applyEmbedCellDefaults)(n),n}function Mye(e){var t,n,r;let i=e.fieldName?` datafieldname="${Ro(e.fieldName)}"`:"",o=xye(e.parameters),a=e.classId?bm(e.classId):String(cn.ControlClassId.TextboxControl);return`<control id="${Ro((t=e.id)!==null&&t!==void 0?t:"")}" classid="{${Ro(a)}}"${i} disabled="${(n=e.isReadOnly)!==null&&n!==void 0?n:!1}" isrequired="${(r=e.isRequired)!==null&&r!==void 0?r:!1}">${o}</control>`}function xye(e){let t=Object.keys(e??{});return t.length===0?"":(t.forEach(r=>(0,bN.assertXmlName)(r,"Form control parameter name")),`<parameters>${t.map(r=>`<${r}>${Ro(e[r])}</${r}>`).join("")}</parameters>`)}function Fye(){return{width:"100%",sections:[],bag:{a:[],c:[]}}}function Uye(e){return`<tab id="{${gs.Guid.NewGuid()}}" name="tab_general" expanded="true" visible="true"><labels><label description="General" languagecode="${e}" /></labels><columns><column width="100%"><sections><section id="{${gs.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 qye(e=JG.DEFAULT_LCID){return{adapter:new Cy(e),api:H0e.formApi,languageSensitive:!0,publish:(t,n,r)=>(0,GG.publishBoundEntity)(t,r),publishScope:(t,n)=>(0,GG.boundEntityPublishScope)(n),rebaselineAfterPublish:"bracket"}}wi.formRegistration=qye;var Bye=new Set(["id","name","label","expanded","visible","columns","bag"]),Vye=new Set(["id","width","sections","bag"]),Gye=new Set(["id","name","label","visible","showLabel","columns","rows","bag"]),jye=new Set(["id","cells","bag"]),Wye=new Set(["id","visible","colspan","rowspan","control","bag"]),zye=new Set(["id","classId","fieldName","type","isRequired","isReadOnly","label","showLabel","parameters","genPage","customControl","bag"]),Hye={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 Kye(e){let t=[];return(0,vi.childObjects)(e,"tabs","","tab",t).forEach(({node:r,index:i})=>{let o=`/tabs/${i}`;(0,vi.rejectUnknownKeys)(r,Bye,o,"tab",t),(0,vi.childObjects)(r,"columns",o,"column",t).forEach(({node:s,index:u})=>{let l=`${o}/columns/${u}`;(0,vi.rejectUnknownKeys)(s,Vye,l,"column",t),(0,vi.childObjects)(s,"sections",l,"section",t).forEach(({node:d,index:f})=>{let p=`${l}/sections/${f}`;(0,vi.rejectUnknownKeys)(d,Gye,p,"section",t),(0,vi.childObjects)(d,"rows",p,"row",t).forEach(({node:h,index:g})=>{let y=`${p}/rows/${g}`;(0,vi.rejectUnknownKeys)(h,jye,y,"row",t),(0,vi.childObjects)(h,"cells",y,"cell",t).forEach(({node:E,index:w})=>{let _=`${y}/cells/${w}`;(0,vi.rejectUnknownKeys)(E,Wye,_,"cell",t,Hye);let I=E.control;I!=null&&!(0,vi.isJsonObject)(I)?t.push((0,vi.issue)(`${_}/control`,"control-must-be-object-or-null",`a cell control must be a JSON object or null, got ${typeof I}`)):(0,vi.isJsonObject)(I)&&(0,vi.rejectUnknownKeys)(I,zye,`${_}/control`,"control",t)})})})})}),t.push(...(0,_r.genPageEmbedIssues)(e)),t.push(...(0,ya.pcfBindingIssues)(e)),t}wi.SUBGRID_CLASS_ID=cn.ControlClassId.SubgridControl;wi.NOTES_CLASS_ID=cn.ControlClassId.TimelineControl;wi.QUICK_VIEW_CLASS_ID=cn.ControlClassId.QuickViewControl;var Jye={Lookup:String(cn.ControlClassId.LookupControl),Customer:String(cn.ControlClassId.LookupControl),Owner:String(cn.ControlClassId.LookupControl),PartyList:String(cn.ControlClassId.PartyListControl),Boolean:String(cn.ControlClassId.BooleanControl),DateTime:String(cn.ControlClassId.DateTimeControl),Decimal:String(cn.ControlClassId.DecimalControl),Double:String(cn.ControlClassId.FloatingNumberControl),Money:String(cn.ControlClassId.CurrencyControl),Integer:String(cn.ControlClassId.IntegerControl),BigInt:String(cn.ControlClassId.IntegerControl),Memo:String(cn.ControlClassId.TextAreaControl),String:String(cn.ControlClassId.TextboxControl)},Yye="3EF39988-22BB-4F0B-BBBE-64B5A3748AEE";function n4(e){return e==="Picklist"||e==="State"||e==="Status"?Yye:e&&Jye[e]||String(cn.ControlClassId.TextboxControl)}wi.classIdForAttributeType=n4;function KG(e,t){let n=e.a.find(r=>r[0]===t);return n?n[1]:void 0}});var IN=C(Rl=>{"use strict";Object.defineProperty(Rl,"__esModule",{value:!0});Rl.viewApi=Rl.findDefaultViews=void 0;var s4=Ke(),_N=qi(),Ir=pe(),io=ae(),Qye=Ms(),i4="savedqueryid,name,description,fetchxml,layoutxml,querytype,returnedtypecode,isdefault",Xye="savedqueryid,name,returnedtypecode,querytype,isdefault",Zye=60*1e3;function _y(e){return(e.localName||e.nodeName).toLowerCase()}function vm(e,t){let n;for(let r=0;r<e.attributes.length;r+=1){let i=e.attributes[r];i.nodeName.toLowerCase()===t&&(n=n===void 0?i.value:null)}return n}function ebe(e){if(!e)return;let t=!0,n=()=>{t=!1},r=new Qye.DOMParser({errorHandler:{warning:n,error:n,fatalError:n}}).parseFromString(e,"text/xml").documentElement;return t&&r&&_y(r)==="fetch"?r:void 0}function tbe(e){for(let t=e.parentNode;t;t=t.parentNode)if(_y(t)==="link-entity")return!0;return!1}function o4(e,t){var n,r,i;if(((n=e.canbedeleted)===null||n===void 0?void 0:n.Value)!==!1)return!1;let o=ebe(e.fetchxml);if(!o)return!1;let a=Array.from(o.getElementsByTagName("*")),s=a.filter(l=>_y(l)==="condition"),u=s.length===1?s[0]:void 0;return u!==void 0&&a.filter(l=>_y(l)==="link-entity").every(l=>{var c;return((c=vm(l,"link-type"))===null||c===void 0?void 0:c.toLowerCase())==="outer"})&&!tbe(u)&&vm(u,"entityname")===void 0&&((r=vm(u,"attribute"))===null||r===void 0?void 0:r.toLowerCase())==="statecode"&&((i=vm(u,"operator"))===null||i===void 0?void 0:i.toLowerCase())==="eq"&&vm(u,"value")===String(t)}function nbe(e,t){let n=String(e??"").trim().toLowerCase().split(/\s+/).filter(i=>i!==""),r=String(t??"").trim().toLowerCase().split(/\s+/).filter(i=>i!=="");return n.length===r.length&&n.filter((i,o)=>i!==r[o]).length===1}function rbe(e){var t,n;let r=e.filter(a=>o4(a,0)),i=e.filter(a=>o4(a,1)),o=[];for(let a of r)for(let s of i)Math.abs(Date.parse(String((t=s.createdon)!==null&&t!==void 0?t:""))-Date.parse(String((n=a.createdon)!==null&&n!==void 0?n:"")))<=Zye&&nbe(a.name,s.name)&&o.push({active:a,inactive:s});return o.length===1?o[0]:void 0}async function ibe(e,t,n={}){var r;let i=new Set(((r=n.excludeViewIds)!==null&&r!==void 0?r:[]).filter(Boolean)),o=`returnedtypecode eq '${(0,io.odataLiteral)(t)}' and querytype eq 0`,a=`/savedqueries${(0,io.odataQuery)([["$select","savedqueryid,name,canbedeleted,fetchxml,createdon"],["$filter",o]])}`,s=await(0,s4.collectPages)(e,a,`findDefaultViews('${t}')`),u=rbe(s),l=new Set(u?[u.active,u.inactive]:[]);return s.filter(c=>c.savedqueryid&&!i.has(c.savedqueryid)&&l.has(c)).map(c=>{var d;return{id:String(c.savedqueryid),name:String((d=c.name)!==null&&d!==void 0?d:"")}})}Rl.findDefaultViews=ibe;async function obe(e,t){var n;let r=`/EntityDefinitions(LogicalName='${(0,io.odataPathLiteral)(t)}')${(0,io.odataQuery)([["$select","ObjectTypeCode"]])}`,i=await e.get(r);if(i.status>=200&&i.status<300){let o=(n=i.body)===null||n===void 0?void 0:n.ObjectTypeCode;return typeof o=="number"?o:void 0}}async function a4(e,t,n){if(!n||!/<grid\b/.test(t)||/<grid[^>]*\bobject=/.test(t))return t;let r=await obe(e,n);return r===void 0?t:t.replace(/<grid\b/,`<grid object="${r}"`)}Rl.viewApi={async get(e,t){let n=(0,io.normalizeGuid)(t,"id"),r=await(0,Ir.readRowEtag)(e,"savedqueries","savedqueryid",n),i=`/savedqueries(${n})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,io.odataQuery)([["$select",i4]]);return{raw:(0,Ir.ensureSuccess)(await e.get(i),e.apiUrl(i)).body,etag:r}},async readContentThenToken(e,t){let n=(0,io.normalizeGuid)(t,"id"),r=`/savedqueries(${n})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,io.odataQuery)([["$select",i4]]),i=(0,Ir.ensureSuccess)(await e.get(r),e.apiUrl(r)),o=await(0,Ir.readRowEtag)(e,"savedqueries","savedqueryid",n);return{raw:i.body,etag:o}},async list(e,t){let n=`/savedqueries${(0,io.odataQuery)([["$select",Xye],["$filter",t?.entityLogicalName?`returnedtypecode eq '${(0,io.odataLiteral)(t.entityLogicalName)}'`:void 0]])}`;return(await(0,s4.collectPages)(e,n,"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,queryType:i.querytype,isDefault:i.isdefault,isDirty:!1}})},async create(e,t,n,r=void 0){let i=t,o=(0,Ir.echoWrite)("savedqueryid"),a=`/savedqueries${o.query}`,s=await a4(e,i.layoutxml,i.returnedtypecode),u=Object.freeze((0,Ir.withClientMintedId)({name:i.name,description:i.description,fetchxml:i.fetchxml,layoutxml:s,returnedtypecode:i.returnedtypecode,querytype:i.querytype,isdefault:i.isdefault},"savedqueryid",n));if(r){let c=n?(0,io.normalizeGuid)(n,"savedqueryid"):void 0;return r.reached({effects:[{componentName:"SavedQuery",componentId:c,identity:"known",operation:"create"}],attemptsWrite:!0},c?()=>(0,_N.existsByKey)(e,r,{collection:"/savedqueries",key:"savedqueryid",id:c,componentName:"SavedQuery"}):void 0)}let l=(0,Ir.ensureSuccess)(await(0,Ir.resendDeadlockVictim)(()=>e.post(a,{...u},o.options)),e.apiUrl(a));return{id:(0,Ir.resolveCreatedId)(l,"savedqueryid","view",n),etag:(0,Ir.readEtag)(l)}},async update(e,t,n,r,i=void 0,o,a){let s=n,u=(0,io.normalizeGuid)(t,"id");a&&!(0,Ir.isVersionToken)(r)&&a.observe({guard:"ifMatch",componentName:"SavedQuery",componentId:u,held:r,status:"missingHeld"});let l=(0,Ir.echoWrite)("savedqueryid",{"If-Match":(0,Ir.requireEtag)(r,"view",u)}),c=`/savedqueries(${u})${l.query}`,d=await a4(e,s.layoutxml,s.returnedtypecode);if(a)return await(0,_N.observeIfMatch)(e,a,{entitySet:"savedqueries",idColumn:"savedqueryid",id:u,componentName:"SavedQuery",held:l.options.headers["If-Match"]}),a.reached({effects:[{componentName:"SavedQuery",componentId:u,identity:"known",operation:"update"}],attemptsWrite:!0});let f=typeof s.returnedtypecode=="string"&&s.returnedtypecode.trim()!==""?{returnedtypecode:s.returnedtypecode}:{},p=(0,Ir.ensureSuccess)(await e.patch(c,{name:s.name,description:s.description,fetchxml:s.fetchxml,layoutxml:d,...f},l.options),e.apiUrl(c));return{id:u,etag:(0,Ir.readEtag)(p)}},delete(e,t){return(0,Ir.deleteRecord)(e,"savedqueries",t)},planPush(e,t,n){return(0,_N.planPushThrough)(Rl.viewApi,e,t,n)}}});var c4=C(Pd=>{"use strict";Object.defineProperty(Pd,"__esModule",{value:!0});Pd.findColumnTemplate=Pd.classifyFindFilter=void 0;var Dd="isquickfindfields",u4=new Set(["attribute","operator","value"]),abe=/\{[0-4]\}/;function TN(e){let t=[];for(let n=0;n<e.childNodes.length;n+=1){let r=e.childNodes[n];r.nodeType===1&&t.push(r)}return t}function l4(e){var t;for(let n=0;n<e.childNodes.length;n+=1){let r=e.childNodes[n];if(r.nodeType!==1&&r.nodeType!==3||r.nodeType===3&&((t=r.nodeValue)!==null&&t!==void 0?t:"").trim()!=="")return!0}return!1}function sbe(e){var t,n;let i=Array.from(e.getElementsByTagName("*")).filter(c=>c.hasAttribute(Dd));if(i.length===0)return{state:"absent"};if(i.length>1)return{state:"unsupported",reason:`${i.length} elements carry ${Dd}`};let o=i[0],a=TN(e).find(c=>c.tagName==="entity");if(o.tagName!=="filter")return{state:"unsupported",reason:`${Dd} is on a <${o.tagName}>, not a <filter>`};if(o.getAttribute(Dd)!=="1")return{state:"unsupported",reason:`${Dd}="${o.getAttribute(Dd)}"`};if(!a||o.parentNode!==a)return{state:"unsupported",reason:"the find filter is not a direct child of the entity"};if(l4(o))return{state:"unsupported",reason:"the find filter holds text"};let s=TN(o),u=[],l=new Set;for(let c of s){if(c.tagName!=="condition"||TN(c).length>0||l4(c))return{state:"unsupported",reason:`the find filter holds a <${c.tagName}> that is not a plain condition`};let d=Array.from({length:c.attributes.length},(m,h)=>c.attributes[h].name);if(d.length!==u4.size||d.some(m=>!u4.has(m)))return{state:"unsupported",reason:`a find condition carries [${d.join(", ")}]`};let f=(t=c.getAttribute("attribute"))!==null&&t!==void 0?t:"";if(f===""||f.includes("."))return{state:"unsupported",reason:`a find condition names '${f}'`};if(!abe.test((n=c.getAttribute("value"))!==null&&n!==void 0?n:""))return{state:"unsupported",reason:`the condition on '${f}' is a literal constraint, not a find column`};let p=f.toLowerCase();if(l.has(p))return{state:"unsupported",reason:`'${f}' is a find column twice`};l.add(p),u.push(f)}return{state:"modelled",filter:o,columns:u,conditions:s}}Pd.classifyFindFilter=sbe;function ube(e){switch(e){case"String":case"Memo":case"Lookup":case"Customer":case"Owner":case"Picklist":case"State":case"Status":case"Boolean":return{operator:"like",value:"{0}"};case"Integer":return{operator:"eq",value:"{1}"};case"Double":return{operator:"eq",value:"{4}"};case"Money":return{operator:"eq",value:"{2}"};case"DateTime":return{operator:"on",value:"{3}"};default:return}}Pd.findColumnTemplate=ube});var _4=C($d=>{"use strict";Object.defineProperty($d,"__esModule",{value:!0});$d.viewRegistration=$d.ViewAdapter=void 0;var kl=Y(),dn=Vi(),ON=Us(),vu=ja(),d4=mo(),lbe=IN(),Rd=Ga(),cbe=ft(),kd=c4(),g4=100,Iy=class{toArtifact(t){var n,r,i,o,a,s,u,l;(0,Rd.installDomShim)();let c=(n=t.fetchxml)!==null&&n!==void 0?n:"",d=(r=t.layoutxml)!==null&&r!==void 0?r:"",f=(0,vu.parseXmlRoot)(c,"<fetch/>"),p=(0,vu.parseXmlRoot)(d,"<grid/>"),m=w4(f),h=(0,kd.classifyFindFilter)(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:hbe(f),queryType:(u=t.querytype)!==null&&u!==void 0?u:0,isDefault:(l=t.isdefault)!==null&&l!==void 0?l:!1,columns:v4(p,f),filters:A4(f),sort:E4(f),...m.length>0?{linkEntities:m}:{},...h.state==="modelled"?{findColumns:[...h.columns]}:{},fetchBag:c?(0,vu.projectElementBag)(f):void 0,layoutBag:d?(0,vu.projectElementBag)(p):void 0}}fromArtifact(t){(0,Rd.installDomShim)();let{fetchxml:n,layoutxml:r}=p4(t);return{savedqueryid:t.id,name:t.name,description:t.description,returnedtypecode:t.entityLogicalName,querytype:t.queryType,isdefault:t.isDefault,fetchxml:n,layoutxml:r}}fromApiResponse(t){return this.toArtifact(t??{})}toApiPayload(t,n,r){var i,o,a,s;(0,Rd.installDomShim)();let u=dbe(t,n),{fetchxml:l,layoutxml:c}=p4(f4(t,n),r,u);return{name:(i=t.name)!==null&&i!==void 0?i:"",description:(o=t.description)!==null&&o!==void 0?o:"",fetchxml:l,layoutxml:c,returnedtypecode:(a=t.entityLogicalName)!==null&&a!==void 0?a:"",querytype:u??0,isdefault:(s=t.isDefault)!==null&&s!==void 0?s:!1}}createDefault(t){var n,r,i,o,a,s,u,l;let c=(n=t.entityLogicalName)!==null&&n!==void 0?n:"";return{id:(r=t.id)!==null&&r!==void 0?r:(0,cbe.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:(u=t.filters)!==null&&u!==void 0?u:{type:"and",conditions:[],groups:[]},sort:(l=t.sort)!==null&&l!==void 0?l:[],...t.linkEntities&&t.linkEntities.length>0?{linkEntities:t.linkEntities}:{},...t.findColumns!==void 0?{findColumns:t.findColumns}:{}}}assignMissingIds(t){return t}committed(t,n){let r=n,i=t;typeof r?.querytype=="number"&&r.querytype!==t.queryType&&(i={...i,queryType:r.querytype});let o=r?.fetchxml;if(i.findColumns===void 0&&typeof o=="string"&&o.includes("isquickfindfields")){(0,Rd.installDomShim)();let a=(0,kd.classifyFindFilter)((0,vu.parseXmlRoot)(o,"<fetch/>"));a.state==="modelled"&&(i={...i,findColumns:[...a.columns]})}return{artifact:i,baseline:i}}validate(t){let n=[],r=t;(0,dn.childObjects)(r,"columns","","column",n),(0,dn.childObjects)(r,"sort","","sort",n),(0,dn.childObjects)(r,"linkEntities","","linkEntity",n),mbe(r.linkEntities,n),fbe(t,n);let i=r.filters;return i!=null&&((0,dn.isJsonObject)(i)?$N(i,"/filters",n):n.push((0,dn.issue)("/filters","filters-must-be-object",`filters must be a JSON object, got ${typeof i}`))),n}metadataNeeds(t,n){let r=f4(t,n);if(!Array.isArray(r.findColumns)||r.findColumns.length===0)return[];(0,Rd.installDomShim)();let i=RN(r);if(i.state==="unsupported")return[];let o=new Set(i.state==="modelled"?i.columns.map(s=>s.toLowerCase()):[]),a=new Set;for(let s of r.findColumns){let u=typeof s=="string"?s.toLowerCase():"";u!==""&&!o.has(u)&&a.add(u)}return[...a].map(s=>({entityLogicalName:r.entityLogicalName,fieldName:s}))}};$d.ViewAdapter=Iy;function f4(e,t){let n=t?.findColumns;return e.findColumns!==void 0||!Array.isArray(n)?e:{...e,findColumns:[...n]}}function dbe(e,t){return t!==void 0?t.queryType:e.queryType}function RN(e){if(!DN(e.fetchBag))return{state:"absent"};let t=new DOMParser().parseFromString("<root/>","text/xml");return(0,kd.classifyFindFilter)(PN(e.fetchBag,"fetch",t))}function fbe(e,t){let n=e.findColumns;if(n===void 0)return;if(!Array.isArray(n)){t.push((0,dn.issue)("/findColumns","view-find-columns-not-array",`findColumns must be an array of column logical names, got ${typeof n}`));return}let r=new Map;n.forEach((o,a)=>{if(typeof o!="string"||o.trim()===""||/\s/.test(o)||o.includes(".")){t.push((0,dn.issue)(`/findColumns/${a}`,"view-find-column-not-name",`a find column is a logical name of the view's own table (no spaces, no joined table), got ${JSON.stringify(o)}`));return}let s=o.toLowerCase();if(r.has(s)){t.push((0,dn.issue)(`/findColumns/${a}`,"view-find-column-duplicate",`'${o}' is already a find column (at /findColumns/${r.get(s)})`));return}r.set(s,a)}),(0,Rd.installDomShim)();let i=RN(e);i.state==="unsupported"?t.push(kN(i.reason)):i.state==="absent"&&e.queryType!==4&&t.push(y4(e.queryType))}function kN(e){return(0,dn.issue)("/findColumns","view-find-filter-unsupported",`this view's find filter cannot be represented as a list of find columns (${e}), so a typed write would discard what the list cannot show; it is left as it is. Remove findColumns to keep it.`)}function y4(e,t=e){return t!==e?(0,dn.issue)("/findColumns","view-find-columns-not-quick-find",`find columns can be added only to a Quick Find view (queryType 4); this view is saved with queryType ${e} and has no find filter. Its local queryType (${t}) is not saved by an update (a view's query type is set when it is created), so it cannot make the view a Quick Find view`):(0,dn.issue)("/findColumns","view-find-columns-not-quick-find",`find columns can be added only to a Quick Find view (queryType 4); this view's queryType is ${e} and it has no find filter`)}function pbe(e,t,n,r,i){var o,a;let s=new Map;for(let u of n){let l=(o=r?.resolveField(t.entityLogicalName,u))===null||o===void 0?void 0:o.attributeType,c=((a=t.findColumns)!==null&&a!==void 0?a:[]).findIndex(p=>String(p).toLowerCase()===u);if(!l||l==="Unknown"){i.push((0,dn.issue)(`/findColumns/${c}`,"view-find-column-unresolved",`the type of '${u}' on '${t.entityLogicalName}' could not be read (the column does not exist, or the read failed), so its search template cannot be chosen; nothing was written`));continue}let d=(0,kd.findColumnTemplate)(l);if(!d){i.push((0,dn.issue)(`/findColumns/${c}`,"view-find-column-type-unsupported",`'${u}' is a ${l} column, which cannot be added as a find column (the maker view designer offers text, choice, yes/no, lookup, whole number, floating point, currency and date columns)`));continue}let f=e.createElement("condition");f.setAttribute("attribute",u),f.setAttribute("operator",d.operator),f.setAttribute("value",d.value),s.set(u,f)}return s}function b4(e,t,n,r,i,o){var a,s;let u=((a=n.findColumns)!==null&&a!==void 0?a:[]).map(p=>String(p).toLowerCase());if(r.state==="unsupported")throw new kl.ValidationError("view",n.id,[kN(r.reason)]);if(r.state==="modelled"&&wm(u,r.columns.map(p=>p.toLowerCase())))return;if(r.state==="absent"&&o!==4)throw new kl.ValidationError("view",n.id,[y4(o,n.queryType)]);let l=new Map(r.state==="modelled"?r.conditions.map(p=>[String(p.getAttribute("attribute")).toLowerCase(),p]):[]),c=[],d=pbe(e,n,u.filter(p=>!l.has(p)),i,c);if(c.length>0)throw new kl.ValidationError("view",n.id,c);let f;if(r.state==="modelled")for(f=r.filter;f.firstChild;)f.removeChild(f.firstChild);else{f=e.createElement("filter"),f.setAttribute("type","or"),f.setAttribute("isquickfindfields","1");let p=t.getElementsByTagName("entity")[0];if(!p)throw new kl.ValidationError("view",n.id,"/findColumns","view-find-columns-no-entity");p.appendChild(f)}for(let p of u)f.appendChild((s=l.get(p))!==null&&s!==void 0?s:d.get(p))}function mbe(e,t){Array.isArray(e)&&e.forEach((n,r)=>{if(!(0,dn.isJsonObject)(n))return;for(let o of["name","from","to"]){let a=n[o];(typeof a!="string"||a.trim()==="")&&t.push((0,dn.issue)(`/linkEntities/${r}/${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=n.filters;i!=null&&((0,dn.isJsonObject)(i)?$N(i,`/linkEntities/${r}/filters`,t):t.push((0,dn.issue)(`/linkEntities/${r}/filters`,"filters-must-be-object",`filters must be a JSON object, got ${typeof i}`)))})}function $N(e,t,n){(0,dn.childObjects)(e,"conditions",t,"condition",n),(0,dn.childObjects)(e,"groups",t,"filterGroup",n).forEach(({node:i,index:o})=>$N(i,`${t}/groups/${o}`,n))}function hbe(e){var t;let n=e.getElementsByTagName("entity")[0];return(t=n?.getAttribute("name"))!==null&&t!==void 0?t:""}function v4(e,t){var n;let r=Ty(t),i=e.getElementsByTagName("cell"),o=[],a=0;for(let s=0;s<i.length;s+=1){let u=i[s];if(u.getAttribute("ishidden")==="1")continue;let l=u.getAttribute("name");if(!l)continue;let c=parseInt((n=u.getAttribute("width"))!==null&&n!==void 0?n:"",10),d={name:l,width:Number.isNaN(c)?g4:c,order:a},f=r.get(l);f&&(d.relatedEntity=f.linkKey,f.attributeName&&f.attributeName!==l&&(d.sourceAttribute=f.attributeName)),a+=1,o.push(d)}return o}function Ty(e){let t=new Map,n=e.getElementsByTagName("link-entity");for(let r=0;r<n.length;r+=1){let i=n[r],o=i.getAttribute("name");if(!o)continue;let a=i.getElementsByTagName("attribute");for(let s=0;s<a.length;s+=1){let u=a[s],l=u.getAttribute("name")||"",c=u.getAttribute("alias")||l;c&&t.set(c,{linkKey:i.getAttribute("alias")||o,linkName:o,attributeName:l,link:i})}}return t}function w4(e){let t=e.getElementsByTagName("entity")[0];if(!t)return[];let n=[];for(let r of jr(t,"link-entity")){let i=r.getAttribute("name"),o=r.getAttribute("from"),a=r.getAttribute("to");if(!i||!o||!a)continue;let s=r.getAttribute("alias"),u=r.getAttribute("link-type"),l=jr(r,"filter").find(c=>!Oy(c));n.push({name:i,from:o,to:a,...s?{alias:s}:{},...u==="inner"||u==="outer"?{linkType:u}:{},...l?{filters:LN(l)}:{}})}return n}function E4(e){var t;let n=e.getElementsByTagName("entity")[0];if(!n)return[];let r=[],i=n.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&&r.push({attribute:s,descending:((t=a.getAttribute("descending"))!==null&&t!==void 0?t:"").toLowerCase()==="true",entityname:a.getAttribute("entityname")||""})}}return r}function A4(e){let t=e.getElementsByTagName("entity")[0],n={type:"and",conditions:[],groups:[]};if(!t)return n;let r=jr(t,"filter").filter(i=>!Oy(i)).map(LN);return r.length===0?n:r.length===1?r[0]:{type:"and",conditions:[],groups:r}}function Oy(e){return e.getAttribute("isquickfindfields")==="1"||gbe(e)||C4(e)?!0:Array.from(e.getElementsByTagName("condition")).some(t=>t.getAttribute("isquickfindfields")==="1"||jr(t,"value").length>0||bbe(t))}function gbe(e){let t=e.getElementsByTagName("*");for(let n=0;n<t.length;n+=1)if(t[n].getAttribute("isquickfindfields")==="1")return!0;return!1}function C4(e){let t=e.childNodes;for(let n=0;n<t.length;n+=1){let r=t[n];if(r.nodeType===1&&(r.tagName==="filter"?C4(r):r.tagName!=="condition"))return!0}return!1}var ybe=new Set(["attribute","operator","value","entityname","uiname","uitype"]);function bbe(e){var t;let n=e.attributes;for(let r=0;r<n.length;r+=1){let i=(t=n[r])===null||t===void 0?void 0:t.name;if(i&&!ybe.has(i))return!0}return!1}function LN(e){var t,n;let r=((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 u=a[s];if(u.nodeType===1)if(u.tagName==="condition"){if(u.getAttribute("isquickfindfields")==="1")continue;let l=u.getAttribute("attribute");if(!l)continue;let c={attribute:l,operator:(n=u.getAttribute("operator"))!==null&&n!==void 0?n:""};u.hasAttribute("value")&&(c.value=u.getAttribute("value")||"");let d=u.getAttribute("entityname")||"";d&&(c.entityname=d),i.push(c)}else u.tagName==="filter"&&o.push(LN(u))}return{type:r,conditions:i,groups:o}}function jr(e,t){let n=[],r=e.childNodes;for(let i=0;i<r.length;i+=1){let o=r[i];o.nodeType===1&&o.tagName===t&&n.push(o)}return n}var MN=e=>{var t,n;return`${(t=e.relatedEntity)!==null&&t!==void 0?t:""}::${(n=e.sourceAttribute)!==null&&n!==void 0?n:e.name}`};function vbe(e,t){let n=Ty(e),r=new Map;for(let i of t){if(!i.relatedEntity)continue;let o=n.get(i.name);if(o){let a=MN(i),s=r.get(a);s?s.push(o.link):r.set(a,[o.link])}}return r}function wbe(e,t,n,r){if(!r||r.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=n.filter(s=>{if(!s.relatedEntity)return!1;let u=r.get(MN(s));return!!u&&u.some(l=>!i.has(l))});if(a.length!==0)throw new kl.ValidationError("view",e.id,a.map(s=>(0,dn.issue)(`/columns/${n.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 p4(e,t,n=e.queryType){var r,i;let o=Ebe(e.columns),a=(r=e.sort)!==null&&r!==void 0?r:[],s=(i=e.filters)!==null&&i!==void 0?i:{type:"and",conditions:[],groups:[]},u=e.findColumns!==void 0?RN(e):void 0;if(u?.state==="unsupported")throw new kl.ValidationError("view",e.id,[kN(u.reason)]);if(!DN(e.fetchBag)||!DN(e.layoutBag))return{fetchxml:$be({...e,columns:o,sort:a,filters:s},t,u,n),layoutxml:Lbe({...e,columns:o},`${e.entityLogicalName}id`)};let l=new DOMParser().parseFromString("<root/>","text/xml"),c=PN(e.fetchBag,"fetch",l),d=PN(e.layoutBag,"grid",l),f=e.findColumns!==void 0?(0,kd.classifyFindFilter)(c):void 0,p=v4(d,c),m=!wm(o,p),h=!wm(a,E4(c)),g=!wm(s,A4(c)),y=e.linkEntities,b=y!==void 0&&!wm(y,w4(c)),E=b?vbe(c,p):void 0;return b&&Pbe(l,c,y),b&&(kbe(e,c,o,E),wbe(e,c,o,E)),m?(m4(l,c,o,p),_be(l,d,o)):b&&m4(l,c,o,p),h&&Obe(l,c,a),g&&Dbe(l,c,s),f!==void 0&&b4(l,c,e,f,t,n),{fetchxml:(0,vu.serializeNode)(c),layoutxml:(0,vu.serializeNode)(d)}}function Ebe(e){return(e??[]).map((t,n)=>{var r,i;return{name:String(t.name).toLowerCase(),width:(r=t.width)!==null&&r!==void 0?r:g4,order:(i=t.order)!==null&&i!==void 0?i:n,...t.relatedEntity?{relatedEntity:t.relatedEntity}:{},...t.sourceAttribute?{sourceAttribute:String(t.sourceAttribute).toLowerCase()}:{}}})}function DN(e){return!!e&&(e.c.length>0||e.a.length>0)}function PN(e,t,n){let r={n:t,a:(0,ON.mergeAttrs)(e.a,[]),c:(0,ON.spliceChildren)(e.c,[])};return(0,ON.rebuildRaw)(r,(0,vu.domEngine)(n),null)}function m4(e,t,n,r){var i,o,a;let s=t.getElementsByTagName("entity")[0];if(!s)return;let u=m=>{var h,g;return`${(h=m.relatedEntity)!==null&&h!==void 0?h:""}:${m.name}:${(g=m.sourceAttribute)!==null&&g!==void 0?g:m.name}`},l=new Set(n.map(u)),c=new Set(n.map(m=>m.name)),d=Ty(t);for(let m of r)l.has(u(m))||(Cbe(s,m),m.relatedEntity&&c.has(m.name)&&Abe((i=d.get(m.name))===null||i===void 0?void 0:i.link,m.name));let f=Ty(t),p=new Set(jr(s,"attribute").map(m=>m.getAttribute("name")).filter(m=>!!m));for(let m of[...n].sort((h,g)=>h.order-g.order))if(m.relatedEntity){let h=f.get(m.name);if(h&&h.attributeName===((o=m.sourceAttribute)!==null&&o!==void 0?o:m.name)&&(h.linkKey===m.relatedEntity||h.linkName===m.relatedEntity||!N4(s,m.relatedEntity)))continue;let g=Sbe(e,s,m.relatedEntity),y=e.createElement("attribute");S4(y,m),g.appendChild(y),f.set(m.name,{linkKey:m.relatedEntity,linkName:g.getAttribute("name")||m.relatedEntity,attributeName:(a=m.sourceAttribute)!==null&&a!==void 0?a:m.name,link:g})}else{if(p.has(m.name))continue;let h=e.createElement("attribute");h.setAttribute("name",m.name),Nbe(s,h),p.add(m.name)}}function S4(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 Abe(e,t){if(e){for(let n of jr(e,"attribute"))if((n.getAttribute("alias")||n.getAttribute("name"))===t){e.removeChild(n);return}}}function Cbe(e,t){if(t.relatedEntity){for(let n of jr(e,"link-entity"))if(!(n.getAttribute("alias")!==t.relatedEntity&&n.getAttribute("name")!==t.relatedEntity)){for(let r of jr(n,"attribute"))if((r.getAttribute("alias")||r.getAttribute("name"))===t.name){n.removeChild(r);return}}return}for(let n of jr(e,"attribute"))if(n.getAttribute("name")===t.name){e.removeChild(n);return}}function N4(e,t,n=!1){let r=o=>o.getAttribute("alias")===t||o.getAttribute("name")===t;for(let o of jr(e,"link-entity"))if(r(o))return o;if(n)return;let i=e.getElementsByTagName("link-entity");for(let o=0;o<i.length;o+=1)if(r(i[o]))return i[o]}function Sbe(e,t,n){let r=N4(t,n);if(r)return r;let i=e.createElement("link-entity");return i.setAttribute("name",n),t.appendChild(i),i}function Nbe(e,t){let n=e.childNodes;for(let r=0;r<n.length;r+=1){let i=n[r];if(i.nodeType===1&&i.tagName!=="attribute"){e.insertBefore(t,i);return}}e.appendChild(t)}function _be(e,t,n){let r=t.getElementsByTagName("row")[0];if(!r)return;let i=[...n].sort((s,u)=>s.order-u.order),o=Ibe(r);if(Tbe(o,i)){for(let s=0;s<i.length;s+=1){let u=String(i[s].width);o[s].getAttribute("width")!==u&&o[s].setAttribute("width",u)}return}let a=new Map;for(let s of o){let u=s.getAttribute("name");u&&a.set(u,s),r.removeChild(s)}for(let s of i){let u=a.get(s.name);u||(u=e.createElement("cell"),u.setAttribute("name",s.name)),u.setAttribute("width",String(s.width)),r.appendChild(u)}}function Ibe(e){return jr(e,"cell").filter(t=>!!t.getAttribute("name")&&t.getAttribute("ishidden")!=="1")}function Tbe(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n].getAttribute("name")!==t[n].name)return!1;return!0}function Obe(e,t,n){let r=t.getElementsByTagName("entity")[0];if(!r)return;let i=(p,m)=>`${p.toLowerCase()}\0${m.toLowerCase()}`,o=new Map,a=new Map,s=(p,m,h)=>{let g=p.get(m);g?g.push(h):p.set(m,[h])},u=null;for(let p of jr(r,"order")){let m=p.getAttribute("attribute")||"";m&&(u||(u=e.createTextNode(""),r.insertBefore(u,p)),s(o,i(p.getAttribute("entityname")||"",m),p),s(a,m.toLowerCase(),p),r.removeChild(p))}let l=new Set,c=(p,m)=>{let h=p.get(m);for(;h&&h.length>0;){let g=h.shift();if(!l.has(g))return l.add(g),g}},d=p=>{var m;let h=a.get(p.toLowerCase());if(!h)return;let g=h.filter(b=>!l.has(b)),y=(m=g.find(b=>!b.getAttribute("entityname")))!==null&&m!==void 0?m:g[0];return y&&l.add(y),y},f=n.map(p=>{let m=String(p.attribute);return p.entityname===void 0?{expression:p,element:void 0}:{expression:p,element:c(o,i(p.entityname,m))}});for(let p of f)p.expression.entityname===void 0&&(p.element=d(String(p.expression.attribute)));for(let{expression:p,element:m}of f){let h=m??e.createElement("order");h.setAttribute("attribute",p.attribute),h.setAttribute("descending",String(p.descending)),p.entityname?h.setAttribute("entityname",p.entityname):p.entityname===""&&h.removeAttribute("entityname"),r.insertBefore(h,u)}u&&r.removeChild(u)}function Dbe(e,t,n){let r=t.getElementsByTagName("entity")[0];if(r){for(let i of jr(r,"filter"))Oy(i)||r.removeChild(i);(n.conditions.length>0||n.groups.length>0)&&r.appendChild(Em(e,n))}}function wm(e,t){return JSON.stringify(e)===JSON.stringify(t)}function Pbe(e,t,n){var r;let i=t.getElementsByTagName("entity")[0];if(!i)return;let o=jr(i,"link-entity").filter(m=>m.getAttribute("name")&&m.getAttribute("from")&&m.getAttribute("to")),a=(m,h)=>m.getAttribute(h)||"",s=new Array(n.length),u=new Set,l=m=>{n.forEach((h,g)=>{if(s[g])return;let y=o.filter(w=>!u.has(w)&&m(w,h));if(y.length!==1)return;let b=y[0];n.some((w,_)=>_!==g&&!s[_]&&m(b,w))||(s[g]=b,u.add(b))})};l((m,h)=>!!h.alias&&a(m,"name")===h.name&&a(m,"alias")===h.alias),l((m,h)=>a(m,"name")===h.name&&a(m,"from")===h.from&&a(m,"to")===h.to),l((m,h)=>a(m,"name")===h.name&&a(m,"from")===h.from),l((m,h)=>a(m,"name")===h.name&&a(m,"to")===h.to),l((m,h)=>a(m,"name")===h.name);let c=n.map((m,h)=>h).filter(m=>!s[m]),d=o.filter(m=>!u.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(n[m].name);h?h.push(m):p.set(n[m].name,[m])}for(let[m,h]of p){let g=(r=f.get(m))!==null&&r!==void 0?r:[];g.length===h.length&&h.forEach((y,b)=>{s[y]=g[b],u.add(g[b])})}n.forEach((m,h)=>{let g=s[h];if(g){h4(e,g,m);return}let y=e.createElement("link-entity");h4(e,y,m),i.appendChild(y)});for(let m of o)u.has(m)||i.removeChild(m)}var Rbe=new Set(["inner","outer"]);function kbe(e,t,n,r){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 u=c=>{let d=r?.get(MN(c));return!!d&&d.every(f=>s.has(f))},l=n.filter(c=>c.relatedEntity&&!o.has(c.relatedEntity)&&!u(c));if(l.length!==0)throw new kl.ValidationError("view",e.id,l.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,dn.issue)(`/columns/${n.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 h4(e,t,n){t.setAttribute("name",n.name),t.setAttribute("from",n.from),t.setAttribute("to",n.to),n.alias?t.setAttribute("alias",n.alias):t.removeAttribute("alias"),n.linkType?t.setAttribute("link-type",n.linkType):Rbe.has(t.getAttribute("link-type")||"")&&t.removeAttribute("link-type");let r=jr(t,"filter").find(o=>!Oy(o)),i=n.filters&&(n.filters.conditions.length>0||n.filters.groups.length>0)?Em(e,n.filters):null;r&&i?t.replaceChild(i,r):r?t.removeChild(r):i&&t.appendChild(i)}function $be(e,t,n,r=e.queryType){var i;let o=new DOMParser().parseFromString("<fetch/>","text/xml"),a=o.documentElement;a.setAttribute("version","1.0"),a.setAttribute("mapping","logical");let s=o.createElement("entity");s.setAttribute("name",e.entityLogicalName),a.appendChild(s);let u=new Map;for(let l of(i=e.linkEntities)!==null&&i!==void 0?i:[]){let c=o.createElement("link-entity");c.setAttribute("name",l.name),c.setAttribute("from",l.from),c.setAttribute("to",l.to),l.alias&&c.setAttribute("alias",l.alias),l.linkType&&c.setAttribute("link-type",l.linkType),l.filters&&(l.filters.conditions.length>0||l.filters.groups.length>0)&&c.appendChild(Em(o,l.filters)),s.appendChild(c);for(let d of[l.alias||l.name,l.name])u.has(d)||u.set(d,c)}for(let l of[...e.columns].sort((c,d)=>c.order-d.order)){let c=o.createElement("attribute");if(l.relatedEntity){S4(c,l);let d=u.get(l.relatedEntity);d||(d=o.createElement("link-entity"),d.setAttribute("name",l.relatedEntity),s.appendChild(d),u.set(l.relatedEntity,d)),d.appendChild(c)}else c.setAttribute("name",l.name),s.appendChild(c)}for(let l of e.sort){let c=o.createElement("order");c.setAttribute("attribute",l.attribute),c.setAttribute("descending",String(l.descending)),l.entityname&&c.setAttribute("entityname",l.entityname),s.appendChild(c)}return(e.filters.conditions.length>0||e.filters.groups.length>0)&&s.appendChild(Em(o,e.filters)),e.findColumns!==void 0&&(n?.state==="modelled"&&s.appendChild(o.importNode(n.filter,!0)),b4(o,a,e,(0,kd.classifyFindFilter)(a),t,r)),new XMLSerializer().serializeToString(o)}function Em(e,t){let n=e.createElement("filter");n.setAttribute("type",t.type);for(let r of t.conditions){let i=e.createElement("condition");i.setAttribute("attribute",r.attribute),i.setAttribute("operator",r.operator),r.entityname&&i.setAttribute("entityname",r.entityname),r.value!==void 0&&i.setAttribute("value",r.value),n.appendChild(i)}for(let r of t.groups)n.appendChild(Em(e,r));return n}function Lbe(e,t){var n;let r=new DOMParser().parseFromString("<grid/>","text/xml"),i=r.documentElement,o=[...e.columns].sort((s,u)=>s.order-u.order);i.setAttribute("name","resultset"),i.setAttribute("jump",((n=o[0])===null||n===void 0?void 0:n.name)||t||`${e.entityLogicalName}id`),i.setAttribute("select","1"),i.setAttribute("icon","1"),i.setAttribute("preview","1");let a=r.createElement("row");a.setAttribute("name","result"),a.setAttribute("id",t||`${e.entityLogicalName}id`),i.appendChild(a);for(let s of o){let u=r.createElement("cell");u.setAttribute("name",s.name),u.setAttribute("width",String(s.width)),a.appendChild(u)}return new XMLSerializer().serializeToString(r)}function Mbe(){return{adapter:new Iy,api:lbe.viewApi,publish:(e,t,n)=>(0,d4.publishBoundEntity)(e,n),publishScope:(e,t)=>(0,d4.boundEntityPublishScope)(t),rebaselineAfterPublish:"bracket"}}$d.viewRegistration=Mbe});function Dy(e,t){return e==="SetFieldValue"&&t!==void 0&&xbe.has(t.attributeType)&&(t.requiredLevel==="None"||t.requiredLevel==="Recommended")}var xbe,xN=B(()=>{"use strict";xbe=new Set(["Integer","Double","Decimal","Money","String","Memo","DateTime","Picklist","Lookup"])});function I4(e){return e!=="Entity"&&e!=="AllForms"&&typeof e=="string"&&e.trim()!==""}function FN(e){return e==="AllForms"||I4(e)?1:2}function UN(e){return I4(e)?e:null}function T4(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:Ld.WorkflowCategory.BusinessRule,type:Ld.WorkflowTypeCode.Definition,mode:1,scope:Ld.WorkflowScope.Organization,primaryentity:e.entityLogicalName,iscrmuiworkflow:!0,processtriggerscope:FN(e.scope),processtriggerformid:UN(e.scope)}}var Ld,O4=B(()=>{"use strict";Ld=Xe(Ds());});function D4(e,t=0){return(lr[e[t+0]]+lr[e[t+1]]+lr[e[t+2]]+lr[e[t+3]]+"-"+lr[e[t+4]]+lr[e[t+5]]+"-"+lr[e[t+6]]+lr[e[t+7]]+"-"+lr[e[t+8]]+lr[e[t+9]]+"-"+lr[e[t+10]]+lr[e[t+11]]+lr[e[t+12]]+lr[e[t+13]]+lr[e[t+14]]+lr[e[t+15]]).toLowerCase()}var lr,P4=B(()=>{lr=[];for(let e=0;e<256;++e)lr.push((e+256).toString(16).slice(1))});function qN(){return Py>Ry.length-16&&((0,R4.randomFillSync)(Ry),Py=0),Ry.slice(Py,Py+=16)}var R4,Ry,Py,k4=B(()=>{R4=require("crypto"),Ry=new Uint8Array(256),Py=Ry.length});var $4,BN,L4=B(()=>{$4=require("crypto"),BN={randomUUID:$4.randomUUID}});function Fbe(e,t,n){if(BN.randomUUID&&!t&&!e)return BN.randomUUID();e=e||{};let r=e.random??e.rng?.()??qN();if(r.length<16)throw new Error("Random bytes length must be >= 16");if(r[6]=r[6]&15|64,r[8]=r[8]&63|128,t){if(n=n||0,n<0||n+16>t.length)throw new RangeError(`UUID byte range ${n}:${n+15} is out of buffer bounds`);for(let i=0;i<16;++i)t[n+i]=r[i];return t}return D4(r)}var Wr,M4=B(()=>{L4();k4();P4();Wr=Fbe});var VN=B(()=>{M4()});var x4=B(()=>{"use strict";});function F4(e){return e!=null&&Ube.has(e)}function ky(e){if(e==null)return!1;let t=e.trim();if(!/^[+-]?\d+$/.test(t))return!1;let n=Number(t);return Number.isInteger(n)&&n>=-2147483648&&n<=2147483647}var Ube,GN=B(()=>{"use strict";Ube=new Set(["Picklist","State","Status"])});var $y=C(oo=>{"use strict";Object.defineProperty(oo,"__esModule",{value:!0});oo.WorkflowConditionOperator=oo.WorkflowAttributeType=oo.SystemStep=oo.FieldRequiredLevelTypes=oo.AttributeDateTimeBehavior=void 0;oo.AttributeDateTimeBehavior={None:0,Dynamic:1,DateOnly:2,StaticTimeZoneInvariant:3,UserLocal:4};oo.FieldRequiredLevelTypes={None:"0",Required:"1",Recommended:"2"};oo.SystemStep={IdentifyContact:"IdentifyContact",IdentifyAccount:"IdentifyAccount",IdentifyCustomer:"IdentifyCustomer",IdentifyCase:"IdentifyCase",Solution:"Solution",Resolve:"Resolve"};oo.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"};oo.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 Ly(e){return e!=null&&q4.includes(e)}function jN(e){return e===Te.WorkflowAttributeType.Integer}function WN(e,t){return t===Te.WorkflowConditionOperator.Equal||t===Te.WorkflowConditionOperator.NotEqual?e:qbe.includes(t)?q4.includes(e)||e===Te.WorkflowAttributeType.DateTime?e:Te.WorkflowAttributeType.String:t===Te.WorkflowConditionOperator.On||t===Te.WorkflowConditionOperator.NotOn?e===Te.WorkflowAttributeType.DateTime?e:Te.WorkflowAttributeType.String:Te.WorkflowAttributeType.String}function B4(e){let t=e.leftWorkflowType??e.valueWorkflowType??Te.WorkflowAttributeType.String,n=Am[e.operator]??Te.WorkflowConditionOperator.Equal;return WN(t,n)}function V4(e,t){let n=e.trim(),i=(n.startsWith("+")||n.startsWith("-")?n.slice(1):n).split(".");if(i.length>2)return!1;let[o,a=""]=i;return o.length===0&&a.length===0||!U4.test(o)||!U4.test(a)||o.length>1&&o.startsWith("0")||o.length>Bbe?!1:t!==Te.WorkflowAttributeType.Integer||i.length===1}var Te,Am,q4,qbe,U4,Bbe,zN=B(()=>{"use strict";Te=Xe($y());Am={Equals:Te.WorkflowConditionOperator.Equal,DoesNotEqual:Te.WorkflowConditionOperator.NotEqual,IsGreaterThan:Te.WorkflowConditionOperator.GreaterThan,IsLessThan:Te.WorkflowConditionOperator.LessThan,IsGreaterThanEqualTo:Te.WorkflowConditionOperator.GreaterThanOrEqual,IsLessThanEqualTo:Te.WorkflowConditionOperator.LessThanOrEqual,Contains:Te.WorkflowConditionOperator.Contains,DoesNotContain:Te.WorkflowConditionOperator.DoesNotContain,BeginsWith:Te.WorkflowConditionOperator.BeginsWith,DoesNotBeginWith:Te.WorkflowConditionOperator.DoesNotBeginWith,EndsWith:Te.WorkflowConditionOperator.EndsWith,DoesNotEndWith:Te.WorkflowConditionOperator.DoesNotEndWith,On:Te.WorkflowConditionOperator.On,NotOn:Te.WorkflowConditionOperator.NotOn,ContainsData:Te.WorkflowConditionOperator.NotNull,DoesNotContainData:Te.WorkflowConditionOperator.IsNull},q4=[Te.WorkflowAttributeType.Decimal,Te.WorkflowAttributeType.Float,Te.WorkflowAttributeType.Integer,Te.WorkflowAttributeType.Money],qbe=[Te.WorkflowConditionOperator.GreaterThan,Te.WorkflowConditionOperator.GreaterThanOrEqual,Te.WorkflowConditionOperator.LessThan,Te.WorkflowConditionOperator.LessThanOrEqual];U4=/^\d*$/,Bbe=28});var G4=B(()=>{"use strict";});function ko(e){return!Vbe.has(e)}function HN(e){return e==="Equals"||e==="DoesNotEqual"}function My(e){return W4.has(e)?Gbe:Kbe.has(e)?jbe:z4.has(e)?Wbe:Ybe.has(e)?Hbe:zbe}function H4(e){return My(e)[0]}function K4(e,t){return My(t).includes(e)}function j4(e){return W4.has(e)?"string":e==="Money"?"money":e==="Integer"||e==="BigInt"?"integer":e==="Decimal"||e==="Double"?"decimal":z4.has(e)?"date":Jbe.has(e)?"boolean":"other"}function xy(e,t){let n=j4(e),r=j4(t);return n==="other"||r==="other"?e===t:n===r}var Vbe,Gbe,jbe,Wbe,zbe,Hbe,W4,Kbe,z4,Jbe,Ybe,Fy=B(()=>{"use strict";G4();Vbe=new Set(["ContainsData","DoesNotContainData"]);Gbe=["Equals","DoesNotEqual","Contains","DoesNotContain","BeginsWith","DoesNotBeginWith","EndsWith","DoesNotEndWith","ContainsData","DoesNotContainData"],jbe=["Equals","DoesNotEqual","IsGreaterThan","IsGreaterThanEqualTo","IsLessThan","IsLessThanEqualTo","ContainsData","DoesNotContainData"],Wbe=["On","NotOn","Equals","DoesNotEqual","IsGreaterThan","IsGreaterThanEqualTo","IsLessThan","IsLessThanEqualTo","ContainsData","DoesNotContainData"],zbe=["Equals","DoesNotEqual","ContainsData","DoesNotContainData"],Hbe=["Equals","DoesNotEqual","Contains","DoesNotContain","BeginsWith","DoesNotBeginWith","EndsWith","DoesNotEndWith","ContainsData","DoesNotContainData"],W4=new Set(["String","Memo","EntityName"]),Kbe=new Set(["Integer","BigInt","Money","Decimal","Double"]),z4=new Set(["DateTime"]),Jbe=new Set(["Boolean"]),Ybe=new Set(["Lookup","Owner","Customer"])});function X4(e){switch(e){case"Boolean":return Ot.WorkflowAttributeType.Boolean;case"Customer":return Ot.WorkflowAttributeType.Customer;case"DateTime":return Ot.WorkflowAttributeType.DateTime;case"Decimal":return Ot.WorkflowAttributeType.Decimal;case"Double":return Ot.WorkflowAttributeType.Float;case"Integer":return Ot.WorkflowAttributeType.Integer;case"Lookup":return Ot.WorkflowAttributeType.Lookup;case"Money":return Ot.WorkflowAttributeType.Money;case"Owner":return Ot.WorkflowAttributeType.Owner;case"Picklist":return Ot.WorkflowAttributeType.Picklist;case"State":return Ot.WorkflowAttributeType.State;case"Status":return Ot.WorkflowAttributeType.Status;case"Uniqueidentifier":case"UniqueIdentifier":return Ot.WorkflowAttributeType.UniqueIdentifier;case"BigInt":return Ot.WorkflowAttributeType.BigType;default:return Ot.WorkflowAttributeType.String}}function o3(e){return e&&e!==Ot.WorkflowAttributeType.String?e:void 0}function Zbe(e){return{__class:i3,parameterName:"primaryEntity",entityName:e}}function J4(e){return{__class:JN,type:KN,typeSet:!1,behavior:Ot.AttributeDateTimeBehavior.None,method:Z4,parameters:[e]}}function Y4(e,t,n=Ot.WorkflowAttributeType.String){return{__class:t3,type:n,behavior:Ot.AttributeDateTimeBehavior.None,typeSet:!1,entity:Zbe(t),attributeName:e}}function eve(e,t=Ot.WorkflowAttributeType.String){return{__class:n3,type:t,behavior:Ot.AttributeDateTimeBehavior.None,typeSet:!1,primitiveValue:e}}function tve(e){return{__class:r3,type:KN,typeSet:!1,behavior:Ot.AttributeDateTimeBehavior.None,days:e,hours:"0",minutes:"0",months:"0",years:"0"}}function a3(e,t){let n=Qbe[e.operator],r=J4(Y4(e.leftField,t,e.leftWorkflowType)),i;e.dateArithmetic?i=tve(e.right.value??"0"):e.right.kind==="field"?i=Y4(e.right.field??"",t,e.right.workflowType):i=eve(e.right.value??"",e.right.workflowType??e.leftWorkflowType);let o=J4(i);return{__class:JN,type:KN,typeSet:!1,behavior:Ot.AttributeDateTimeBehavior.None,method:e3,parameters:[n,r,o]}}function s3(e){return typeof e=="object"&&e.__class===JN}function nve(e){return typeof e=="object"&&e.__class===r3}function Uy(e){return s3(e)&&e.method===Z4&&e.parameters.length>0?Uy(e.parameters[0]):e}function Q4(e){if(typeof e!="object"||e.__class!==t3)return null;let t=e.entity;if(t&&t.__class&&t.__class!==i3)return null;let n=e.attributeName;return n?{field:n,workflowType:o3(e.type)}:null}function u3(e){if(!e)return null;let t=Uy(e);if(!s3(t)||t.method!==e3||t.parameters.length!==3)return null;let n=t.parameters[0],r=Xbe[String(n)];if(!r)return null;let i=Q4(Uy(t.parameters[1]));if(!i)return null;let o=Uy(t.parameters[2]);if(nve(o))return r!=="+"&&r!=="-"?null:{leftField:i.field,leftWorkflowType:i.workflowType,operator:r,right:{kind:"value",value:String(o.days??"")},dateArithmetic:!0};let a=Q4(o);if(a)return{leftField:i.field,leftWorkflowType:i.workflowType,operator:r,right:{kind:"field",field:a.field,workflowType:a.workflowType}};if(typeof o=="object"&&o.__class===n3){let s=o.primitiveValue;return{leftField:i.field,leftWorkflowType:i.workflowType,operator:r,right:{kind:"value",value:s!=null?String(s):"",workflowType:o3(o.type)}}}return null}function QN(e){let t=(e??"").trim();if(!/^\d+$/.test(t))return!1;let n=Number(t);return Number.isSafeInteger(n)&&n>=YN&&n<=Md}function $l(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&&!QN(t)?"invalidDayCount":null}function xd(e){return $l(e)===null}var Ot,Z4,e3,KN,t3,n3,JN,r3,i3,Qbe,Xbe,YN,Md,Cm=B(()=>{"use strict";Ot=Xe($y());Fy();Z4="0",e3="3",KN="0",t3="EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions",n3="PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions",JN="MethodCallExpression:#Microsoft.Crm.Workflow.Expressions",r3="TimeSpanExpression:#Microsoft.Crm.Workflow.Expressions",i3="PrimaryEntity:#Microsoft.Crm.Workflow.Expressions";Qbe={"+":0,"-":1,"*":2,"/":3},Xbe={0:"+",1:"-",2:"*",3:"/"};YN=0,Md=2147483647});function ive(e){return e.startsWith("__")&&!rve.has(e)}function ove(e){let t=Object.create(null);return Object.keys(e).forEach(n=>{ive(n)&&(t[n]=e[n])}),Object.keys(t).length>0?t:void 0}function A3(e){return e.__class==="BinaryExpression:#Microsoft.Crm.Workflow.Expressions"}function Ml(e){return e.__class==="UnaryExpression:#Microsoft.Crm.Workflow.Expressions"}function qy(e){return A3(e)||Ml(e)}function ave(e){return e.__class==="ConditionBranchStep:#Microsoft.Crm.Workflow.ObjectModel"}function Sm(){return{list:[]}}function XN(e,t,n){return e&&e.list.length>0?{list:[{...e.list[0],description:t},...e.list.slice(1)]}:{list:[{labelId:Wr(),languageCode:n,description:t}]}}function e_(e){return{__class:"PrimaryEntity:#Microsoft.Crm.Workflow.Expressions",parameterName:"primaryEntity",entityName:e}}function jy(e,t,n,r=re.AttributeDateTimeBehavior.None){return{__class:"EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions",type:n,behavior:r,typeSet:!1,entity:e_(t),attributeName:e}}function Ll(e,t,n=re.AttributeDateTimeBehavior.None){return{__class:"PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions",type:t,behavior:n,typeSet:!1,primitiveValue:e}}function lve(e){return e.bpfField==="StageCategory"?e.stageType==="SelectedStage"?N3:S3:C3}function _3(e){return e.bpfField==="StageCategory"?re.WorkflowAttributeType.BpfStageCategory:re.WorkflowAttributeType.BpfProcess}function cve(e,t){let n=_3(e),r=e.bpfField==="StageCategory"?{__class:"EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions",type:n,behavior:re.AttributeDateTimeBehavior.None,typeSet:!1,entity:{__class:"RelatedEntity:#Microsoft.Crm.Workflow.Expressions",parameterName:`related_${c3}_${l3}`,entityName:l3,relatedAttributeName:c3},attributeName:uve}:jy(sve,t,n);return{__class:"MethodCallExpression:#Microsoft.Crm.Workflow.Expressions",type:n,behavior:re.AttributeDateTimeBehavior.None,typeSet:!1,method:r_,parameters:[lve(e),r]}}function I3(e){let t=e;if(t.__class!=="MethodCallExpression:#Microsoft.Crm.Workflow.Expressions"||String(t.method)!==r_)return null;let n=(t.parameters??[])[0];if(typeof n!="string")return null;let r=n.replace(/^"+|"+$/g,"");return r===S3?{bpfField:"StageCategory",stageType:"ActiveStage"}:r===N3?{bpfField:"StageCategory",stageType:"SelectedStage"}:r===C3?{bpfField:"ProcessName"}:null}function By(e){if(!e)return!1;let t=e;if(t.__class==="MethodCallExpression:#Microsoft.Crm.Workflow.Expressions"&&String(t.method)===r_){let n=(t.parameters??[])[0];if(typeof n=="string"&&dve.has(n.replace(/^"+|"+$/g,"")))return!0}return Ml(e)?By(e.operand):A3(e)?By(e.left)||(e.right??[]).some(By):!1}function T3(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 fve(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 d3(e){if(!e)return!1;switch(e.__class){case"EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions":return T3(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 pve(e){let t=n_[e.conditionOperatoroperator];if(!t)return!1;let n=t==="ContainsData"||t==="DoesNotContainData";if(Ml(e))return n&&f3(e.operand,!0);let r=e.right??[];return r.length!==(n?0:1)?!1:f3(e.left,n,r[0])}function f3(e,t,n){return I3(e)||T3(e)?t||d3(n):!1}function t_(e){if(!e||!qy(e))return!1;let t=e.conditionOperatoroperator;if(!Ml(e)&&(t===re.WorkflowConditionOperator.LogicalAnd||t===re.WorkflowConditionOperator.LogicalOr)){let n=e.right??[];return n.length>0&&t_(e.left)&&n.every(t_)}return pve(e)}function p3(e){return!e||fve(e)?!1:By(e)||!t_(e)}function O3(e){return{__class:"LookupExpression:#Microsoft.Crm.Workflow.Expressions",type:e.workflowType??re.WorkflowAttributeType.Lookup,behavior:re.AttributeDateTimeBehavior.None,typeSet:!1,entityType:e.entityType,label:e.label??"",staticValue:Ll(e.id.replace(/[{}]/g,""),re.WorkflowAttributeType.UniqueIdentifier)}}function hve(e){return e===re.WorkflowAttributeType.DateTime?re.AttributeDateTimeBehavior.DateOnly:re.AttributeDateTimeBehavior.None}function gve(e,t){if(t!==re.WorkflowAttributeType.DateTime)return re.AttributeDateTimeBehavior.None;let n=e.leftDateTimeBehavior;return n!==void 0&&n!==re.AttributeDateTimeBehavior.None?n:hve(t)}function yve(e,t,n){if(t!==re.WorkflowAttributeType.DateTime)return re.AttributeDateTimeBehavior.None;let r=e.valueFieldDateTimeBehavior;return r!==void 0&&r!==re.AttributeDateTimeBehavior.None?r:n}function vve(e){let t=e.trim().toLowerCase();if(t==="true"||t==="1")return"1";if(t==="false"||t==="0")return"0"}function Ive(e){let t=_ve.exec(e);if(t)return`${t[1]}T${t[2]}`;let n=Nve.exec(e);if(!n)return;let[,r,i,o,a,s,u]=n,l=Sve.indexOf(i.toLowerCase());if(l<0)return;let c=String(l+1).padStart(2,"0");return`${o}-${c}-${r}T${a}:${s}:${u}`}function Tve(e){let t=Ive(e.trim());return t!==void 0&&D3(t)?t:e}function D3(e){let t=e.trim(),n=t.indexOf("T")>=0?"T":" ",r=t.indexOf(n),i=r>=0?t.slice(0,r):t,o=r>=0?t.slice(r+1):"";if(!wve.test(i)||o.length>0&&!Eve.test(o)&&!Ave.test(o)&&!Cve.test(o))return!1;let[a,s,u]=i.split("-"),l=new Date(`${a}-${s}-${u}T00:00:00Z`);return!Number.isNaN(l.getTime())&&l.getUTCFullYear()===Number(a)&&l.getUTCMonth()+1===Number(s)&&l.getUTCDate()===Number(u)}function Ove(e,t){let n={value:e,type:re.WorkflowAttributeType.String};if(t===re.WorkflowAttributeType.String||bve.includes(t)||e.trim().length===0)return n;if(t===re.WorkflowAttributeType.Boolean){let r=vve(e);return r==null?n:{value:r,type:t}}return mve.includes(t)?ky(e)?{value:e.trim(),type:t}:n:Ly(t)?{value:e.trim(),type:t}:t===re.WorkflowAttributeType.DateTime&&D3(e)?{value:e.trim(),type:t}:n}function m3(e){return e==="ContainsData"||e==="DoesNotContainData"}function h3(e){return Dve.has(e)}function g3(e,t){return{__class:"UnaryExpression:#Microsoft.Crm.Workflow.Expressions",type:re.WorkflowAttributeType.Boolean,behavior:re.AttributeDateTimeBehavior.None,typeSet:!1,conditionOperatoroperator:t,operand:e}}function y3(e,t){let n=e.leftWorkflowType??e.valueWorkflowType??re.WorkflowAttributeType.String,r=Am[e.operator]??re.WorkflowConditionOperator.Equal,i=gve(e,n),o=WN(n,r);if(e.source==="BusinessProcess"){let u=cve(e,t);if(m3(e.operator))return g3(u,r);let l=_3(e);return{__class:"BinaryExpression:#Microsoft.Crm.Workflow.Expressions",type:re.WorkflowAttributeType.Boolean,behavior:re.AttributeDateTimeBehavior.None,typeSet:!1,conditionOperatoroperator:r,left:u,right:[Ll(e.value??"",l)]}}let a=jy(e.field,t,n,i);if(m3(e.operator))return g3(a,r);let s;if(e.valueType==="Field"&&e.valueField){let u=h3(o)&&h3(e.valueFieldWorkflowType??"")?e.valueFieldWorkflowType:o;s=[jy(e.valueField,t,u,yve(e,u,i))]}else if(e.valueType==="Lookup"){if(!e.lookupValue)throw new Error("Lookup condition is missing its record value.");s=[O3(e.lookupValue)]}else if(e.valueType==="Clear")s=[Ll(null,re.WorkflowAttributeType.String,i)];else if(e.valueType==="Expression")s=[Gy(e.valueType,e.value,e.valueField,t,e.expression,e.rawExpression)];else{let u=Ove(e.value??"",o);s=[Ll(u.value,u.type,i)]}return{__class:"BinaryExpression:#Microsoft.Crm.Workflow.Expressions",type:re.WorkflowAttributeType.Boolean,behavior:re.AttributeDateTimeBehavior.None,typeSet:!1,conditionOperatoroperator:r,left:a,right:s}}function Pve(){return Ll(!0,re.WorkflowAttributeType.Boolean)}function Rve(e,t,n){if(e.length===0)return null;let r=y3(e[0],n);for(let i=1;i<e.length;i++){let o=e[i].connector??t;r={__class:"BinaryExpression:#Microsoft.Crm.Workflow.Expressions",type:re.WorkflowAttributeType.Boolean,behavior:re.AttributeDateTimeBehavior.None,typeSet:!1,conditionOperatoroperator:o==="AND"?re.WorkflowConditionOperator.LogicalAnd:re.WorkflowConditionOperator.LogicalOr,left:r,right:[y3(e[i],n)]}}return r}function Vy(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===re.WorkflowAttributeType.Boolean){let n=t.trim().toLowerCase();if(n==="1"||n==="true")return{valueType:"Value",value:"true",valueWorkflowType:e.type};if(n==="0"||n==="false")return{valueType:"Value",value:"false",valueWorkflowType:e.type}}return e.type===re.WorkflowAttributeType.DateTime?{valueType:"Value",value:Tve(t),valueWorkflowType:e.type}:{valueType:"Value",value:t,valueWorkflowType:e.type}}if(e.__class==="LookupExpression:#Microsoft.Crm.Workflow.Expressions"){let t=e.staticValue,n=typeof t=="object"&&t?.__class==="PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions"?t.primitiveValue:t;return{valueType:"Lookup",lookupValue:{entityType:e.entityType,id:String(n??""),label:e.label,...e.type!==re.WorkflowAttributeType.Lookup?{workflowType:e.type}:{}}}}if(e.__class==="MethodCallExpression:#Microsoft.Crm.Workflow.Expressions"){let t=u3(e);return t?{valueType:"Expression",expression:t}:{valueType:"Expression",rawExpression:e}}return{valueType:"Value",value:""}}function kve(e){let t=n_[e.conditionOperatoroperator]??"Equals",n=t==="ContainsData"||t==="DoesNotContainData",r=Ml(e)?e.operand:e.left,i=Ml(e)?[]:e.right??[],o=I3(r);if(o){let g=i[0];return{id:Wr(),field:"",fieldDisplayName:"",source:"BusinessProcess",bpfField:o.bpfField,...o.stageType?{stageType:o.stageType}:{},operator:t,valueType:"Value",value:g?.primitiveValue!=null&&!n?String(g.primitiveValue):""}}let a=r.__class==="EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions",s=r.__class==="EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions"?r.attributeName:"",u=a?r.type:void 0,l=n?{valueType:"Value"}:Vy(i[0]),c=u,d=a&&r.type===re.WorkflowAttributeType.DateTime&&r.behavior!==re.AttributeDateTimeBehavior.None?r.behavior:void 0,f=l.valueWorkflowType??u,p=n?void 0:i[0],h=p?.__class==="EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions"&&p.type===re.WorkflowAttributeType.DateTime&&p.behavior!==re.AttributeDateTimeBehavior.None?p.behavior:void 0;return{id:Wr(),field:s,fieldDisplayName:s,operator:t,...l,...f?{valueWorkflowType:f}:{},...c?{leftWorkflowType:c}:{},...d!==void 0?{leftDateTimeBehavior:d}:{},...h!==void 0?{valueFieldDateTimeBehavior:h}:{}}}function b3(e){if(!e||!qy(e))return{clauses:[],logic:"AND"};let t=[],n=(o,a)=>{let s=o.conditionOperatoroperator;if(Ml(o)||s!==re.WorkflowConditionOperator.LogicalAnd&&s!==re.WorkflowConditionOperator.LogicalOr){t.push({...kve(o),...a?{connector:a}:{}});return}let u=s===re.WorkflowConditionOperator.LogicalAnd?"AND":"OR";qy(o.left)&&n(o.left,a),(o.right??[]).filter(qy).forEach(l=>n(l,u))};n(e,void 0);let i=t.slice(1).map(o=>o.connector??"AND")[0]??"AND";return{clauses:t,logic:i}}function Gy(e,t,n,r,i,o,a,s){if(e==="Field"&&n)return jy(n,r,re.WorkflowAttributeType.String);if(e==="Expression"){if(i)return a3(i,r);if(o!=null)return o}return e==="Lookup"&&a?O3(a):e==="Clear"?Ll(null,s??re.WorkflowAttributeType.String):Ll(t??"",re.WorkflowAttributeType.String)}function ZN(e,t){return{propertyName:e,propertyValueExpr:t}}function Fd(e){return`Step_${e.value++}`}function ao(e,t){let n=(t.counts[e]??0)+1,r=`${e}${n}`;for(;t.used.has(r);)n+=1,r=`${e}${n}`;return t.counts[e]=n,t.used.add(r),r}function v3(e,t,n){return e&&!n.used.has(e)?(n.used.add(e),e):ao(t,n)}function $ve(e){return e===E3.StateCode.Activated?"Active":"Draft"}function Lve(e){let t={},n=e;typeof n.ismanaged=="boolean"&&(t.isManaged=n.ismanaged);let r=n.iscustomizable;return typeof r=="boolean"?t.isCustomizable=r:r!==null&&typeof r=="object"&&typeof r.Value=="boolean"&&(t.isCustomizable=r.Value),t}function Mve(e,t){let n=e.processtriggerscope,r=e.processtriggerformid;return n===1?r&&r.trim()!==""?r:"AllForms":n===2?"Entity":t??"Entity"}function P3(e,t=1033){return new Ud({languageCode:t}).serialize(e)}function R3(e){return new Ud().deserialize(e)}var E3,re,rve,n_,r_,C3,S3,N3,sve,uve,l3,c3,dve,mve,bve,wve,Eve,Ave,Cve,Sve,Nve,_ve,Dve,i_,Ud,o_=B(()=>{"use strict";VN();E3=Xe(Ds());x4();GN();zN();Cm();re=Xe($y());rve=new Set(["__class"]);n_={};for(let e of Object.keys(Am))n_[Am[e]]=e;r_="23",C3="BpfProcess",S3="ActiveStageCategory",N3="SelectedStageCategory",sve="processid",uve="stagecategory",l3="processstage",c3="stageid";dve=new Set(["ActiveStage","SelectedStage","Stage"]);mve=[re.WorkflowAttributeType.Picklist,re.WorkflowAttributeType.State,re.WorkflowAttributeType.Status];bve=[re.WorkflowAttributeType.Lookup,re.WorkflowAttributeType.Customer,re.WorkflowAttributeType.Owner];wve=/^\d{4}-\d{2}-\d{2}$/,Eve=/^\d{2}:\d{2}$/,Ave=/^\d{2}:\d{2}:\d{2}$/,Cve=/^\d{2}:\d{2}:\d{2}\.\d{1,7}$/,Sve=["jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"],Nve=/^[A-Za-z]{3}, (\d{2}) ([A-Za-z]{3}) (\d{4}) (\d{2}):(\d{2}):(\d{2}) GMT$/,_ve=/^(\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$/;Dve=new Set([re.WorkflowAttributeType.Lookup,re.WorkflowAttributeType.Owner,re.WorkflowAttributeType.Customer]);i_={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"};Ud=class{resolveLabel;languageCode;entityName="";stepCounter={value:0};idCounter={counts:{},used:new Set};constructor(t={}){this.resolveLabel=t.resolveLabel??(n=>i_[n]),this.languageCode=t.languageCode??1033}label(t){return this.resolveLabel(t)}serialize(t){let n=t.wfomRoot;this.entityName=t.entityLogicalName,this.stepCounter={value:n?Number(n.nextStepIndex):1},this.idCounter={counts:{},used:new Set};let r=t.scope!=="Entity"&&t.scope!=="AllForms"?t.scope:null,i=t.rootCondition?[this.serializeConditionNode(t.rootCondition)]:[],o={...n?.reservedProperties??{},__class:"WorkflowStep:#Microsoft.Crm.Workflow.ObjectModel",id:n?.id??t.ruleId??Wr(),name:n?.name??"Step_0",description:n!==void 0?n.description:t.description||null,stepLabels:Sm(),argumentsArray:[],primaryEntityName:n?.primaryEntityName??this.entityName,nextStepIndex:String(this.stepCounter.value),isCrmUIWorkflow:!0,category:n?.category??"2",businessProcessType:n?.businessProcessType??"0",mode:n?.mode??"0",title:n?.title??t.name,formId:r,workflowEntityId:n?.workflowEntityId??t.ruleId??"",variables:n?.variables??[],inputs:n?.inputs??[],steps:{list:i}};return JSON.stringify(o)}makeApplyActionStep(t){return{__class:"SetAttributeValueStep:#Microsoft.Crm.Workflow.ObjectModel",id:ao("SetAttributeValueStep",this.idCounter),description:t.displayName||"New Action",name:t.stepName??Fd(this.stepCounter),stepLabels:{list:[]},specification:ZN(t.field,Gy(t.valueType,t.value,t.valueField,this.entityName,t.expression,t.rawExpression,t.lookupValue,t.valueWorkflowType)),entity:e_(this.entityName)}}makeRecommendationActionStep(t,n,r){let i=n.map(u=>this.makeApplyActionStep(u)),o=t??"",a=r?.stepLabels,s=XN(a,o,this.languageCode);return{__class:"ActionStep:#Microsoft.Crm.Workflow.ObjectModel",id:v3(r?.id,"ActionStep",this.idCounter),name:r?.name??Fd(this.stepCounter),description:r?.description??"Action step",stepLabels:s,steps:{list:i},actionId:null,actionType:r?.actionType??"4",processId:r?.processId??Wr(),uniqueName:r?.uniqueName??`id_${Wr().replace(/-/g,"")}ActionStep`}}serializeAction(t){let n=e_(this.entityName),r=t.stepName??Fd(this.stepCounter),i=t.stepLabels??Sm(),o={name:r,stepLabels:i,description:t.displayName},a=t.type;switch(a){case"SetFieldValue":return{...o,id:ao("SetAttributeValueStep",this.idCounter),__class:"SetAttributeValueStep:#Microsoft.Crm.Workflow.ObjectModel",entity:n,specification:ZN(t.field,Gy(t.valueType,t.value,t.valueField,this.entityName,t.expression,t.rawExpression,t.lookupValue,t.valueWorkflowType))};case"SetDefaultValue":return{...o,id:ao("SetDefaultValueStep",this.idCounter),__class:"SetDefaultValueStep:#Microsoft.Crm.Workflow.ObjectModel",entity:n,specification:ZN(t.field,Gy(t.valueType,t.value,t.valueField,this.entityName,t.expression,t.rawExpression,t.lookupValue,t.valueWorkflowType))};case"LockUnlock":return{...o,id:ao("SetDisplayModeStep",this.idCounter),__class:"SetDisplayModeStep:#Microsoft.Crm.Workflow.ObjectModel",controlId:t.field,controlType:"standard",isReadOnly:t.lock,entity:n};case"SetBusinessRequired":return{...o,id:ao("SetFieldRequiredLevelStep",this.idCounter),__class:"SetFieldRequiredLevelStep:#Microsoft.Crm.Workflow.ObjectModel",controlId:t.field,controlType:"standard",requiredLevel:t.required?re.FieldRequiredLevelTypes.Required:re.FieldRequiredLevelTypes.None,entity:n};case"SetVisibility":return{...o,id:ao("SetVisibilityStep",this.idCounter),__class:"SetVisibilityStep:#Microsoft.Crm.Workflow.ObjectModel",controlId:t.field,controlType:"standard",isVisible:t.visible,entity:n};case"ShowErrorMessage":{let s=t.errorMessage||t.displayName,u=XN(t.stepLabels,s,this.languageCode);return{...o,id:ao("SetMessageStep",this.idCounter),__class:"SetMessageStep:#Microsoft.Crm.Workflow.ObjectModel",stepLabels:u,name:s,controlId:t.field,entity:n,level:t.messageLevel??"error",actionSteps:t.messageActionSteps??{list:[]}}}case"Recommendation":{let s=t.messageText??t.recommendationTitle??t.displayName,u=XN(t.stepLabels,s,this.languageCode),l={list:[this.makeRecommendationActionStep(t.acceptanceText,t.applyActions??[],t.recommendationActionStepMeta)]};return{...o,id:ao("SetMessageStep",this.idCounter),__class:"SetMessageStep:#Microsoft.Crm.Workflow.ObjectModel",stepLabels:u,description:t.recommendationTitle||t.displayName,controlId:t.field,entity:n,level:"RECOMMENDATION",actionSteps:l}}default:throw new Error(`Unsupported action type: ${a}`)}}serializeConditionNode(t){let n=t.stepName??Fd(this.stepCounter),r=ao("ConditionStep",this.idCounter),i=[],o=t,a=!0;for(;o;){let s=o.rawConditionExpression??Rve(o.clauses,o.logic,this.entityName),u=a?o.branchName??Fd(this.stepCounter):Fd(this.stepCounter),c={__class:"ConditionBranchStep:#Microsoft.Crm.Workflow.ObjectModel",id:a?v3(o.branchId,"ConditionBranchStep",this.idCounter):ao("ConditionBranchStep",this.idCounter),name:u,description:o.displayName,stepLabels:Sm(),conditionExpression:s??(a?Pve():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:r,name:n,description:"",stepLabels:Sm(),containsElsebranch:i.length>1,steps:{list:i}}}makeTerminalElseBranch(t){return{__class:"ConditionBranchStep:#Microsoft.Crm.Workflow.ObjectModel",id:ao("ConditionBranchStep",this.idCounter),name:"Else",description:null,stepLabels:Sm(),conditionExpression:void 0,steps:{list:t.map(n=>this.serializeBranchItem(n))}}}serializeBranchItem(t){return t.kind==="condition"?this.serializeConditionNode(t):this.serializeAction(t)}deserialize(t){let n=t,r=null,i;if(t.wfomJson)try{let o=JSON.parse(t.wfomJson);i={id:o.id==="WorkflowStep0"||!o.id?t.workflowid??Wr():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:ove(o)};let s=(o.steps?.list??[]).find(u=>u.__class==="ConditionStep:#Microsoft.Crm.Workflow.ObjectModel");s&&(r=this.deserializeConditionStep(s))}catch{}return{ruleId:t.workflowid??null,name:t.name??"",description:t.description??"",entityLogicalName:t.primaryentity??"",scope:Mve(n,i?.formId),status:$ve(t.statecode),rootCondition:r,wfomRoot:i,...Lve(t)}}deserializeConditionStep(t){let n=(t.steps?.list??[]).filter(ave);return this.buildConditionNodeFromBranches(n,t,!0)}buildConditionNodeFromBranches(t,n,r){let[i,...o]=t,{clauses:a,logic:s}=b3(i?.conditionExpression),u=this.deserializeBranch(i?.steps?.list??[]),l=this.deserializeElseChain(o,n),c=i?.description||i?.name||n.description||n.name||this.label("condition");return{kind:"condition",id:(r?n.id:i?.id)??Wr(),displayName:c,clauses:a,logic:s,trueBranch:u,falseBranch:l,isCollapsed:!1,stepName:r?n.name:void 0,branchId:r?i?.id:void 0,branchName:r?i?.name:void 0,...p3(i?.conditionExpression)?{rawConditionExpression:i?.conditionExpression}:{}}}deserializeElseChain(t,n){if(t.length===0)return[];let[r]=t,{clauses:i}=b3(r.conditionExpression);return i.length===0&&!p3(r.conditionExpression)?this.deserializeBranch(r.steps?.list??[]):[this.buildConditionNodeFromBranches(t,n,!1)]}deserializeBranch(t){return t.map(n=>n.__class==="ConditionStep:#Microsoft.Crm.Workflow.ObjectModel"?this.deserializeConditionStep(n):this.deserializeAction(n)).filter(n=>n!==null)}parseRecommendationApplyActions(t){let r=(t?.list??[])[0];if(!r)return{applyActions:[]};let i={id:r.id,name:r.name,description:r.description??void 0,stepLabels:r.stepLabels,processId:r.processId,uniqueName:r.uniqueName,actionType:r.actionType},o=r.stepLabels?.list,a=o&&o.length>0?o[0].description??"":"";return{applyActions:(r.steps?.list??[]).filter(u=>u.__class==="SetAttributeValueStep:#Microsoft.Crm.Workflow.ObjectModel").map(u=>{let l=u.specification;return{id:u.id||Wr(),field:l?.propertyName??"",stepName:u.name??void 0,displayName:u.description??void 0,...Vy(l?.propertyValueExpr)}}),meta:i,acceptanceText:a}}deserializeAction(t){switch(t.__class){case"SetAttributeValueStep:#Microsoft.Crm.Workflow.ObjectModel":{let n=Vy(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,...n}}case"SetDefaultValueStep:#Microsoft.Crm.Workflow.ObjectModel":{let n=Vy(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,...n}}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!==re.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 n=t.stepLabels?.list,r=n&&n.length>0?n[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:r,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:r||t.name||"",messageLevel:t.level??void 0,messageActionSteps:t.actionSteps}}case"ActionStep:#Microsoft.Crm.Workflow.ObjectModel":{let{applyActions:n,meta:r,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:n,recommendationActionStepMeta:r}}default:return null}}}});var k3=B(()=>{"use strict";});function Bve(e){return typeof e=="object"&&e!==null?e:null}function qd(e){let t=Bve(e);if(!t)return!1;if(t.__class===Uve){let n=t;return String(n.method)===qve?!0:Array.isArray(n.parameters)&&n.parameters.some(qd)}if(t.__class===Fve)return qd(t.operand);if(t.__class===xve){let n=t;return qd(n.left)||Array.isArray(n.right)&&n.right.some(qd)}return!1}var xve,Fve,Uve,qve,$3=B(()=>{"use strict";k3();xve="BinaryExpression:#Microsoft.Crm.Workflow.Expressions",Fve="UnaryExpression:#Microsoft.Crm.Workflow.Expressions",Uve="MethodCallExpression:#Microsoft.Crm.Workflow.Expressions",qve="23"});function l_(e){return Vve.has(e.type)}function a_(e,t,n,r,i,o,a){let s=i.get(n);!s||!x3.has(s.attributeType)||r!=="Value"||a?.operator&&!HN(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 Gve(e,t){let n=t.get(e.field);return!!n&&x3.has(n.attributeType)&&HN(e.operator)}function s_(e){return!!(e?.entityType?.trim()&&e.id?.trim())}function u_(e,t,n){return{nodeId:e,kind:"INVALID_DAY_COUNT",message:`Please enter a whole number of days between 0 and ${Md}.`,target:t,itemId:n,messageKey:"Validation.InvalidDayCount",messageParams:{max:Md}}}function L3(e,t,n,r,i,o,a,s){if(i!=="Clear")return;let u=o.get(r);Dy(n,u)||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 zy(e){if(!e)return!1;for(let t of[...e.trueBranch,...e.falseBranch])if(t.kind==="action"){if(l_(t))return!0}else if(zy(t))return!0;return!1}function c_(e,t){if(e.id===t)return e;for(let n of[...e.trueBranch,...e.falseBranch]){if(n.id===t)return n;if(n.kind==="condition"){let r=c_(n,t);if(r)return r}}return null}function jve(e){if(!e||typeof e!="object")return!1;let{__class:t,primitiveValue:n}=e;return t!=="PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions"?!1:n===!0||typeof n=="string"&&n.toLowerCase()==="true"}function Wve(e){return e.clauses.length===0&&(e.rawConditionExpression===void 0||jve(e.rawConditionExpression))}function Hve(e){return!!e.clauses?.some(t=>t.source==="BusinessProcess")||qd(e.rawConditionExpression)}function Bd(e,t){for(let n=0;n<e.trueBranch.length;n++){let r=e.trueBranch[n];if(r.id===t)return{node:e,branch:"true",index:n};if(r.kind==="condition"){let i=Bd(r,t);if(i)return i}}for(let n=0;n<e.falseBranch.length;n++){let r=e.falseBranch[n];if(r.id===t)return{node:e,branch:"false",index:n};if(r.kind==="condition"){let i=Bd(r,t);if(i)return i}}return null}function d_(e,t){return{...e,trueBranch:M3(e.trueBranch,t),falseBranch:M3(e.falseBranch,t)}}function M3(e,t){return e.filter(n=>n.id!==t).map(n=>n.kind==="condition"?d_(n,t):n)}function wu(e,t,n){return e.id===t?n(e):{...e,trueBranch:e.trueBranch.map(r=>r.kind==="condition"?wu(r,t,n):r),falseBranch:e.falseBranch.map(r=>r.kind==="condition"?wu(r,t,n):r)}}function Wy(e,t,n){return{...e,trueBranch:e.trueBranch.map(r=>r.kind==="action"&&r.id===t?n(r):r.kind==="condition"?Wy(r,t,n):r),falseBranch:e.falseBranch.map(r=>r.kind==="action"&&r.id===t?n(r):r.kind==="condition"?Wy(r,t,n):r)}}function F3(e,t,n,r){return wu(e,t,i=>({...i,trueBranch:n==="true"?[...i.trueBranch,r]:i.trueBranch,falseBranch:n==="false"?[...i.falseBranch,r]:i.falseBranch}))}function f_(e){return e.length===1&&e[0].kind==="condition"}function Jve(e){let t=0,n=e??void 0;for(;n;){t+=1;let{falseBranch:r}=n;if(f_(r)){n=r[0];continue}r.length>0&&(t+=1),n=void 0}return t}function Yve(e){return!!e&&Jve(e)<Kve}function Qve(e,t){if(!e)return;let n=(r,i)=>{if(r.id===t)return i;let o=[];if(f_(r.falseBranch)){let a=n(r.falseBranch[0],i);if(a)return a}else o.push(...r.falseBranch.filter(a=>a.kind==="condition"));o.push(...r.trueBranch.filter(a=>a.kind==="condition"));for(let a of o){let s=n(a,a);if(s)return s}};return n(e,e)}function U3(e,t,n){let r=Qve(e,t);return!r||!Yve(r)?e:wu(e,t,i=>q3(i,n))}function q3(e,t){if(f_(e.falseBranch))return{...e,falseBranch:[q3(e.falseBranch[0],t)]};let n=p_(t);return n.falseBranch=e.falseBranch,{...e,falseBranch:[n]}}function B3(e,t){let n=Bd(e,t);if(!n||n.branch!=="false")return e;let r=n.node.falseBranch[n.index];if(!r||r.kind!=="condition")return e;let i=r.falseBranch;return wu(e,n.node.id,o=>({...o,falseBranch:i}))}function V3(e,t,n){let r=Bd(e,t);if(!r)return e;let i=o=>{let a=[...o],s=a[r.index+n];return s?(a[r.index+n]=a[r.index],a[r.index]=s,a):o};return wu(e,r.node.id,o=>({...o,trueBranch:r.branch==="true"?i(o.trueBranch):o.trueBranch,falseBranch:r.branch==="false"?i(o.falseBranch):o.falseBranch}))}function p_(e){return{kind:"condition",id:Wr(),displayName:e??"New Condition",clauses:[],logic:"AND",trueBranch:[],falseBranch:[],isCollapsed:!1}}function G3(e,t){let n={kind:"action",id:Wr(),type:e,displayName:t??`New ${e}`};switch(e){case"Recommendation":return{...n,type:"Recommendation",field:"",recommendationTitle:"",messageText:"",applyActions:[{id:Wr(),field:"",valueType:"Value",value:""}]};case"LockUnlock":return{...n,type:"LockUnlock",field:"",lock:!0};case"ShowErrorMessage":return{...n,type:"ShowErrorMessage",field:"",errorMessage:""};case"SetFieldValue":return{...n,type:"SetFieldValue",field:"",valueType:"Value",value:""};case"SetDefaultValue":return{...n,type:"SetDefaultValue",field:"",valueType:"Value",value:""};case"SetBusinessRequired":return{...n,type:"SetBusinessRequired",field:"",required:!0};case"SetVisibility":return{...n,type:"SetVisibility",field:"",visible:!0};default:return{...n,type:"SetFieldValue",field:"",valueType:"Value",value:""}}}function j3(e){if(!e)return[];let t=[];return W3(e,t),[...new Set(t)]}function W3(e,t){e.clauses.forEach(n=>{n.field&&t.push(n.field)}),[...e.trueBranch,...e.falseBranch].forEach(n=>{n.kind==="condition"?W3(n,t):"field"in n&&n.field&&t.push(n.field)})}function z3(e,t=[],n){if(!e)return[{nodeId:"root",kind:"NO_CONDITION",message:"A business rule must include at least one condition.",target:"node"}];let r=[],i=new Map(t.map(o=>[o.logicalName,o]));return K3(e,r,i,!0),n==="Entity"&&H3(e,r),zy(e)||r.push({nodeId:"root",kind:"NO_ACTION",message:"A business rule must include at least one action step.",target:"node"}),r}function H3(e,t){Hve(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(n=>{n.kind==="condition"&&H3(n,t)})}function K3(e,t,n,r=!1){let i=r&&Wve(e),o=!!e.rawConditionExpression;e.clauses.length===0&&!r&&!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?$l(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(ko(a.operator)&&a.valueType==="Value"&&!a.value&&!Gve(a,n))t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_VALUE",message:"Please enter a value for this clause.",target:"clauseValue",itemId:a.id});else if(ko(a.operator)&&a.valueType==="Value"&&a.value){let l=n.get(a.field);l?.maxLength&&a.value.length>l.maxLength&&t.push({nodeId:e.id,kind:"CLAUSE_VALUE_TOO_LONG",message:`Value exceeds the field's maximum length of ${l.maxLength} characters.`,target:"clauseValue",itemId:a.id,messageParams:{maxLength:l.maxLength}})}else ko(a.operator)&&a.valueType==="Expression"&&!a.rawExpression&&!xd(a.expression)?t.push(s==="invalidDayCount"?u_(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"}):ko(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"});ko(a.operator)&&a.valueType==="Value"&&a.value&&F4(n.get(a.field)?.attributeType)&&!ky(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 u=B4(a);ko(a.operator)&&a.valueType==="Value"&&a.value&&Ly(u)&&!V4(a.value,u)&&t.push({nodeId:e.id,kind:"INVALID_CLAUSE_NUMERIC_VALUE",message:jN(u)?"Please enter a whole number for this clause.":"Please enter a valid number for this clause.",target:"clauseValue",itemId:a.id,messageKey:jN(u)?"Validation.InvalidClauseWholeNumberValue":"Validation.InvalidClauseNumericValue"}),ko(a.operator)&&a.valueType==="Lookup"&&(s_(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"})),ko(a.operator)&&a_(e.id,"Condition",a.field,a.valueType,n,t,{operator:a.operator,target:"clauseValue",itemId:a.id})}),i&&e.trueBranch.forEach(a=>{a.kind==="action"&&zve.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")K3(a,t,n);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=n.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(n.size>0){let s=n.get(a.field),u=n.get(a.valueField);s&&u&&!xy(s.attributeType,u.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:$l(a.expression);!a.rawExpression&&!xd(a.expression)&&t.push(s==="invalidDayCount"?u_(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"&&!s_(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&&(a_(a.id,a.type,a.field,a.valueType,n,t,{target:"actionValue"}),L3(a.id,a.type,a.type,a.field,a.valueType,n,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(u=>{if(!u.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:u.id,messageKey:"Validation.RecommendationApplyField"});else if(u.valueType==="Field")u.valueField||t.push({nodeId:a.id,kind:"EMPTY_ACTION_VALUE",message:"Recommendation: please select a field to copy from.",target:"applyActionValue",itemId:u.id,messageKey:"Validation.RecommendationApplySourceField"});else if(u.valueType==="Expression"){let l=u.rawExpression?null:$l(u.expression);!u.rawExpression&&!xd(u.expression)&&t.push(l==="invalidDayCount"?u_(a.id,"applyActionValue",u.id):{nodeId:a.id,kind:"EMPTY_ACTION_VALUE",message:"Recommendation: please complete the formula.",target:"applyActionValue",itemId:u.id,messageKey:"Validation.RecommendationApplyFormula"})}else u.valueType==="Lookup"?s_(u.lookupValue)||t.push({nodeId:a.id,kind:"EMPTY_ACTION_VALUE",message:"Recommendation: please complete the lookup record.",target:"applyActionValue",itemId:u.id,messageKey:"Validation.RecommendationApplyLookupValue"}):u.valueType==="Clear"||u.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:u.id,messageKey:"Validation.RecommendationApplyValue"});u.field&&(a_(a.id,"Recommendation",u.field,u.valueType,n,t,{target:"applyActionValue",itemId:u.id}),L3(a.id,"Recommendation","SetFieldValue",u.field,u.valueType,n,t,{target:"applyActionValue",itemId:u.id}))})}}})}var Vve,x3,zve,Kve,m_=B(()=>{"use strict";VN();xN();Fy();Cm();$3();zN();GN();Vve=new Set(["LockUnlock","ShowErrorMessage","Recommendation","SetFieldValue","SetDefaultValue","SetBusinessRequired","SetVisibility"]);x3=new Set(["Lookup","Customer","Owner"]);zve=new Set(["SetFieldValue","ShowErrorMessage","Recommendation"]);Kve=10});var J3={};Fi(J3,{DAY_COUNT_MAX:()=>Md,DAY_COUNT_MIN:()=>YN,DEFAULT_DESERIALIZE_LABELS:()=>i_,WorkflowJsonMapper:()=>Ud,addElseIfInTree:()=>U3,appendToBranch:()=>F3,areFieldKindsCompatible:()=>xy,attributeTypeToWorkflowType:()=>X4,buildWorkflowEntity:()=>T4,collectUsedFields:()=>j3,createEmptyAction:()=>G3,createEmptyCondition:()=>p_,deserializeWorkflowJson:()=>R3,findNode:()=>c_,findParent:()=>Bd,getDefaultOperatorForFieldType:()=>H4,getExpressionModelIssue:()=>$l,getOperatorsForFieldType:()=>My,hasAnyTriggerGeneratingAction:()=>zy,isDayCountValid:()=>QN,isExpressionModelComplete:()=>xd,isOperatorCompatible:()=>K4,isTriggerGeneratingAction:()=>l_,moveBranchItemInTree:()=>V3,operatorNeedsValue:()=>ko,processTriggerFormIdFromScope:()=>UN,processTriggerScopeFromScope:()=>FN,removeElseIfInTree:()=>B3,removeNodeFromTree:()=>d_,serializeToWorkflowJson:()=>P3,supportsClearForActionType:()=>Dy,updateActionInTree:()=>Wy,updateConditionInTree:()=>wu,validateBusinessRule:()=>z3});var Y3=B(()=>{"use strict";xN();O4();o_();o_();m_();m_();Fy();Cm();Cm();});var Eu=C(Hy=>{"use strict";Object.defineProperty(Hy,"__esModule",{value:!0});Hy.cloneJson=void 0;function Xve(e){return JSON.parse(JSON.stringify(e))}Hy.cloneJson=Xve});var uj=C(Au=>{"use strict";Object.defineProperty(Au,"__esModule",{value:!0});Au.BUSINESS_RULE_NULL_GUID=Au.businessRuleRegistration=Au.BusinessRuleAdapter=void 0;var Q3=ft(),Nm=(Y3(),_i(J3)),X3=mo(),Z3=Y(),Zve=Eu(),ba=Vi(),ewe=Mv(),twe=ft(),nwe=fl(),rwe=new Set(["ShowErrorMessage","Recommendation"]);function rj(e){var t,n;return e?[...(t=e.trueBranch)!==null&&t!==void 0?t:[],...(n=e.falseBranch)!==null&&n!==void 0?n:[]].some(r=>Array.isArray(r.trueBranch)||Array.isArray(r.falseBranch)?rj(r):rwe.has(String(r.type))):!1}function iwe(e){return ij((0,Zve.cloneJson)(e))}function ij(e){var t,n;let r=i=>(i??[]).map(o=>owe(o)?ij(o):o);return{...e,logic:(t=e.logic)!==null&&t!==void 0?t:"AND",clauses:(n=e.clauses)!==null&&n!==void 0?n:[],trueBranch:r(e.trueBranch),falseBranch:r(e.falseBranch)}}function owe(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 awe(e){var t;if(e===null||typeof e!="object"||Array.isArray(e))throw new Z3.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 Z3.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 swe="00000000-0000-0000-0000-000000000000";Au.BUSINESS_RULE_NULL_GUID=swe;var uwe=new Set(["Recommendation","LockUnlock","ShowErrorMessage","SetFieldValue","SetDefaultValue","SetBusinessRequired","SetVisibility"]),lwe=["ruleId","name","description","entityLogicalName","scope","status","rootCondition"],cwe=["kind","id","displayName","logic","clauses","trueBranch","falseBranch"],dwe=["id","field","fieldDisplayName","operator","valueType","value","valueField","lookupValue","expression","rawExpression","valueWorkflowType"];function $o(e,t){return e===void 0?t:{...e,...t}}var xl=["kind","id","type","displayName","field","stepName","stepLabels"],ej=["valueType","valueWorkflowType","value","valueField","lookupValue","expression","rawExpression"],fwe={Recommendation:[...xl,"recommendationTitle","messageText","acceptanceText","applyActions","recommendationActionStepMeta"],LockUnlock:[...xl,"lock"],ShowErrorMessage:[...xl,"errorMessage","messageLevel","messageActionSteps"],SetFieldValue:[...xl,...ej],SetDefaultValue:[...xl,...ej],SetBusinessRequired:[...xl,"required"],SetVisibility:[...xl,"visible"]};function Ne(e,t){return t===void 0?{}:{[e]:t}}function oj(e){var t;return e==null?void 0:{...e,label:(t=e.label)!==null&&t!==void 0?t:""}}function h_(e){return{valueType:e.valueType,...Ne("valueWorkflowType",e.valueWorkflowType),...Ne("value",e.value),...Ne("valueField",e.valueField),...Ne("lookupValue",oj(e.lookupValue)),...Ne("expression",e.expression),...Ne("rawExpression",e.rawExpression)}}function aj(e,t){let n=new Set(t),r={};for(let[i,o]of Object.entries(e))n.has(i)||o!==void 0&&(r[i]=o);return Object.keys(r).length>0?r:void 0}var pwe=["id","field","valueType","valueWorkflowType","value","valueField","lookupValue","expression","rawExpression","stepName","displayName"];function mwe(e){return $o(e.bag,{id:e.id,field:e.field,...h_(e),...Ne("stepName",e.stepName),...Ne("displayName",e.displayName)})}function hwe(e){let t=aj(e,pwe);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 tj(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 nj(e){throw new Error(`Unsupported business-rule action type: ${e.type}`)}var gwe=new Set(["INVALID_CLEAR_FOR_FIELD","INVALID_VALUE_TYPE_FOR_FIELD","CLAUSE_VALUE_TOO_LONG","ACTION_VALUE_TOO_LONG"]),ywe=new Set,bwe="INVALID_CLEAR_FOR_FIELD";function vwe(e){let t=r=>{var i;return(0,ba.isJsonObject)(r)&&(r.label===""||r.label===void 0)?{...r,label:String((i=r.id)!==null&&i!==void 0?i:"")}:r},n=r=>{if(!(0,ba.isJsonObject)(r))return r;let i={...r};"lookupValue"in i&&(i.lookupValue=t(i.lookupValue)),Array.isArray(i.applyActions)&&(i.applyActions=i.applyActions.map(n));for(let o of["clauses","trueBranch","falseBranch"])Array.isArray(i[o])&&(i[o]=i[o].map(n));return i};return n(e)}var Ky=class{toArtifact(t){let n=this.residualBag(t,lwe),r={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 n&&(r.bag=n),r}fromArtifact(t){let n=t.rootCondition?this.conditionFromJson(t.rootCondition):null;return $o(t.bag,{ruleId:t.id,name:t.name,description:t.description,entityLogicalName:t.entityLogicalName,scope:t.scope,status:t.status,rootCondition:n})}fromApiResponse(t){var n;let r=t??{},i={...(n=r.Entity)!==null&&n!==void 0?n:{},wfomJson:r.WfomJson},o=(0,Nm.deserializeWorkflowJson)(i);return this.toArtifact(o)}needsBaseLanguage(t){return rj(t.rootCondition)}toApiPayload(t,n,r){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,Nm.serializeToWorkflowJson)(a,(i=r?.baseLanguageCode)!==null&&i!==void 0?i:nwe.DEFAULT_LCID),u=(o=a.ruleId)!==null&&o!==void 0?o:(0,Q3.newId)();return{Entity:this.buildWorkflowEntity(a,u),WfomJson:s,status:t.status}}createDefault(t){var n,r,i,o,a,s;let u={ruleId:(n=t.id)!==null&&n!==void 0?n:null,name:(r=t.name)!==null&&r!==void 0?r:"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,Nm.createEmptyCondition)():t.rootCondition===null?null:this.conditionFromJson(iwe(awe(t.rootCondition)))},l=this.toArtifact(u);return l.id||(l.id=(0,Q3.newId)()),l}assignMissingIds(t){return(0,twe.assignMissingIds)(t)}validate(t){let n=[],r=t.rootCondition;return r==null?n:(0,ba.isJsonObject)(r)?(sj(r,"/rootCondition",n),n):(n.push((0,ba.issue)("/rootCondition","condition-must-be-object",`rootCondition must be a JSON object or null, got ${typeof r}`)),n)}semanticIssues(t,n=[]){let r;try{r=this.fromArtifact(t)}catch(a){return[(0,ba.issue)("/rootCondition","rule-not-representable",a instanceof Error?a.message:String(a))]}let i=r.rootCondition===null?null:vwe(r.rootCondition),o;return n.length===0?o=gwe:n.some(a=>a.requiredLevel!==void 0)?o=ywe:o=new Set([bwe]),(0,Nm.validateBusinessRule)(i,n).filter(a=>!o.has(a.kind)).map(a=>(0,ba.issue)(`/rootCondition (${a.nodeId})`,`business-rule-${a.kind}`,a.message))}issuesBlockingPush(t,n=[],r){return this.semanticIssues(t,n)}columnsCheckedAtPush(t){let n;try{n=this.fromArtifact(t)}catch{return[]}let r=new Set,i=a=>{a&&r.add(a)},o=a=>{var s;for(let u of a.clauses)i(u.field),i(u.valueField);for(let u of[...a.trueBranch,...a.falseBranch]){if(u.kind==="condition"){o(u);continue}if(i(u.field),u.type==="SetFieldValue"||u.type==="SetDefaultValue")i(u.valueField);else if(u.type==="Recommendation")for(let l of(s=u.applyActions)!==null&&s!==void 0?s:[])i(l.field),i(l.valueField)}};return n.rootCondition&&o(n.rootCondition),[...r]}residualBag(t,n){return aj(t,n)}buildWorkflowEntity(t,n){return(0,Nm.buildWorkflowEntity)(t,n)}conditionToJson(t){let n=this.residualBag(t,cwe),r={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 n&&(r.bag=n),r}clauseToJson(t){let n=this.residualBag(t,dwe),r={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 n&&(r.bag=n),r}branchItemToJson(t){return t.kind==="condition"?this.conditionToJson(t):this.actionToJson(t)}actionToJson(t){let n=this.residualBag(t,fwe[t.type]),r={kind:"action",id:t.id,displayName:t.displayName,field:t.field,...Ne("stepName",t.stepName),...Ne("stepLabels",t.stepLabels),...Ne("bag",n)};switch(t.type){case"Recommendation":return{...r,type:"Recommendation",recommendationTitle:t.recommendationTitle,messageText:t.messageText,...Ne("acceptanceText",t.acceptanceText),applyActions:t.applyActions.map(hwe),...Ne("recommendationActionStepMeta",t.recommendationActionStepMeta)};case"LockUnlock":return{...r,type:"LockUnlock",lock:t.lock};case"ShowErrorMessage":return{...r,type:"ShowErrorMessage",errorMessage:t.errorMessage,...Ne("messageLevel",t.messageLevel),...Ne("messageActionSteps",t.messageActionSteps)};case"SetFieldValue":return{...r,type:"SetFieldValue",...tj(t)};case"SetDefaultValue":return{...r,type:"SetDefaultValue",...tj(t)};case"SetBusinessRequired":return{...r,type:"SetBusinessRequired",required:t.required};case"SetVisibility":return{...r,type:"SetVisibility",visible:t.visible};default:return nj(t)}}conditionFromJson(t){var n;let r=(n=t.bag)!==null&&n!==void 0?n:{};return $o(r,{kind:"condition",isCollapsed:typeof r.isCollapsed=="boolean"?r.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 n;return $o(t.bag,{id:t.id,field:t.field,fieldDisplayName:(n=t.fieldDisplayName)!==null&&n!==void 0?n:t.field,operator:t.operator,valueType:t.valueType,...Ne("value",t.value),...Ne("valueField",t.valueField),...Ne("lookupValue",oj(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(!uwe.has(t.type))throw new Error(`Unsupported business-rule action type: ${t.type}`);Ewe(t);let n={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 $o(t.bag,{...n,type:"Recommendation",recommendationTitle:t.recommendationTitle,messageText:t.messageText,...Ne("acceptanceText",t.acceptanceText),applyActions:t.applyActions.map(mwe),...Ne("recommendationActionStepMeta",t.recommendationActionStepMeta)});case"LockUnlock":return $o(t.bag,{...n,type:"LockUnlock",lock:t.lock});case"ShowErrorMessage":return $o(t.bag,{...n,type:"ShowErrorMessage",errorMessage:t.errorMessage,...Ne("messageLevel",t.messageLevel),...Ne("messageActionSteps",t.messageActionSteps)});case"SetFieldValue":return $o(t.bag,{...n,type:"SetFieldValue",...h_(t)});case"SetDefaultValue":return $o(t.bag,{...n,type:"SetDefaultValue",...h_(t)});case"SetBusinessRequired":return $o(t.bag,{...n,type:"SetBusinessRequired",required:t.required});case"SetVisibility":return $o(t.bag,{...n,type:"SetVisibility",visible:t.visible});default:return nj(t)}}isConditionJson(t){return Object.prototype.hasOwnProperty.call(t,"clauses")&&Object.prototype.hasOwnProperty.call(t,"logic")&&!Object.prototype.hasOwnProperty.call(t,"type")}};Au.BusinessRuleAdapter=Ky;function sj(e,t,n){(0,ba.optionalEnum)(e,"logic",["AND","OR"],t,"condition-logic-invalid",n),(0,ba.childObjects)(e,"clauses",t,"clause",n);for(let r of["trueBranch","falseBranch"])(0,ba.childObjects)(e,r,t,"branchItem",n).forEach(({node:o,index:a})=>{"clauses"in o||"trueBranch"in o||"falseBranch"in o?sj(o,`${t}/${r}/${a}`,n):wwe(o,`${t}/${r}/${a}`,n)})}function wwe(e,t,n){e.type==="SetDefaultValue"&&e.valueType==="Clear"&&n.push((0,ba.issue)(`${t}/valueType`,"clear-only-set-field-value","Clear is only supported for SetFieldValue actions."))}function Ewe(e){if(e.type==="SetDefaultValue"&&e.valueType==="Clear")throw new Error("Clear is only supported for SetFieldValue actions.")}function Awe(){return{adapter:new Ky,api:ewe.businessRuleApi,publish:(e,t,n)=>(0,X3.publishBoundEntity)(e,n),publishScope:(e,t)=>(0,X3.boundEntityPublishScope)(t)}}Au.businessRuleRegistration=Awe});var Nj=C(Cu=>{"use strict";Object.defineProperty(Cu,"__esModule",{value:!0});Cu.appRegistration=Cu.AppAdapter=Cu.HEADER_NAV_BOOLEAN_RULE=void 0;var ys=Vi(),Yn=Us(),Tm=ja(),Om=vc(),g_=Ff(),y_=Ga(),Cwe=ft(),Swe=ae(),bj=fl(),vj=Y(),wj=h0();Object.defineProperty(Cu,"HEADER_NAV_BOOLEAN_RULE",{enumerable:!0,get:function(){return wj.HEADER_NAV_BOOLEAN_RULE}});var Xy="7.0.0.0",lj=`<SiteMap IntroducedVersion="${Xy}"></SiteMap>`,cj="/_imgs/imagestrips/transparent_spacer.gif",dj="/_imgs/TableIconsFluentV9/document_one_page_sparkle.svg",Ej=["Entity","Url","DefaultDashboard","Page","GenPageId"],_m="sitemapId",fj="sitemapName",b_="sitemapNameUnique",pj="aiDescription",mj="[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}",Nwe=new RegExp(`^(?:\\{${mj}\\}|${mj})$`);function hj(e,t){if(!Nwe.test(e.trim()))throw new vj.ValidationError("app",t,[{pointer:"/sitemapId",rule:"app-sitemapid-guid",message:`sitemapId must be a GUID; received '${e}'.`}]);return e.trim()}function gj(e,t,n){if(e===void 0)return n;if(typeof e!="boolean")throw new vj.ValidationError("app",t,[Aj(e)]);return e}function Aj(e){return(0,ys.issue)("/headerAndNavigationRefresh",wj.HEADER_NAV_BOOLEAN_RULE,`headerAndNavigationRefresh must be a boolean, got ${typeof e}`)}function _we(e){let t=r=>{let i=e[r];return typeof i=="string"&&i.trim()!==""?i.trim():void 0},n=r=>{let i=t(r);if(i!==void 0)try{return(0,Swe.normalizeGuid)(i,r)}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 n("dashboardId")&&`DashBoard:${n("dashboardId")}`;case"CustomPage":return t("page")&&`CustomPage:${t("page").toLowerCase()}`;case"GenPage":return n("genPageId")&&`GenPage:${n("genPageId")}`;default:return}}function Iwe(e){var t,n,r,i;let o=[];for(let a of(n=(t=e.siteMap)===null||t===void 0?void 0:t.areas)!==null&&n!==void 0?n:[])for(let s of(r=a.groups)!==null&&r!==void 0?r:[])for(let u of(i=s.subAreas)!==null&&i!==void 0?i:[])u.type==="Entity"&&u.entity&&o.push(u.entity);return o}var Zy=class{constructor(t=bj.DEFAULT_LCID){this.lcid=t}toArtifact(t){let{bag:n,modeledEls:r}=Jy(t,"Area");return{id:"",name:"",uniqueName:"",description:"",siteMap:{areas:r.map(i=>this.areaToJson(i)),bag:n},bag:(0,Yn.emptyBag)()}}fromArtifact(t){(0,y_.installDomShim)();let n=this.assignMissingIds(JSON.parse(JSON.stringify(t))),r=new DOMParser().parseFromString("<root/>","text/xml"),i=this.rootToRaw(n);return(0,Yn.rebuildRaw)(i,(0,Tm.domEngine)(r),null)}fromApiResponse(t){var n,r,i,o,a,s,u,l,c,d,f;(0,y_.installDomShim)();let p=t??{},m=(n=p.$sitemap)!==null&&n!==void 0?n:p,h=(0,Tm.parseXmlRoot)((r=m.sitemapxml)!==null&&r!==void 0?r:lj,lj),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:[[_m,(l=(u=m.sitemapid)!==null&&u!==void 0?u:p._sitemapid_value)!==null&&l!==void 0?l:""],[fj,(c=m.sitemapname)!==null&&c!==void 0?c:""],[b_,(d=m.sitemapnameunique)!==null&&d!==void 0?d:""],[pj,(f=p.aiappdescription)!==null&&f!==void 0?f:""]],c:[]},g}toApiPayload(t,n){var r,i,o,a,s,u,l,c,d,f,p,m,h,g,y,b;(0,y_.installDomShim)();let E=(0,Tm.serializeNode)(this.fromArtifact(t)),w=[],_=[];for(let T of(i=(r=t.siteMap)===null||r===void 0?void 0:r.areas)!==null&&i!==void 0?i:[])for(let O of(o=T.groups)!==null&&o!==void 0?o:[])for(let v of(a=O.subAreas)!==null&&a!==void 0?a:[])v.type==="Entity"&&v.entity?w.push(v.entity):v.type==="DashBoard"&&v.dashboardId&&_.push(v.dashboardId);let I=(s=t.bag)!==null&&s!==void 0?s:(0,Yn.emptyBag)();return{sitemapId:Im(I,_m)||(t.sitemapId?hj(t.sitemapId,t.id):""),sitemapxml:E,sitemapname:Im(I,fj)||t.name,...Im(I,b_)?{sitemapNameUnique:Im(I,b_)}:{},appModuleId:t.id,appModuleName:t.name,appModuleDescription:t.description,...t.aiDescription!==void 0&&t.aiDescription!==(n?n.aiDescription:Im(I,pj))?{appModuleAiDescription:t.aiDescription}:{},appModuleUniqueName:t.uniqueName,...t.iconWebResourceId?{iconWebResourceId:t.iconWebResourceId}:{},...t.headerAndNavigationRefresh===void 0?{}:{appSettings:{[g_.HEADER_AND_NAVIGATION_REFRESH]:gj(t.headerAndNavigationRefresh,(u=t.id)!==null&&u!==void 0?u:"(unknown)",!0)?g_.APP_SETTING_ON:g_.APP_SETTING_OFF}},...typeof t.published=="boolean"?{published:t.published}:{},entities:w,components:{forms:(c=(l=t.components)===null||l===void 0?void 0:l.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:[],..._],...((y=t.components)===null||y===void 0?void 0:y.mainFormsByTable)!==void 0?{mainFormsByTable:t.components.mainFormsByTable}:{},...((b=t.components)===null||b===void 0?void 0:b.mainFormsOnUpdate)!==void 0?{mainFormsOnUpdate:t.components.mainFormsOnUpdate}:{}}}}createDefault(t){var n,r,i,o,a,s;let u=!((n=t.siteMap)===null||n===void 0)&&n.areas&&t.siteMap.areas.length>0?t.siteMap.areas:[{id:"",title:"Area",groups:[{id:"",title:"Group",subAreas:[]}]}],l=(r=t.id)!==null&&r!==void 0?r:(0,Cwe.newId)();return{id:l,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:u},...t.sitemapId?{sitemapId:hj(t.sitemapId,l)}:{},...t.iconWebResourceId?{iconWebResourceId:t.iconWebResourceId}:{},headerAndNavigationRefresh:gj(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 n=t;if(!n||typeof n!="object")return t;let r=n.siteMap;return r&&Array.isArray(r.areas)?r.areas.forEach(E_):Array.isArray(n.areas)?n.areas.forEach(E_):Array.isArray(n.groups)?E_(n):Array.isArray(n.subAreas)?Sj(n):"type"in n&&eb(n,"subarea"),t}validate(t){let n=[],r=t.published;r!==void 0&&typeof r!="boolean"&&n.push((0,ys.issue)("/published","published-must-be-boolean",`published must be a boolean, got ${typeof r}`));let i=t.siteMap,o=t.headerAndNavigationRefresh;if(o!==void 0&&typeof o!="boolean"&&n.push(Aj(o)),i==null)return n;if(!(0,ys.isJsonObject)(i))return n.push((0,ys.issue)("/siteMap","sitemap-must-be-object",`siteMap must be a JSON object, got ${typeof i}`)),n;let a=(0,ys.childObjects)(i,"areas","/siteMap","area",n),s=new Map;return a.forEach(({node:u,index:l})=>{let c=`/siteMap/areas/${l}`;(0,ys.childObjects)(u,"groups",c,"group",n).forEach(({node:f,index:p})=>{let m=`${c}/groups/${p}`;(0,ys.childObjects)(f,"subAreas",m,"subArea",n).forEach(({node:g,index:y})=>{let b=`${m}/subAreas/${y}`;(0,ys.optionalEnum)(g,"type",["Entity","URL","DashBoard","CustomPage","GenPage"],b,"subarea-type-invalid",n);let E=_we(g);if(!E)return;let w=s.get(E);if(w===void 0){s.set(E,b);return}n.push((0,ys.issue)(b,"subarea-duplicate-target",`the sitemap already navigates to this target at ${w}; a duplicate SubArea would pin it twice and a single removeElement would leave one behind`))})})}),n}issuesBlockingPush(t){var n,r,i;return[...(0,Om.mainFormSetShapeIssues)((n=t.components)===null||n===void 0?void 0:n.mainFormsByTable,Iwe(t)),...(0,Om.mainFormModeIssues)((r=t.components)===null||r===void 0?void 0:r.mainFormsOnUpdate,(i=t.components)===null||i===void 0?void 0:i.mainFormsByTable)]}applyServerIdentity(t,n){let r=n[_m];if(!r)return;t.bag||(t.bag=(0,Yn.emptyBag)());let i=t.bag.a.find(o=>o[0]===_m);i?i[1]=r:t.bag.a.push([_m,r])}areaToJson(t){var n;let{bag:r,modeledEls:i}=Jy(t,"Group"),o={id:(n=t.getAttribute("Id"))!==null&&n!==void 0?n:"",title:v_(t,this.lcid),groups:i.map(u=>this.groupToJson(u)),bag:r},a=t.getAttribute("Icon");a&&(o.icon=a);let s=t.getAttribute("VectorIcon");return s&&(o.vectorIcon=s),o}groupToJson(t){var n;let{bag:r,modeledEls:i}=Jy(t,"SubArea");return{id:(n=t.getAttribute("Id"))!==null&&n!==void 0?n:"",title:v_(t,this.lcid),subAreas:i.map(o=>this.subAreaToJson(o)),bag:r}}subAreaToJson(t){var n;let{bag:r}=Jy(t,null),i=Twe(t),o={id:(n=t.getAttribute("Id"))!==null&&n!==void 0?n:"",type:i,title:v_(t,this.lcid),bag:r};if(i==="Entity"){let u=t.getAttribute("Entity");u&&(o.entity=u)}else if(i==="DashBoard"){let u=t.getAttribute("DefaultDashboard");u&&(o.dashboardId=u);let l=t.getAttribute("Url");l&&(o.dashboardUrl=l)}else if(i==="CustomPage"){let u=t.getAttribute("Page");u&&(o.page=u)}else if(i==="GenPage"){let u=t.getAttribute("GenPageId");u&&(o.genPageId=u)}else{let u=t.getAttribute("Url");u&&(o.url=u)}let a=t.getAttribute("Icon");a&&a!==cj&&(o.icon=a);let s=t.getAttribute("VectorIcon");return s&&(o.vectorIcon=s),o}rootToRaw(t){var n,r,i,o;let a=(r=(n=t.siteMap)===null||n===void 0?void 0:n.bag)!==null&&r!==void 0?r:(0,Yn.emptyBag)(),u=Yy(a)?[["IntroducedVersion",Xy]]:[],l=((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,Yn.mergeAttrs)(a.a,u),c:(0,Yn.spliceChildren)(a.c,l)}}areaToRaw(t){var n,r;let i=(n=t.bag)!==null&&n!==void 0?n:(0,Yn.emptyBag)(),o=Yy(i),a=[],s=[];t.id&&a.push(["Id",t.id]),o&&a.push(["ShowGroups","true"],["ResourceId","SitemapDesigner.NewTitle"],["DescriptionResourceId","SitemapDesigner.NewTitle"],["IntroducedVersion",Xy]),t.icon!==void 0?a.push(["Icon",t.icon]):Qy(i.a,"Icon")&&s.push("Icon"),t.vectorIcon!==void 0?a.push(["VectorIcon",t.vectorIcon]):Qy(i.a,"VectorIcon")&&s.push("VectorIcon");let u=((r=t.groups)!==null&&r!==void 0?r:[]).map(c=>this.groupToRaw(c)),l=w_((0,Yn.spliceChildren)(i.c,u),t.title,o,this.lcid);return{n:"Area",a:(0,Yn.mergeAttrs)(i.a,a,s),c:l}}groupToRaw(t){var n,r;let i=(n=t.bag)!==null&&n!==void 0?n:(0,Yn.emptyBag)(),o=Yy(i),a=[];t.id&&a.push(["Id",t.id]),o&&a.push(["ResourceId","SitemapDesigner.NewGroup"],["DescriptionResourceId","SitemapDesigner.NewGroup"],["ToolTipResourseId","SitemapDesigner.Unknown"],["IntroducedVersion",Xy],["IsProfile","false"]);let s=((r=t.subAreas)!==null&&r!==void 0?r:[]).map(l=>this.subAreaToRaw(l)),u=w_((0,Yn.spliceChildren)(i.c,s),t.title,o,this.lcid);return{n:"Group",a:(0,Yn.mergeAttrs)(i.a,a),c:u}}subAreaToRaw(t){var n;let r=(n=t.bag)!==null&&n!==void 0?n:(0,Yn.emptyBag)(),i=Yy(r),o=Dwe(r.a,t.type),a=[],s=[];t.id&&a.push(["Id",t.id]);let u=!i&&!r.a.some(([c])=>Ej.includes(c));Rwe(a,t,u),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]):Qy(o,"Icon",cj)&&s.push("Icon"),t.vectorIcon!==void 0?a.push(["VectorIcon",t.vectorIcon]):Qy(o,"VectorIcon")?t.type==="GenPage"?a.push(["VectorIcon",dj]):s.push("VectorIcon"):t.type==="GenPage"&&!Owe(o,"VectorIcon")&&a.push(["VectorIcon",dj]);let l=w_((0,Yn.spliceChildren)(r.c,[]),t.title,i,this.lcid);return{n:"SubArea",a:(0,Yn.mergeAttrs)(o,a,s),c:l}}};Cu.AppAdapter=Zy;function Jy(e,t){let n=(0,Tm.nodeLikeFromDom)(e).getAllProperties().map(s=>[s.key,s.value]),r=[],i=[],o=e.childNodes,a=0;for(let s=0;s<o.length;s+=1){let u=o[s];u.nodeType!==1&&u.nodeType!==3||(u.nodeType===1&&t!==null&&u.tagName===t?i.push(u):r.push({i:a,node:(0,Yn.rawFromNode)((0,Tm.nodeLikeFromDom)(u))}),a+=1)}return{bag:{a:n,c:r},modeledEls:i}}function yj(e,t){let n=[],r=e.childNodes;for(let i=0;i<r.length;i+=1){let o=r[i];o.nodeType===1&&o.tagName===t&&n.push(o)}return n}function v_(e,t){var n;let r=yj(e,"Titles")[0];if(!r)return"";let o=yj(r,"Title").find(a=>a.getAttribute("LCID")===String(t));return o&&(n=o.getAttribute("Title"))!==null&&n!==void 0?n:""}function Twe(e){return e.getAttribute("GenPageId")?"GenPage":e.getAttribute("Entity")?"Entity":e.getAttribute("Page")?"CustomPage":e.getAttribute("DefaultDashboard")?"DashBoard":"URL"}function Yy(e){return e.a.length===0&&e.c.length===0}function Owe(e,t){return e.some(([n])=>n===t)}function Qy(e,t,n){let r=e.find(([o])=>o===t),i=r?.[1];return!!i&&i!==n}function Im(e,t){let n=e.a.find(([r])=>r===t);return n?n[1]:void 0}function Dwe(e,t){let n=Pwe(t);return e.filter(([r])=>!Ej.includes(r)||n.has(r)).map(r=>[r[0],r[1]])}function Pwe(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 Rwe(e,t,n){var r,i,o,a,s;switch(t.type){case"Entity":e.push(["Entity",(r=t.entity)!==null&&r!==void 0?r:""]);break;case"URL":(t.url!==void 0||!n)&&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 w_(e,t,n,r){if(!t)return e;let i=e.findIndex(o=>o.n==="Titles");if(i>=0){let o=e.slice();return o[i]=kwe(e[i],t,r),o}return n?[$we(t,r),...e]:e}function kwe(e,t,n){let r=!1,i=e.c.map(o=>!r&&o.n==="Title"&&Lwe(o,"LCID")===String(n)?(r=!0,{n:o.n,a:(0,Yn.mergeAttrs)(o.a,[["Title",t]]),c:o.c}):o);return r||i.unshift(Cj(t,n)),{n:e.n,a:e.a.map(o=>[o[0],o[1]]),c:i}}function $we(e,t){return{n:"Titles",a:[],c:[Cj(e,t)]}}function Cj(e,t){return{n:"Title",a:[["LCID",String(t)],["Title",e]],c:[]}}function Lwe(e,t){let n=e.a.find(([r])=>r===t);return n?n[1]:void 0}function Mwe(e){let t="0123456789abcdef",n="";for(let r=0;r<e;r+=1)n+=t[Math.floor(Math.random()*t.length)];return n}function eb(e,t){e&&(typeof e.id!="string"||e.id.length===0)&&(e.id=`${t}_${Mwe(8)}`)}function E_(e){var t;eb(e,"area");for(let n of(t=e.groups)!==null&&t!==void 0?t:[])Sj(n)}function Sj(e){var t;eb(e,"group");for(let n of(t=e.subAreas)!==null&&t!==void 0?t:[])eb(n,"subarea")}function xwe(e=bj.DEFAULT_LCID){return{adapter:new Zy(e),api:Om.appApi,languageSensitive:!0,publish:(t,n)=>(0,Om.publishApp)(t,n),assertCombinablePublish:(t,n)=>(0,Om.assertAppPublicationCombinable)(t,n),publishScope:t=>({envelope:"appmodule",targetIds:[t]}),publishesOnPush:(t,n)=>{let r=t?.published;return n?r!==!1:r===!0},rebaselineAfterPublish:"bracket"}}Cu.appRegistration=xwe});var _j={};Fi(_j,{ActionType:()=>C_,AppActionOrigin:()=>P_,AppActionVisibilityType:()=>D_,ButtonType:()=>N_,CannotUpdateAppActionColumns:()=>Fwe,Context:()=>I_,IconType:()=>S_,Location:()=>__,OnClickEventType:()=>O_,Scope:()=>T_,VisibilityType:()=>A_});var A_,C_,S_,N_,__,I_,T_,O_,D_,P_,Fwe,Ij=B(()=>{"use strict";(function(e){e[e.NotSupported=0]="NotSupported",e[e.Show=1]="Show",e[e.ClassicRules=2]="ClassicRules",e[e.Expression=3]="Expression"})(A_||(A_={}));(function(e){e[e.NotSupported=0]="NotSupported",e[e.None=1]="None",e[e.JavaScript=2]="JavaScript",e[e.Expression=3]="Expression"})(C_||(C_={}));(function(e){e[e.NoIcon=0]="NoIcon",e[e.UseIcon=1]="UseIcon",e[e.UseWebResource=2]="UseWebResource"})(S_||(S_={}));(function(e){e[e.Standard=0]="Standard",e[e.Dropdown=1]="Dropdown",e[e.Split=2]="Split",e[e.Group=3]="Group"})(N_||(N_={}));(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"})(__||(__={}));(function(e){e[e.All=0]="All",e[e.Entity=1]="Entity"})(I_||(I_={}));(function(e){e[e.App=0]="App",e[e.Entity=1]="Entity",e[e.Global=2]="Global"})(T_||(T_={}));(function(e){e[e.None=0]="None",e[e.Formula=1]="Formula",e[e.JavaScript=2]="JavaScript"})(O_||(O_={}));(function(e){e[e.None=0]="None",e[e.Formula=1]="Formula",e[e.ClassicRules=2]="ClassicRules"})(D_||(D_={}));(function(e){e[e.Default=0]="Default",e[e.Migrated=1]="Migrated",e[e.MigratedClone=2]="MigratedClone"})(P_||(P_={}));Fwe=["appactionid","appmoduleid","context","contextvalue","location","name","type","uniquename","isdisabled","origin"]});var Hj=C(jd=>{"use strict";Object.defineProperty(jd,"__esModule",{value:!0});jd.commandRegistration=jd.CommandAdapter=void 0;var fn=(Ij(),_i(_j)),Tj=mo(),Ln=Vi(),Vd=Xv(),Uwe=aw(),F_=LA(),$j=ft(),Fl=ae(),Gd=Y(),k_="$ClientSvg:",$_=".svg",qwe=2,Bwe=1,Vwe=1,Lj="entityMetadataId",Gwe=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"]),Pm=class{toArtifact(t){var n,r,i,o,a,s,u;let l=(n=t.appActions)!==null&&n!==void 0?n:[],c=(r=t.entityLogicalName)!==null&&r!==void 0?r:"",d=l.find(h=>typeof h.appactionid!="string"||h.appactionid==="");if(d)throw new Gd.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 l){let g=typeof h._parentappactionid_value=="string"&&h._parentappactionid_value?h._parentappactionid_value:"",y=(o=f.get(g))!==null&&o!==void 0?o:[];y.push(h),f.set(g,y)}let p=new Map;for(let h of(a=f.get(""))!==null&&a!==void 0?a:[]){let g=x_(h.location),y=(s=p.get(g))!==null&&s!==void 0?s:[];y.push(h),p.set(g,y)}let m=[];for(let[h,g]of p)m.push({location:h,groups:Wwe(g,f,q_(h),c)});return{id:c,entityLogicalName:c,commandBars:zwe(m),bag:{a:[[Lj,(u=t.entityMetadataId)!==null&&u!==void 0?u:""]]}}}fromArtifact(t){return{entityLogicalName:t.entityLogicalName,entityMetadataId:M_(t),appActions:nb(t).map(n=>n.row)}}fromApiResponse(t){return this.toArtifact(t??{})}toApiPayload(t,n){let r=new Set(n?nb(n).map(f=>f.appactionid):[]),i=nb(t,new Set([...r].map(f=>f.toLowerCase()))),o=new Set(i.map(f=>f.appactionid)),a=i.map(f=>{let p=f.exists||r.has(f.appactionid);return{appactionid:f.appactionid,exists:p,etag:f.etag,body:p?rEe(f.row):zj(f.row),...f.inheritsParentLocation===!0&&!p?{inheritsParentLocation:!0}:{}}}),s=[...r].filter(f=>!o.has(f));(0,Vd.assertOneWritePerRow)(t.entityLogicalName,{rows:a,deletedRowIds:s});let{sentDisabled:u,disabledAfter:l}=tEe(t,n,r),c=new Map([...u].map(([f,p])=>[va(f),p]));for(let f of a){let p=f.exists?c.get(va(f.appactionid)):void 0;p!==void 0&&(f.body.isdisabled=p)}let d=nEe(t,n,r);return{entityLogicalName:t.entityLogicalName,entityMetadataId:M_(t),rows:a,...s.length>0?{deletedRowIds:s}:{},...Object.keys(d).length>0?{keptDisabled:d}:{},...l.size>0?{disabledAfter:Object.fromEntries(l)}:{},...u.size>0?{sentDisabled:Object.fromEntries(u)}:{}}}committed(t,n){let{keptDisabled:r,disabledAfter:i}=n??{},o=new Map(Object.entries(r??{}).map(([l,c])=>[va(l),c])),a=new Map(Object.entries(i??{}).map(([l,c])=>[va(l),c]));if(o.size===0&&a.size===0)return{artifact:t,baseline:t};let u=Dj(t,l=>{let c=!wa(l.bag)&&l.disabled===void 0?o.get(va(l.id)):void 0,d=wa(l.bag)?a.get(va(Rm(l))):void 0,f=d!==void 0?Oj(l.bag,d):void 0;return c===void 0&&f===void 0?l:{...l,...c!==void 0?{disabled:c}:{},...f?{bag:f}:{}}});return{artifact:u,baseline:u}}partiallyCommitted(t,n,r){var i;let o=(i=n?.sentDisabled)!==null&&i!==void 0?i:{},a=new Set(r.map(va)),s=Object.keys(o).filter(l=>a.has(va(l)));return s.length===0?t:Dj(t,l=>{let c=va(Rm(l)),d=s.find(f=>va(f)===c);return d===void 0?l:wa(l.bag)?{...l,bag:Oj(l.bag,o[d])}:{...l,disabled:o[d]}})}createDefault(t){var n,r,i,o;let a=(r=(n=t.entityLogicalName)!==null&&n!==void 0?n:t.id)!==null&&r!==void 0?r:"";return{id:(i=t.id)!==null&&i!==void 0?i:a,entityLogicalName:a,commandBars:(o=t.commandBars)!==null&&o!==void 0?o:[]}}assignMissingIds(t){return(0,$j.assignMissingIds)(t)}normalize(t){let n=Hwe(t),r=!1,i=(Array.isArray(t.commandBars)?t.commandBars:[]).map(o=>{let a=(0,Ln.isJsonObject)(o)&&Array.isArray(o.groups)?o.groups:void 0;if(!a)return o;let s=!1,u=a.map(l=>{let c=(0,Ln.isJsonObject)(l)&&Array.isArray(l.controls)?l.controls:void 0;if(!c)return l;let d=c.map(f=>Bj(f,n));return d.every((f,p)=>f===c[p])?l:(s=!0,{...l,controls:d})});return s?(r=!0,{...o,groups:u}):o});return r?{...t,commandBars:i}:t}validate(t){let n=[];return(0,Ln.childObjects)(t,"commandBars","","commandBar",n).forEach(({node:i,index:o})=>{let a=`/commandBars/${o}`;(0,Ln.optionalEnum)(i,"location",["MainTab","ContextualTab","HomeTab"],a,"bar-location-invalid",n),(0,Ln.childObjects)(i,"groups",a,"group",n).forEach(({node:u,index:l})=>{let c=`${a}/groups/${l}`;wa(u.bag)||((0,Ln.optionalGuidId)(u,"id",c,"group-id-invalid",n),typeof u.title=="string"&&u.title.length>0&&n.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."})),Mj((0,Ln.childObjects)(u,"controls",c,"control",n),`${c}/controls`,n)})}),n}};jd.CommandAdapter=Pm;function wa(e){let t=e?.a;return Array.isArray(t)&&t.length>0}function va(e){try{return(0,Fl.normalizeGuid)(e,"row id")}catch{return e.toLowerCase()}}function Oj(e,t){return{...e,a:[...e.a.filter(([n])=>n!=="isdisabled"),["isdisabled",t]]}}function Dj(e,t){var n;let r=i=>{let o=Array.isArray(i.children)?i.children.map(r):void 0,a=o!==void 0&&o.some((u,l)=>{var c;return u!==((c=i.children)===null||c===void 0?void 0:c[l])}),s=t(i);return a?{...s,children:o}:s};return{...e,commandBars:((n=e.commandBars)!==null&&n!==void 0?n:[]).map(i=>({...i,groups:Array.isArray(i.groups)?i.groups.map(o=>({...o,controls:Array.isArray(o.controls)?o.controls.map(r):o.controls})):i.groups}))}}function Mj(e,t,n){e.forEach(({node:r,index:i})=>{let o=`${t}/${i}`;wa(r.bag)||(0,Ln.optionalGuidId)(r,"id",o,"control-id-invalid",n),(0,Ln.optionalEnum)(r,"type",["Button","FlyoutAnchor","SplitButton"],o,"control-type-invalid",n);let a=r.location;a!==void 0&&(typeof a!="number"||!Number.isInteger(a)||a<0||a>6)&&n.push((0,Ln.issue)(`${o}/location`,"control-location-invalid",`location must be an integer 0-6 when present, got ${JSON.stringify(a)}`)),r.action!==void 0&&r.action!==null&&((0,Ln.isJsonObject)(r.action)?(0,Ln.optionalEnum)(r.action,"type",["javascript"],`${o}/action`,"action-type-invalid",n):n.push((0,Ln.issue)(`${o}/action`,"control-action-must-be-object",`a control action must be a JSON object when present, got ${typeof r.action}`)));let s=(0,Ln.childObjects)(r,"children",o,"control",n);s.length>0&&Mj(s,`${o}/children`,n)})}function L_(e){return{a:Object.entries(e)}}function jwe(e){return Object.fromEntries(e.a)}function Lo(e,t){if(e){for(let[n,r]of e.a)if(n===t)return r}}function M_(e){let t=Lo(e.bag,Lj);return typeof t=="string"?t:""}function Wwe(e,t,n,r){var i,o;let a=[],s=[];for(let u of ob(e))u.type===fn.ButtonType.Group?a.push({id:U_(u.name,r),title:typeof u.grouptitle=="string"?u.grouptitle:"",controls:ob((o=t.get((i=u.appactionid)!==null&&i!==void 0?i:""))!==null&&o!==void 0?o:[]).map(l=>ib(l,t,n,r)),bag:L_(u)}):s.push(ib(u,t,n,r));return s.length>0&&a.unshift({id:eEe(r,n),title:"",controls:s}),a}function Rm(e){let t=e.bag?Lo(e.bag,"appactionid"):void 0;return typeof t=="string"&&t.trim()!==""?t:e.id}function ib(e,t,n,r){var i,o,a,s,u;let l=U_(e.name,r),c={id:l,type:Dm(e.type),label:typeof e.buttonlabeltext=="string"?e.buttonlabeltext:"",command:typeof e.appactionid=="string"?e.appactionid:l,bag:L_(e)},d=xj(e);d&&(c.icon=d);let f=Fj(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!==n&&(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 ob(p))if(g.type===fn.ButtonType.Group){let y=(o=g.appactionid)!==null&&o!==void 0?o:"",b=L_(g);c.flyoutGroupId===void 0&&(c.flyoutGroupId=(a=g.appactionid)!==null&&a!==void 0?a:void 0,c.flyoutGroupBag=b);let E=[];for(let w of ob((u=t.get((s=g.appactionid)!==null&&s!==void 0?s:""))!==null&&u!==void 0?u:[])){let _=ib(w,t,n,r);m.push(_),E.push(Rm(_))}h.push({id:y,bag:b,childIds:E})}else m.push(ib(g,t,n,r));c.children=m,h.length>1&&(c.flyoutGroups=h)}return c}function xj(e){var t;if(!((t=e.IconWebResourceId)===null||t===void 0)&&t.name)return e.IconWebResourceId.name;if(e.fonticon)return e.fonticon.startsWith(k_)?e.fonticon.slice(k_.length)+$_:e.fonticon}function Fj(e){var t;let n=e.onclickeventjavascriptfunctionname;if(typeof n!="string"||!n)return;let r=e.OnClickEventJavaScriptWebResourceId,i=e._onclickeventjavascriptwebresourceid_value,o={type:"javascript",webResourceId:(t=typeof i=="string"?i:r?.webresourceid)!==null&&t!==void 0?t:"",functionName:n};r?.name&&(o.libraryName=r.name);let a=e.onclickeventjavascriptparameters;return typeof a=="string"&&a&&(o.parameters=a),o}function Pj(e){return typeof e.sequence=="number"?e.sequence:typeof e.buttonsequencepriority=="number"?e.buttonsequencepriority:0}function ob(e){return[...e].sort((t,n)=>Pj(t)-Pj(n))}function zwe(e){let t={MainTab:0,ContextualTab:1,HomeTab:2};return[...e].sort((n,r)=>{var i,o;return((i=t[n.location])!==null&&i!==void 0?i:9)-((o=t[r.location])!==null&&o!==void 0?o:9)})}function U_(e,t){if(!e)return"";if(e.indexOf("{!EntityLogicalName}")>=0)return e.replace("{!EntityLogicalName}",t);let n=e.split("!");return n.length===2?n[1]:e}function x_(e){switch(e){case fn.Location.Form:case fn.Location.QuickForm:return"MainTab";case fn.Location.HomePageGrid:case fn.Location.Dashboard:return"HomeTab";default:return"ContextualTab"}}function q_(e){switch(e){case"MainTab":return fn.Location.Form;case"HomeTab":return fn.Location.HomePageGrid;default:return fn.Location.SubGridStandard}}function Dm(e){switch(e){case fn.ButtonType.Dropdown:return"FlyoutAnchor";case fn.ButtonType.Split:return"SplitButton";default:return"Button"}}function B_(e){switch(e){case"FlyoutAnchor":return fn.ButtonType.Dropdown;case"SplitButton":return fn.ButtonType.Split;default:return fn.ButtonType.Standard}}function Uj(e){var t;return e.bag&&e.bag.a.length>0?!0:((t=e.title)!==null&&t!==void 0?t:"").length>0}function qj(e,t){var n,r,i;return((r=(n=e.bag)===null||n===void 0?void 0:n.a.length)!==null&&r!==void 0?r:0)>0?!0:t.has(((i=e.id)!==null&&i!==void 0?i:"").toLowerCase())}function nb(e,t=new Set){var n,r,i,o;let a=[],s=M_(e);for(let u of(n=e.commandBars)!==null&&n!==void 0?n:[]){let l=q_(u.location),c=((r=u.groups)!==null&&r!==void 0?r:[]).flatMap(p=>{var m;return(m=p.controls)!==null&&m!==void 0?m:[]}),d=c.length>0&&c.every(p=>!qj(p,t)),f=0;for(let p of(i=u.groups)!==null&&i!==void 0?i:[]){let m,h=l;if(Uj(p)){let g=Jwe(p,l,void 0,e,s);a.push(g),m=g.appactionid,h=rb(g,p.bag,t,l)}for(let g of(o=p.controls)!==null&&o!==void 0?o:[])Vj(g,l,h,m,e,s,a,d?f:void 0,t),f+=1}}return a}function Bj(e,t){if(!(0,Ln.isJsonObject)(e))return e;let n=e.children,r=n,i=!1;Array.isArray(n)&&(r=n.map(s=>Bj(s,t)),i=r.some((s,u)=>s!==n[u]));let o=!wa(e.bag)&&(typeof e.id!="string"||e.id.trim()==="");if(!o&&!i)return e;let a;if(o){do a=(0,$j.newId)();while(t.has(a));t.add(a)}return{...e,...a!==void 0?{id:a}:{},...i?{children:r}:{}}}function Hwe(e){let t=new Set,n=(o,...a)=>{if((0,Ln.isJsonObject)(o))for(let s of[...a.map(u=>o[u]),wa(o.bag)?Lo(o.bag,"appactionid"):void 0])typeof s=="string"&&s.trim()!==""&&t.add(s.toLowerCase())},r=o=>{(0,Ln.isJsonObject)(o)&&(n(o,"id","flyoutGroupId"),n({bag:o.flyoutGroupBag}),(Array.isArray(o.flyoutGroups)?o.flyoutGroups:[]).forEach(a=>n(a,"id")),(Array.isArray(o.children)?o.children:[]).forEach(r))},i=e.commandBars;return(Array.isArray(i)?i:[]).forEach(o=>{let a=(0,Ln.isJsonObject)(o)?o.groups:void 0;(Array.isArray(a)?a:[]).forEach(s=>{n(s,"id");let u=(0,Ln.isJsonObject)(s)?s.controls:void 0;(Array.isArray(u)?u:[]).forEach(r)})}),t}function Vj(e,t,n,r,i,o,a,s,u=new Set){var l,c;let d=Kwe(e,n==="read"?t:n,r,i,o,s);n==="read"&&e.location===void 0&&Gj(d,u)&&(d.inheritsParentLocation=!0),a.push(d);let f=rb(d,e.bag,u,(l=e.location)!==null&&l!==void 0?l:n),p=(c=e.children)!==null&&c!==void 0?c:[];if(p.length===0&&!(e.flyoutGroups&&e.flyoutGroups.length>0))return;let m=p.every(w=>!qj(w,u)),h=(w,_,I,T)=>{Vj(w,t,I,_,i,o,a,m?T:void 0,u)},g=e.flyoutGroups;if(g&&g.length>0){let w=new Map(p.map(N=>[Rm(N),N])),_=new Set,I=0,T,O=f;for(let[N,S]of g.entries()){let R=S.id||(N===0?R_(d.appactionid):(0,F_.deterministicId)("flyout-group",`${d.appactionid}#${N}`)),x=Rj(R,f,t,d.appactionid,i,o,S.bag,u);a.push(x);let G=rb(x,S.bag,u,f),U=x.appactionid;T===void 0&&(T=U,O=G);for(let M of S.childIds){let q=w.get(M);!q||_.has(M)||(_.add(M),h(q,U,G,I),I+=1)}}let v=T??R_(d.appactionid);for(let N of p){let S=Rm(N);_.has(S)||(_.add(S),h(N,v,O,I),I+=1)}return}let y=e.flyoutGroupId||R_(d.appactionid),b=Rj(y,f,t,d.appactionid,i,o,e.flyoutGroupBag,u);a.push(b);let E=rb(b,e.flyoutGroupBag,u,f);for(let[w,_]of p.entries())h(_,y,E,w)}function Gj(e,t){return!e.exists&&!t.has(e.appactionid.toLowerCase())}function rb(e,t,n,r){if(e.exists){let i=Lo(t,"location");return(0,Vd.isStorableLocation)(i)?i:"read"}return n.has(e.appactionid.toLowerCase())?"read":r}function Kwe(e,t,n,r,i,o){let a=V_(e,t,n,r,i),s=a.row;o!==void 0&&typeof s.sequence!="number"&&(s.sequence=o);let u=xj(s);return e.location!==void 0&&(s.location=e.location),s.type=B_(e.type),s.buttonlabeltext=e.label,Qwe(s,e.icon,u),Zwe(s,e.action),Xwe(s),e.hidden!==void 0&&(s.hidden=e.hidden),e.disabled!==void 0&&(s.isdisabled=e.disabled),{...a,row:s}}function Jwe(e,t,n,r,i){let o=V_(e,t,n,r,i);return o.row.type=fn.ButtonType.Group,o.row.grouptitle=e.title,o}function Rj(e,t,n,r,i,o,a,s){let u=V_({id:e,bag:a},t==="read"?n:t,r,i,o);t==="read"&&Gj(u,s)&&(u.inheritsParentLocation=!0);let l=u.row;return l["[email protected]"]=`/appactions(${(0,Fl.normalizeGuid)(r,"Command flyout group id")})`,l.type=fn.ButtonType.Group,l.grouptitle===void 0&&(l.grouptitle=""),l.isgrouptitlehidden===void 0&&(l.isgrouptitlehidden=!0),u}function V_(e,t,n,r,i){let o,a,s,u;if(e.bag&&e.bag.a.length>0){o=jwe(e.bag),a=!0;let l=Lo(e.bag,"@odata.etag");s=typeof l=="string"?l:null;let c=Lo(e.bag,"appactionid");u=typeof c=="string"&&c?c:e.id}else{if(typeof e.id!="string"||e.id.trim()==="")throw new Gd.InvalidArgumentError(`Cannot serialize command '${r.entityLogicalName}': a new control has no id. Its primary key is minted once, before the first push, by normalize() \u2014 serialize the normalized artifact.`);u=e.id,o=Ywe(u,t,r,i),a=!1,s=null}return n?o["[email protected]"]=`/appactions(${(0,Fl.normalizeGuid)(n,"Command parent appaction id")})`:a&&typeof o._parentappactionid_value=="string"&&o._parentappactionid_value&&o.type!==fn.ButtonType.Group&&(o["[email protected]"]=null),delete o._parentappactionid_value,{appactionid:u,exists:a,etag:s,row:o}}function Ywe(e,t,n,r){let i={appactionid:e,name:`${e}!${e.replace(/-/g,"").slice(0,32)}`,uniquename:"",location:t,context:fn.Context.Entity,contextvalue:n.entityLogicalName,scope:fn.Scope.Entity};return r&&(i["[email protected]"]=`/entities(${(0,Fl.normalizeGuid)(r,"Command context entity metadata id")})`),i}function Qwe(e,t,n){if(t===n){let r=e._iconwebresourceid_value;typeof r=="string"&&r&&!e.fonticon&&(e["[email protected]"]=`/webresourceset(${(0,Fl.normalizeGuid)(r,"Command icon web resource id")})`);return}if(t===void 0){e.fonticon="",e.IconWebResourceId=null;return}e.fonticon=t.toLowerCase().endsWith($_)?k_+t.slice(0,t.length-$_.length):t,e.IconWebResourceId=null}function Xwe(e){let t=(r,i)=>{let o=e[r];if(typeof o!="string"||o.length===0||e[`${i}@odata.bind`]!==void 0)return;let a=(0,Fl.normalizeGuid)(o,`Command ${i}`);e[`${i}@odata.bind`]=`/canvasapps(${a})`};e.onclickeventtype===Bwe&&t("_onclickeventformulacomponentlibraryid_value","OnClickEventFormulaComponentLibraryId");let n=e.visibilitytype;(!n||n===Vwe)&&t("_visibilityformulacomponentlibraryid_value","VisibilityFormulaComponentLibraryId")}function Zwe(e,t){if(!(!t||t.type!=="javascript")){if(e.onclickeventtype=qwe,t.webResourceId){let n=(0,Fl.normalizeGuid)(t.webResourceId,"Command action web resource id");e["[email protected]"]=`/webresourceset(${n})`}e.onclickeventjavascriptfunctionname=t.functionName,t.parameters!==void 0&&(e.onclickeventjavascriptparameters=t.parameters)}}function R_(e){return(0,F_.deterministicId)("flyout-group",e)}function eEe(e,t){return(0,F_.deterministicId)("loose-group",`${e}|${t}`)}function ab(e){var t,n,r;let i=[],o=a=>{let s=wa(a.bag)?Lo(a.bag,"appactionid"):void 0;return typeof s=="string"&&s?s:a.id};for(let a of(t=e.commandBars)!==null&&t!==void 0?t:[]){let s=q_(a.location);for(let u of(n=a.groups)!==null&&n!==void 0?n:[]){Uj(u)&&i.push({rowId:o(u),bag:wa(u.bag)?u.bag:void 0,kind:"group",bar:a.location,location:s,type:fn.ButtonType.Group,disabled:void 0});let l=c=>{var d,f;i.push({rowId:o(c),bag:wa(c.bag)?c.bag:void 0,kind:"control",bar:a.location,location:(d=c.location)!==null&&d!==void 0?d:s,type:B_(c.type),disabled:c.disabled}),((f=c.children)!==null&&f!==void 0?f:[]).forEach(l)};((r=u.controls)!==null&&r!==void 0?r:[]).forEach(l)}}return i}function tEe(e,t,n){var r,i;let o=e.entityLogicalName,a=new Map,s=new Map,u=new Map((t?ab(t):[]).map(f=>[f.rowId,f])),l=f=>new Map(nb(f).map(p=>[p.appactionid,p.row.location])),c=t?l(t):new Map,d;for(let f of ab(e)){if(f.bag){let h=Lo(f.bag,"location");if((0,Vd.isStorableLocation)(h)){if(f.kind==="group"&&x_(h)!==f.bar)throw kj(o,f.rowId,x_(h),f.bar,"stored");if(f.kind==="control"&&f.location!==h)throw tb(o,f.rowId,"Location",String(h),String(f.location),"stored")}let g=Lo(f.bag,"type");if(f.kind==="control"&&typeof g=="number"){let b=Dm(g);if(B_(b)!==f.type)throw tb(o,f.rowId,"type",b,Dm(f.type),"stored")}let y=Lo(f.bag,"isdisabled");if(f.kind==="control"){let b=n.has(f.rowId)?u.get(f.rowId):void 0,E=b?.kind==="control"&&b.bag?Lo(b.bag,"isdisabled"):y;f.disabled!==void 0&&(typeof E!="boolean"||f.disabled!==E)&&a.set(f.rowId,f.disabled);let w=(r=f.disabled)!==null&&r!==void 0?r:typeof E=="boolean"?E:void 0;w!==void 0&&w!==y&&s.set(f.rowId,w)}continue}let p=n.has(f.rowId)?u.get(f.rowId):void 0;if(!p||p.kind!==f.kind)continue;if(f.kind==="group"&&p.bar!==f.bar)throw kj(o,f.rowId,p.bar,f.bar,"pushed");if(f.kind==="control"){d=d??l(e);let h=c.get(f.rowId),g=d.get(f.rowId);if((0,Vd.isStorableLocation)(h)&&(0,Vd.isStorableLocation)(g)&&h!==g)throw tb(o,f.rowId,"Location",String(h),String(g),"pushed")}if(f.kind==="control"&&p.type!==f.type)throw tb(o,f.rowId,"type",Dm(p.type),Dm(f.type),"pushed");let m=(i=p.disabled)!==null&&i!==void 0?i:!1;f.kind==="control"&&f.disabled!==void 0&&f.disabled!==m&&a.set(f.rowId,f.disabled)}return{sentDisabled:a,disabledAfter:s}}function nEe(e,t,n){var r;let i={};if(!t)return i;let o=new Map(ab(t).map(a=>[a.rowId,a]));for(let a of ab(e)){let s=n.has(a.rowId)?(r=o.get(a.rowId))===null||r===void 0?void 0:r.disabled:void 0;a.kind==="control"&&!a.bag&&a.disabled===void 0&&typeof s=="boolean"&&(i[a.rowId]=s)}return i}var jj="An existing app action keeps its Location and its type: an update never carries either, and the platform ignores a Location update \u2014 so the push would report a change that did not happen. Nothing was written.";function Wj(e){return e==="stored"?"as stored on the server":"as last pushed \u2014 re-fetch the command to read the stored one"}function tb(e,t,n,r,i,o){return new Gd.SdkError(Gd.COMMAND_IMMUTABLE_COLUMN_CHANGED_CODE,`Refusing to push command '${e}': it would change the ${n} of app action '${t}' from ${r} (${Wj(o)}) to ${i}. ${jj} Set it back to ${r}${n==="Location"?" and keep the control in its bar":""}, or remove the control and add a new one with the ${n} you want.`)}function kj(e,t,n,r,i){return new Gd.SdkError(Gd.COMMAND_IMMUTABLE_COLUMN_CHANGED_CODE,`Refusing to push command '${e}': it would move group '${t}' from the ${n} bar (${Wj(i)}) to the ${r} bar, which is another Location. ${jj} Move it back to the ${n} bar, or remove it and add a new group to the ${r} bar.`)}function zj(e){let t={...e};for(let n of Gwe)delete t[n];return t}function rEe(e){let t=zj(e);for(let n of fn.CannotUpdateAppActionColumns)delete t[n];return t}var iEe={project:(e,t,n)=>new Pm().toArtifact({entityLogicalName:e,entityMetadataId:t,appActions:n}),projectedId:U_,action:e=>Fj(e)};function oEe(){return{adapter:new Pm,api:Vd.commandApi,publish:(e,t,n)=>(0,Tj.publishBoundEntity)(e,n),publishScope:(e,t)=>(0,Tj.boundEntityPublishScope)(t),inspect:(e,t,n)=>(0,Uwe.inspectCommandBar)(e,t,n,iEe)}}jd.commandRegistration=oEe});var Jj=C(km=>{"use strict";Object.defineProperty(km,"__esModule",{value:!0});km.chartApi=void 0;var aEe=Ke(),G_=qi(),zr=pe(),Su=ae(),Kj="savedqueryvisualizationid,name,description,primaryentitytypecode,datadescription,presentationdescription,charttype,type,isdefault",sEe="savedqueryvisualizationid,name,primaryentitytypecode,charttype,isdefault";km.chartApi={async get(e,t){let n=(0,Su.normalizeGuid)(t,"id"),r=await(0,zr.readRowEtag)(e,"savedqueryvisualizations","savedqueryvisualizationid",n),i=`/savedqueryvisualizations(${n})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,Su.odataQuery)([["$select",Kj]]);return{raw:(0,zr.ensureSuccess)(await e.get(i),e.apiUrl(i)).body,etag:r}},async readContentThenToken(e,t){let n=(0,Su.normalizeGuid)(t,"id"),r=`/savedqueryvisualizations(${n})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,Su.odataQuery)([["$select",Kj]]),i=(0,zr.ensureSuccess)(await e.get(r),e.apiUrl(r)),o=await(0,zr.readRowEtag)(e,"savedqueryvisualizations","savedqueryvisualizationid",n);return{raw:i.body,etag:o}},async list(e,t){let n=`/savedqueryvisualizations${(0,Su.odataQuery)([["$select",sEe],["$filter",t?.entityLogicalName?`primaryentitytypecode eq '${(0,Su.odataLiteral)(t.entityLogicalName)}'`:void 0]])}`;return(await(0,aEe.collectPages)(e,n,"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,n,r=void 0){let i=t,o=(0,zr.echoWrite)("savedqueryvisualizationid"),a=`/savedqueryvisualizations${o.query}`;if(r){let u=n?(0,Su.normalizeGuid)(n,"savedqueryvisualizationid"):void 0;return r.reached({effects:[{componentName:"SavedQueryVisualization",componentId:u,identity:"known",operation:"create"}],attemptsWrite:!0},u?()=>(0,G_.existsByKey)(e,r,{collection:"/savedqueryvisualizations",key:"savedqueryvisualizationid",id:u,componentName:"SavedQueryVisualization"}):void 0)}let s=(0,zr.ensureSuccess)(await e.post(a,(0,zr.withClientMintedId)({name:i.name,description:i.description,datadescription:i.datadescription,presentationdescription:i.presentationdescription,primaryentitytypecode:i.primaryentitytypecode,charttype:i.charttype,isdefault:i.isdefault},"savedqueryvisualizationid",n),o.options),e.apiUrl(a));return{id:(0,zr.resolveCreatedId)(s,"savedqueryvisualizationid","chart",n),etag:(0,zr.readEtag)(s)}},async update(e,t,n,r,i=void 0,o,a){let s=n,u=(0,Su.normalizeGuid)(t,"id");a&&!(0,zr.isVersionToken)(r)&&a.observe({guard:"ifMatch",componentName:"SavedQueryVisualization",componentId:u,held:r,status:"missingHeld"});let l=(0,zr.echoWrite)("savedqueryvisualizationid",{"If-Match":(0,zr.requireEtag)(r,"chart",u)}),c=`/savedqueryvisualizations(${u})${l.query}`;if(a)return await(0,G_.observeIfMatch)(e,a,{entitySet:"savedqueryvisualizations",idColumn:"savedqueryvisualizationid",id:u,componentName:"SavedQueryVisualization",held:l.options.headers["If-Match"]}),a.reached({effects:[{componentName:"SavedQueryVisualization",componentId:u,identity:"known",operation:"update"}],attemptsWrite:!0});let d=(0,zr.ensureSuccess)(await e.patch(c,{name:s.name,description:s.description,datadescription:s.datadescription,presentationdescription:s.presentationdescription},l.options),e.apiUrl(c));return{id:u,etag:(0,zr.readEtag)(d)}},delete(e,t){return(0,zr.deleteRecord)(e,"savedqueryvisualizations",t)},planPush(e,t,n){return(0,G_.planPushThrough)(km.chartApi,e,t,n)}}});var fW=C(zd=>{"use strict";Object.defineProperty(zd,"__esModule",{value:!0});zd.chartRegistration=zd.ChartAdapter=void 0;var j_=Us(),Yj=Vi(),Ea=ja(),Qj=mo(),uEe=Jj(),W_=Ga(),lEe=ft(),cEe=["Column","StackedColumn","StackedColumn100","Bar","StackedBar","StackedBar100","Area","StackedArea","StackedArea100","Line","Pie","Doughnut","Funnel","Tag"],dEe=new Map(cEe.map(e=>[e.toLowerCase(),e]));function nW(e){var t;return e&&(t=dEe.get(e.toLowerCase()))!==null&&t!==void 0?t:"Column"}function fEe(){return'<Chart Palette="BrightPastel"><Series><Series ChartType="Column" ChartArea="Default" /></Series><ChartAreas><ChartArea Name="Default" /></ChartAreas><Legends><Legend Name="Default" /></Legends></Chart>'}function pEe(e){var t,n;let r=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="${Wd(h.series.attribute)}" aggregate="${Wd(h.series.aggregate)}" />`,s=h=>`<attribute alias="${h.alias}" name="${Wd(h.category.attribute)}" groupby="true"${h.category.dateGrouping?` dategrouping="${Wd(h.category.dateGrouping)}"`:""} />`,u=[],l=new Map,c=(h,g)=>{if(!h){u.push(g);return}let y=l.get(h);y?y.push(g):l.set(h,[g])};i.forEach(h=>c(h.series.relatedEntity,a(h))),o.forEach(h=>c(h.category.relatedEntity,s(h)));let d=[...l.entries()].map(([h,g])=>`<link-entity name="${Wd(h)}">${g.join("")}</link-entity>`).join(""),f=u.join("")+d,p=i.map(h=>`<measurecollection><measure alias="${h.alias}" /></measurecollection>`).join(""),m=(n=(t=o[0])===null||t===void 0?void 0:t.alias)!==null&&n!==void 0?n:"";return`<datadefinition><fetchcollection><fetch mapping="logical" aggregate="true"><entity name="${Wd(r)}">${f}</entity></fetch></fetchcollection><categorycollection><category alias="${m}">${p}</category></categorycollection></datadefinition>`}var sb=class{toArtifact(t){var n,r,i,o,a,s,u;(0,W_.installDomShim)();let l=(n=t.datadescription)!==null&&n!==void 0?n:"",c=(r=t.presentationdescription)!==null&&r!==void 0?r:"",d=(0,Ea.parseXmlRoot)(l,"<datadefinition/>"),f=(0,Ea.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:ub(f),isDefault:(u=t.isdefault)!==null&&u!==void 0?u:!1,series:oW(d),categories:aW(d),presentation:rW(f),dataBag:l?(0,Ea.projectElementBag)(d):void 0,presentationBag:c?(0,Ea.projectElementBag)(f):void 0,rowBag:mEe(t.charttype,t.type)}}fromArtifact(t){(0,W_.installDomShim)();let{datadescription:n,presentationdescription:r}=hEe(t);return{savedqueryvisualizationid:t.id,name:t.name,description:t.description,primaryentitytypecode:t.entityLogicalName,datadescription:n,presentationdescription:r,charttype:Xj(t.rowBag,"charttype"),type:Xj(t.rowBag,"type"),isdefault:t.isDefault}}fromApiResponse(t){return this.toArtifact(t??{})}toApiPayload(t){var n,r,i,o,a,s,u;let l=this.fromArtifact(t);return{name:(n=l.name)!==null&&n!==void 0?n:"",description:(r=l.description)!==null&&r!==void 0?r:"",datadescription:(i=l.datadescription)!==null&&i!==void 0?i:"",presentationdescription:(o=l.presentationdescription)!==null&&o!==void 0?o:"",primaryentitytypecode:(a=l.primaryentitytypecode)!==null&&a!==void 0?a:"",charttype:(s=l.charttype)!==null&&s!==void 0?s:0,isdefault:(u=l.isdefault)!==null&&u!==void 0?u:!1}}createDefault(t){var n,r,i,o,a,s,u;(0,W_.installDomShim)();let l=(n=t.entityLogicalName)!==null&&n!==void 0?n:"";return{id:(r=t.id)!==null&&r!==void 0?r:(0,lEe.newId)(),name:(i=t.name)!==null&&i!==void 0?i:"New Chart",description:(o=t.description)!==null&&o!==void 0?o:"",entityLogicalName:l,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:(u=t.presentation)!==null&&u!==void 0?u:{palette:"BrightPastel",showLegend:!0}}}assignMissingIds(t){return t}validate(t){let n=[],r=t;return(0,Yj.childObjects)(r,"series","","series",n),(0,Yj.childObjects)(r,"categories","","category",n),n}};zd.ChartAdapter=sb;function mEe(e,t){let n=[];return e!==void 0&&n.push(["charttype",String(e)]),t!==void 0&&n.push(["type",String(t)]),n.length>0?{a:n,c:[]}:void 0}function Xj(e,t){if(!e)return;let n=e.a.find(([i])=>i===t);if(!n)return;let r=parseInt(n[1],10);return Number.isNaN(r)?void 0:r}function ub(e){let t=e.getElementsByTagName("Series");for(let n=0;n<t.length;n+=1)if(t[n].getAttribute("ChartType"))return nW(t[n].getAttribute("ChartType"));return"Column"}function rW(e){var t;let n={showLegend:e.getElementsByTagName("Legend").length>0},r=e.getAttribute("Palette");r&&(n.palette=r);let i=e.getElementsByTagName("Title")[0],o=((t=i?.textContent)!==null&&t!==void 0?t:"").trim();return o&&(n.title=o),n}function lb(e){return e.getElementsByTagName("fetch")[0]}function iW(e){let t=new Map;if(!e)return t;let n=e.getElementsByTagName("link-entity");for(let r=0;r<n.length;r+=1){let i=n[r],o=i.getAttribute("name");if(!o)continue;let a=i.getElementsByTagName("attribute");for(let s=0;s<a.length;s+=1){let u=a[s],l=u.getAttribute("alias")||u.getAttribute("name");l&&t.set(l,o)}}return t}function oW(e){let t=lb(e);if(!t)return[];let n=iW(t),r=t.getElementsByTagName("attribute"),i=[];for(let o=0;o<r.length;o+=1){let a=r[o],s=a.getAttribute("aggregate");if(!s)continue;let u=a.getAttribute("name");if(!u)continue;let l={attribute:u,aggregate:s},c=a.getAttribute("charttype");c&&(l.seriesType=nW(c));let d=a.getAttribute("alias");d&&(l.alias=d);let f=d||u,p=n.get(f);p&&(l.relatedEntity=p),i.push(l)}return i}function aW(e){var t;let n=lb(e);if(!n)return[];let r=iW(n),i=n.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 u=s.getAttribute("name");if(!u)continue;let l={attribute:u},c=s.getAttribute("dategrouping");c&&(l.dateGrouping=c);let d=s.getAttribute("alias");d&&(l.alias=d);let f=d||u,p=r.get(f);p&&(l.relatedEntity=p),o.push(l)}return o}function hEe(e){var t,n;let r=(t=e.series)!==null&&t!==void 0?t:[],i=(n=e.categories)!==null&&n!==void 0?n:[];if(!Zj(e.dataBag)||!Zj(e.presentationBag)){let c=pEe({...e,series:r,categories:i});return{datadescription:c,presentationdescription:$Ee(e,c)}}let o=new DOMParser().parseFromString("<root/>","text/xml"),a=eW(e.dataBag,"datadefinition",o),s=eW(e.presentationBag,"Chart",o),u=e.chartType||ub(s),l=oW(a);if(!z_(r,l)){let c=H_(a);gEe(o,a,r);let d=H_(a),f=d.length>0?d:r.map(()=>"");sW(o,s,f,c,u)}return z_(i,aW(a))||yEe(o,a,i),e.chartType&&e.chartType!==ub(s)&&cW(s,e.chartType),e.presentation&&!z_(e.presentation,rW(s))&&dW(s,e.presentation),{datadescription:(0,Ea.serializeNode)(a),presentationdescription:(0,Ea.serializeNode)(s)}}function Zj(e){return!!e&&(e.c.length>0||e.a.length>0)}function sW(e,t,n,r,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=[],u=o.childNodes;for(let d=0;d<u.length;d+=1)u[d].nodeType===1&&u[d].tagName==="Series"&&s.push(u[d]);let l=new Map;r.forEach((d,f)=>{let p=s[f];if(!p)return;let m=l.get(d);m?m.push(p):l.set(d,[p])});let c=n.map(d=>{let f=l.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 H_(e){let t=[],n=e.getElementsByTagName("measure");for(let r=0;r<n.length;r+=1)t.push(n[r].getAttribute("alias")||"");return t}function eW(e,t,n){let r={n:t,a:(0,j_.mergeAttrs)(e.a,[]),c:(0,j_.spliceChildren)(e.c,[])};return(0,j_.rebuildRaw)(r,(0,Ea.domEngine)(n),null)}function gEe(e,t,n){let r=lb(t),i=r?.getElementsByTagName("entity")[0];!r||!i||uW(e,t,i,SEe(r),n,_Ee,{aliasPrefix:"aggregate_column",addRef:wEe,removeRef:CEe})}function yEe(e,t,n){let r=lb(t),i=r?.getElementsByTagName("entity")[0];!r||!i||uW(e,t,i,NEe(r),n,IEe,{aliasPrefix:"groupby_column",addRef:EEe,removeRef:AEe})}function uW(e,t,n,r,i,o,a){let s=new Map;for(let p of r){let m=p.getAttribute("alias");m&&s.set(m,p)}let u=new Set,l=[],c=(p,m)=>{var h;let g=TEe(n,p),y=m.relatedEntity;(g??void 0)!==(y??void 0)&&((h=p.parentNode)===null||h===void 0||h.removeChild(p),tW(e,n,p,y))};for(let p of i){let m=p.alias?s.get(p.alias):void 0;m&&!u.has(m)?(o(m,p),c(m,p),u.add(m)):l.push(p)}let d=r.filter(p=>!u.has(p)),f=0;for(let p of l)if(f<d.length){let m=d[f];o(m,p),c(m,p),u.add(m),f+=1}else{let m=e.createElement("attribute"),h=p.alias||vEe(t,a.aliasPrefix);m.setAttribute("alias",h),o(m,p),tW(e,n,m,p.relatedEntity),a.addRef(e,t,h)}for(let p of r)if(!u.has(p)){let m=p.getAttribute("alias");m&&a.removeRef(t,m),DEe(p)}}function bEe(e){let t=new Set;for(let n of["attribute","measure","category"]){let r=e.getElementsByTagName(n);for(let i=0;i<r.length;i+=1){let o=r[i].getAttribute("alias");o&&t.add(o)}}return t}function vEe(e,t){let n=bEe(e);if(!n.has(t))return t;for(let r=2;;r+=1){let i=`${t}_${r}`;if(!n.has(i))return i}}function lW(e,t){let n=t.getElementsByTagName("categorycollection")[0];if(n)return n;let r=e.createElement("categorycollection");return t.appendChild(r),r}function wEe(e,t,n){let r=lW(e,t),i=r.getElementsByTagName("category")[0];i||(i=e.createElement("category"),r.appendChild(i));let o=e.createElement("measurecollection"),a=e.createElement("measure");a.setAttribute("alias",n),o.appendChild(a),i.appendChild(o)}function EEe(e,t,n){let r=lW(e,t),i=e.createElement("category");i.setAttribute("alias",n),r.appendChild(i)}function AEe(e,t){let n=e.getElementsByTagName("category");for(let r=0;r<n.length;r+=1)n[r].getAttribute("alias")===t&&n[r].removeAttribute("alias")}function CEe(e,t){var n;let r=e.getElementsByTagName("measure"),i=[];for(let o=0;o<r.length;o+=1)r[o].getAttribute("alias")===t&&i.push(r[o]);for(let o of i){let a=o.parentNode;a?.removeChild(o),a&&a.tagName==="measurecollection"&&!REe(a)&&((n=a.parentNode)===null||n===void 0||n.removeChild(a))}}function SEe(e){let t=[],n=e.getElementsByTagName("attribute");for(let r=0;r<n.length;r+=1)n[r].getAttribute("aggregate")&&t.push(n[r]);return t}function NEe(e){var t;let n=[],r=e.getElementsByTagName("attribute");for(let i=0;i<r.length;i+=1)((t=r[i].getAttribute("groupby"))!==null&&t!==void 0?t:"").toLowerCase()==="true"&&n.push(r[i]);return n}function _Ee(e,t){e.setAttribute("name",t.attribute),e.setAttribute("aggregate",t.aggregate),t.seriesType&&e.setAttribute("charttype",t.seriesType)}function IEe(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 TEe(e,t){let n=t.parentNode;for(;n&&n!==e;){let r=n;if(r.nodeType===1&&r.tagName==="link-entity")return r.getAttribute("name")||void 0;n=r.parentNode}}function tW(e,t,n,r){r?OEe(e,t,r).appendChild(n):t.appendChild(n)}function OEe(e,t,n){let r=t.getElementsByTagName("link-entity");for(let o=0;o<r.length;o+=1)if(r[o].getAttribute("name")===n)return r[o];let i=e.createElement("link-entity");return i.setAttribute("name",n),t.appendChild(i),i}function DEe(e){let t=e.parentNode;if(t&&(t.removeChild(e),t.tagName==="link-entity"&&!PEe(t))){let n=t.parentNode;n&&n.removeChild(t)}}function PEe(e){let t=e.childNodes;for(let n=0;n<t.length;n+=1){let r=t[n];if(r.nodeType===1){let i=r.tagName;if(i==="attribute"||i==="link-entity")return!0}}return!1}function REe(e){let t=e.childNodes;for(let n=0;n<t.length;n+=1)if(t[n].nodeType===1)return!0;return!1}function cW(e,t){let n=e.getElementsByTagName("Series"),r=!1;for(let i=0;i<n.length;i+=1)n[i].getAttribute("ChartType")&&(n[i].setAttribute("ChartType",t),r=!0);if(!r){for(let i=0;i<n.length;i+=1)if(!kEe(n[i])){n[i].setAttribute("ChartType",t);return}}}function kEe(e){let t=e.childNodes;for(let n=0;n<t.length;n+=1){let r=t[n];if(r.nodeType===1&&r.tagName==="Series")return!0}return!1}function dW(e,t){var n;let r=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=r.createElement("Legends"),e.appendChild(o));let a=r.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 u=0;u<s.length;u+=1)a.push(s[u]);for(let u of a)(n=u.parentNode)===null||n===void 0||n.removeChild(u)}}if(t.title!==void 0){let i=e.getElementsByTagName("Title")[0];i&&(i.textContent=t.title)}}function $Ee(e,t){let n=(0,Ea.parseXmlRoot)(fEe(),"<Chart/>"),r=e.chartType||ub(n);cW(n,r),e.presentation&&dW(n,e.presentation);let i=H_((0,Ea.parseXmlRoot)(t,"<datadefinition/>"));return i.length>0&&sW(n.ownerDocument,n,i,i.slice(0,1),r),(0,Ea.serializeNode)(n)}function z_(e,t){return JSON.stringify(e)===JSON.stringify(t)}function Wd(e){return String(e??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function LEe(){return{adapter:new sb,api:uEe.chartApi,publish:(e,t,n)=>(0,Qj.publishBoundEntity)(e,n),publishScope:(e,t)=>(0,Qj.boundEntityPublishScope)(t),rebaselineAfterPublish:"bracket"}}zd.chartRegistration=LEe});var K_=C(Aa=>{"use strict";Object.defineProperty(Aa,"__esModule",{value:!0});Aa.dashboardApi=Aa.unpublishedDashboardPath=Aa.dashboardEntity=void 0;var MEe=Ke(),pW=qi(),Nu=pe(),Ul=ae(),xEe=oE(),mW=Sc();function hW(e){return e&&e.toLowerCase()!=="none"?e:void 0}Aa.dashboardEntity=hW;var gW="formid,name,description,formxml,type,objecttypecode,istabletenabled,iscustomizable,componentstate,versionnumber",FEe={select:gW,required:["name","type","objecttypecode","istabletenabled"]},UEe="formid,name,type,objecttypecode",qEe=0,BEe=10;function yW(e){return`/systemforms(${e})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,Ul.odataQuery)([["$select",gW]])}Aa.unpublishedDashboardPath=yW;Aa.dashboardApi={async get(e,t){let n=(0,Ul.normalizeGuid)(t,"id"),r=yW(n),i=(0,Nu.ensureSuccess)(await e.get(r),e.apiUrl(r));return(0,mW.assertSystemFormRecordKind)(i.body,n,"dashboard","fetch"),{raw:i.body,etag:(0,Nu.readEtag)(i)}},async list(e,t){let n=[`(type eq ${qEe} or type eq ${BEe})`];t?.entityLogicalName&&n.push(`objecttypecode eq '${(0,Ul.odataLiteral)(t.entityLogicalName)}'`);let r=`/systemforms${(0,Ul.odataQuery)([["$select",UEe],["$filter",n.join(" and ")]])}`;return(await(0,MEe.collectPages)(e,r,"listArtifacts('dashboard')")).map(o=>{var a,s;let u=hW(o.objecttypecode);return{type:"dashboard",id:(a=o.formid)!==null&&a!==void 0?a:"",name:(s=o.name)!==null&&s!==void 0?s:"",...u?{entityLogicalName:u}:{},isDirty:!1}})},async create(e,t,n,r=void 0){let i=t,o=(0,Nu.echoWrite)("formid"),a=`/systemforms${o.query}`,s={name:i.name,description:i.description,formxml:i.formxml,istabletenabled:i.istabletenabled,type:i.type};if(i.objecttypecode&&(s.objecttypecode=i.objecttypecode),r){let l=n?(0,Ul.normalizeGuid)(n,"formid"):void 0;return r.reached({effects:[{componentName:"SystemForm",componentId:l,identity:"known",operation:"create"}],attemptsWrite:!0},l?()=>(0,pW.existsByKey)(e,r,{collection:"/systemforms",key:"formid",id:l,componentName:"SystemForm"}):void 0)}let u=(0,Nu.ensureSuccess)(await e.post(a,(0,Nu.withClientMintedId)(s,"formid",n),o.options),e.apiUrl(a));return{id:(0,Nu.resolveCreatedId)(u,"formid","dashboard",n),etag:(0,Nu.readEtag)(u)}},async update(e,t,n,r,i=void 0,o,a){let s=n;return(0,xEe.patchSystemForm)(e,(0,Ul.normalizeGuid)(t,"id"),"dashboard",{name:s.name,description:s.description,formxml:s.formxml,istabletenabled:s.istabletenabled},r,FEe,a)},readContentThenToken(e,t){return Aa.dashboardApi.get(e,t)},planPush(e,t,n){return(0,pW.planPushThrough)(Aa.dashboardApi,e,t,n)},async delete(e,t){let n=(0,Ul.normalizeGuid)(t,"id");return await(0,mW.assertSystemFormKind)(e,n,"dashboard"),(0,Nu.deleteRecord)(e,"systemforms",n)}}});var NW=C(Hd=>{"use strict";Object.defineProperty(Hd,"__esModule",{value:!0});Hd.inspectDashboard=Hd.validateDashboardInspectOptions=void 0;var AW=ja(),VEe=vy(),bs=Y(),GEe=Ga(),jEe=Eu(),bW=Rs(),CW=pe(),J_=ae(),WEe=K_(),zEe=vE(),vW=Sc(),vs="inspectArtifact('dashboard')",HEe="0x80040217",KEe=new Set([0,10]),JEe=20;function ws(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function wW(e){return ws(e)&&Array.isArray(e.a)&&e.a.every(t=>Array.isArray(t)&&t.length===2&&typeof t[0]=="string"&&typeof t[1]=="string")&&(e.c===void 0||Array.isArray(e.c))}function Y_(e){return e.replace(/[{}]/g,"").toLowerCase()}function SW(e,t){let n=(0,J_.normalizeGuid)(String(e??""),`${vs} id`);if(t===void 0)return{normalizedId:n};if(!ws(t))throw new bs.InvalidArgumentError(`${vs}: options must be an object when given.`);let r=Object.keys(t).find(a=>a!=="expected");if(r!==void 0)throw new bs.InvalidArgumentError(`${vs}: '${r}' is not a dashboard inspection option (only 'expected'${r==="find"||r==="appModuleId"?`; '${r}' is the command inspection's`:""}).`);let i=t.expected;if(i===void 0)return{normalizedId:n};if(!ws(i)||typeof i.id!="string"||!Array.isArray(i.components))throw new bs.InvalidArgumentError(`${vs}: expected must be a dashboard artifact (getArtifact before the push).`);if((0,J_.normalizeGuid)(i.id,`${vs} expected.id`)!==n)throw new bs.InvalidArgumentError(`${vs}: expected.id '${i.id}' is not the inspected dashboard '${n}' \u2014 a witness compares a row only with the artifact pushed to it.`);if(!wW(i.bag))throw new bs.InvalidArgumentError(`${vs}: expected.bag must be the dashboard's hybrid bag ({ a: [...], c: [...] }).`);i.components.forEach((a,s)=>{let u=`${vs}: expected.components[${s}]`;if(!ws(a))throw new bs.InvalidArgumentError(`${u} must be a dashboard component object.`);if(a.id!==void 0&&typeof a.id!="string")throw new bs.InvalidArgumentError(`${u}.id must be the control id (text) when given.`);if(a.bag!==void 0&&!wW(a.bag))throw new bs.InvalidArgumentError(`${u}.bag must be a hybrid bag ({ a: [...], c: [...] }) when given.`)});let o=new Set;for(let a of i.components)if(typeof a.id=="string"&&a.id!==""){let s=Y_(a.id);if(o.has(s))throw new bs.InvalidArgumentError(`${vs}: expected holds control id '${a.id}' twice, so its tiles cannot be paired with the row's.`);o.add(s)}return{normalizedId:n,expected:i}}Hd.validateDashboardInspectOptions=SW;function YEe(e){var t;let n=ws(e)?(t=e.error)!==null&&t!==void 0?t:e.Error:void 0,r=ws(n)?n.code:void 0;return typeof r=="string"?r:void 0}function QEe(e){var t;let n=ws(e)?(t=e.error)!==null&&t!==void 0?t:e.Error:void 0,r=ws(n)?n.message:void 0;return typeof r=="string"?r:void 0}async function XEe(e,t,n,r,i){var o;let{normalizedId:a,expected:s}=SW(t,n),u;try{u=await e.get((0,WEe.unpublishedDashboardPath)(a))}catch(g){return EW(a,"unreadable",{reasonCode:"READ_FAILED",reason:`The row could not be read: ${g instanceof Error?g.message:String(g)}`})}let l=(0,CW.nowIso)(),c=(g,y={})=>EW(a,g,y,l),d=YEe(u.body);if(u.status===404&&d?.toLowerCase()===HEe)return c("missing");if(u.status<200||u.status>=300)return c("unreadable",{reasonCode:"READ_FAILED",reason:`HTTP ${u.status}${d?` ${d}`:""}: ${(o=QEe(u.body))!==null&&o!==void 0?o:"no message"}`});let f=u.body,p=ZEe(f,a);if(p)return c(p.observation,{reasonCode:p.reasonCode,reason:p.reason});let m;try{m=r.fromApiResponse(f)}catch(g){return c("unreadable",{reasonCode:"SCHEMA",reason:`The row cannot be projected: ${g instanceof Error?g.message:String(g)}`})}if(!s)return c("present",{artifact:m});if(s.dashboardType==="Interactive")return c("unreadable",{reasonCode:"COMPARISON_NOT_ESTABLISHED",reason:"An Interactive dashboard is not compared: its stored form was never measured against what was sent."});if(s.components.some(g=>typeof g.name!="string"||g.name===""))return c("unreadable",{reasonCode:"COMPARISON_NOT_ESTABLISHED",reason:"A tile with an empty name is completed by the platform; its stored label cannot be checked."});let h;try{h=await(0,zEe.readProvisionedLanguages)(e)}catch(g){return c("unreadable",{reasonCode:"LANGUAGES_UNREADABLE",reason:`The org's provisioned languages could not be read: ${g instanceof Error?g.message:String(g)}`})}if(h.length!==1||h[0]!==i)return c("unreadable",{reasonCode:"COMPARISON_NOT_ESTABLISHED",reason:`The org provisions ${h.join(", ")}; a comparison is established only for one language that is the authoring language (${i}).`});try{let g=eAe(s,String(f.formxml));if(typeof g=="string")return c("unreadable",{reasonCode:"PAIRING",reason:g});(0,GEe.installDomShim)();let y=r.toApiPayload(g),b=String(f.formxml),E=(0,VEe.completeLabelsAsStored)(y.formxml,b,i,{emptyInsertionsOnly:!0}),w=r.fromApiResponse({...f,...y,formxml:E});if((0,bW.deepEqual)(w,m))return c("matching",{artifact:m});let _=(0,bW.deepDiff)(w,m).map(I=>I.pointer).slice(0,JEe);return c("conflicting",{reasonCode:"CONTENT",artifact:m,differences:_})}catch(g){return c("unreadable",{reasonCode:"COMPARISON_NOT_ESTABLISHED",reason:`The comparison could not be made: ${g instanceof Error?g.message:String(g)}`})}}Hd.inspectDashboard=XEe;function EW(e,t,n,r=(0,CW.nowIso)()){return{type:"dashboard",id:e,observedAt:r,observation:t,...n}}function ZEe(e,t){let n=o=>({observation:"unreadable",reasonCode:"SCHEMA",reason:o});if(!ws(e))return n("The answer is not a row.");let r;try{r=typeof e.formid=="string"?(0,J_.normalizeGuid)(e.formid,"formid"):void 0}catch{r=void 0}if(r!==t)return{observation:"unreadable",reasonCode:"IDENTITY_MISMATCH",reason:`The row answered with formid ${JSON.stringify(e.formid)}, not ${t}.`};let i=(0,vW.decodeCode)(e.type);if(!KEe.has(i))return(0,vW.isKnownSystemFormType)(i)?{observation:"conflicting",reasonCode:"KIND",reason:`The row is a systemform of type ${i}, not a dashboard.`}:n(`The row's type ${JSON.stringify(e.type)} is not a known systemform type.`);if(typeof e.name!="string")return n("The row has no name.");if(typeof e.istabletenabled!="boolean")return n("The row has no istabletenabled flag.");if(typeof e.objecttypecode!="string")return n("The row has no objecttypecode.");if(e.description!==void 0&&e.description!==null&&typeof e.description!="string")return n("The row has a description that is not text.");if(typeof e.formxml!="string"||e.formxml.trim()==="")return n("The row has no formxml.");try{let o=(0,AW.parseXmlRoot)(e.formxml,"<form/>");if(o.nodeName!=="form")return n(`The row's formxml root is <${o.nodeName}>, not <form>.`)}catch(o){return n(`The row's formxml cannot be parsed: ${o instanceof Error?o.message:String(o)}`)}}function eAe(e,t){var n,r,i,o,a,s,u,l,c,d,f,p;let m=new Map,h=(0,AW.parseXmlRoot)(t,"<form/>"),g=Array.from(h.getElementsByTagName("cell"));for(let b of g){let E=(n=b.getAttribute("id"))!==null&&n!==void 0?n:"";for(let w of Array.from(b.childNodes).filter(_=>_.nodeType===1&&_.nodeName==="control")){let _=Y_((r=w.getAttribute("id"))!==null&&r!==void 0?r:"");m.set(_,[...(i=m.get(_))!==null&&i!==void 0?i:[],E])}}let y=(0,jEe.cloneJson)(e);for(let b of y.components){if(((s=(a=(o=b.bag)===null||o===void 0?void 0:o.a)===null||a===void 0?void 0:a.find(I=>I[0]==="id"))===null||s===void 0?void 0:s[1])!==void 0)continue;let w=typeof b.id=="string"?Y_(b.id):"",_=w?(u=m.get(w))!==null&&u!==void 0?u:[]:[];if(_.length!==1||_[0]==="")return`Tile '${(l=b.id)!==null&&l!==void 0?l:""}' cannot be paired with a stored cell: ${_.length===0?"no stored cell holds its control id":`${_.length} stored cells hold its control id`}.`;b.bag={a:[...(d=(c=b.bag)===null||c===void 0?void 0:c.a)!==null&&d!==void 0?d:[],["id",_[0]]],c:(p=(f=b.bag)===null||f===void 0?void 0:f.c)!==null&&p!==void 0?p:[]}}return y}});var FW=C(Ca=>{"use strict";Object.defineProperty(Ca,"__esModule",{value:!0});Ca.dashboardRegistration=Ca.TILE_CLASS_ID=Ca.DashboardAdapter=void 0;var Lm=Us(),so=ja(),Q_=mo(),$m=Vi(),PW=K_(),X_=Ga(),ql=ft(),RW=ae(),kW=fl(),tAe=vy(),nAe=NW(),_W="0",Z_="10",rAe=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"]]),iAe="{3FF9A528-DD50-4ACA-8F10-2E5ED73513AD}",db=class{constructor(t=kW.DEFAULT_LCID){this.lcid=t}toArtifact(t){var n,r,i,o,a;(0,X_.installDomShim)();let s=(n=t.formxml)!==null&&n!==void 0?n:"",u=(0,so.parseXmlRoot)(s,"<form/>");return{id:(r=t.formid)!==null&&r!==void 0?r:"",name:(i=t.name)!==null&&i!==void 0?i:"",description:(o=t.description)!==null&&o!==void 0?o:"",dashboardType:oAe(t.type),entityLogicalName:(a=(0,PW.dashboardEntity)(t.objecttypecode))!==null&&a!==void 0?a:null,enabledForMobile:!!t.istabletenabled,layoutType:aAe(u),components:IW(u,this.lcid),bag:(0,so.projectElementBag)(u)}}fromArtifact(t){var n;return(0,X_.installDomShim)(),{formid:t.id,name:t.name,description:t.description,type:t.dashboardType==="Interactive"?Z_:_W,objecttypecode:(n=t.entityLogicalName)!==null&&n!==void 0?n:"",istabletenabled:t.enabledForMobile,formxml:TW(t,this.lcid)}}fromApiResponse(t){return this.toArtifact(t??{})}completeAsStored(t,n){return(0,tAe.completeRecordAsStored)(t,n,this.lcid)}toApiPayload(t){return{name:t.name,description:t.description,formxml:TW(t,this.lcid),istabletenabled:t.enabledForMobile,type:t.dashboardType==="Interactive"?Z_:_W,objecttypecode:t.entityLogicalName}}createDefault(t){var n,r,i,o,a,s,u,l;(0,X_.installDomShim)();let c=(0,so.parseXmlRoot)(vAe(),"<form/>");return{id:(n=t.id)!==null&&n!==void 0?n:(0,ql.newId)(),name:(r=t.name)!==null&&r!==void 0?r:"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:(u=t.layoutType)!==null&&u!==void 0?u:0,components:(l=t.components)!==null&&l!==void 0?l:IW(c,this.lcid),bag:(0,so.projectElementBag)(c)}}assignMissingIds(t){if(t&&typeof t=="object"&&!Array.isArray(t)&&"position"in t&&!("components"in t)){let n=t;(typeof n.id!="string"||n.id.length===0)&&(n.id=(0,ql.newId)())}return t}validate(t){let n=[],r=(0,$m.childObjects)(t,"components","","component",n),i=new Set;return r.forEach(({node:o,index:a})=>{let s=`/components/${a}`;for(let u of["position","parameters"]){let l=o[u];l!==void 0&&!(0,$m.isJsonObject)(l)&&n.push((0,$m.issue)(`${s}/${u}`,`component-${u}-must-be-object`,`a component ${u} must be a JSON object when present, got ${l===null?"null":typeof l}`))}if((0,$m.isJsonObject)(o.position)){let u=Mm(o.position);i.has(u)?n.push((0,$m.issue)(`${s}/position`,"component-position-collision",`two components occupy the same dashboard position (${u}); move one to a free cell`)):i.add(u)}}),n}};Ca.DashboardAdapter=db;function oAe(e){return String(e??"")===Z_?"Interactive":"Standard"}function aAe(e){let t=e?.getAttribute("formLayout")||e?.getAttribute("layoutType"),n=parseInt(t??"",10);return Number.isNaN(n)?0:n}function Oe(e,t){let n=[],r=e.childNodes;for(let i=0;i<r.length;i+=1){let o=r[i];o.nodeType===1&&o.tagName.toLowerCase()===t&&n.push(o)}return n}function IW(e,t){let n=[];return Oe(e,"tabs").flatMap(i=>Oe(i,"tab")).forEach((i,o)=>{Oe(i,"columns").flatMap(s=>Oe(s,"column")).forEach((s,u)=>{Oe(s,"sections").flatMap(c=>Oe(c,"section")).forEach((c,d)=>{sAe(c,{tabIndex:o,columnIndex:u,sectionIndex:d},n,t)})})}),n}function sAe(e,t,n,r){Oe(e,"rows").flatMap(o=>Oe(o,"row")).forEach((o,a)=>{Oe(o,"cell").forEach((s,u)=>{let l=uAe(s,{...t,rowIndex:a,cellIndex:u},r);l&&n.push(l)})})}function uAe(e,t,n){var r,i;let o=MW((r=e.getAttribute("id"))!==null&&r!==void 0?r:"");if(o.toLowerCase().startsWith("spacer"))return null;let a=Oe(e,"control")[0];if(!a)return null;let s=(i=a.getAttribute("classid"))!==null&&i!==void 0?i:"",u=dAe(a),l=fAe(s,u,a),c=lAe(a);return{id:a.getAttribute("id")||o,type:l,name:LW(e,n),classId:s,position:t,colspan:fb(e,"colspan",1),rowspan:fb(e,"rowspan",1),parameters:u,bag:(0,so.projectElementBag)(e),...c?{icProperties:c}:{}}}function $W(e){let t=e.childNodes;for(let n=0;n<t.length;n+=1){let r=t[n];if(r.nodeType===1&&r.tagName.toLowerCase()==="icproperties")return r}}function lAe(e){let t=$W(e);return t?(0,so.serializeNode)(t):void 0}function cAe(e,t,n){let r=$W(t);if(!n){r&&t.removeChild(r);return}let i=new DOMParser().parseFromString(n,"text/xml").documentElement,o=(0,Lm.rebuildRaw)((0,Lm.rawFromNode)((0,so.nodeLikeFromDom)(i)),(0,so.domEngine)(e),null);r&&(0,so.serializeNode)(r)===(0,so.serializeNode)(o)||(r?t.replaceChild(o,r):t.appendChild(o))}function LW(e,t){var n,r;let i=Oe(e,"labels")[0];if(!i)return"";let o=Oe(i,"label"),a=(n=o.find(s=>s.getAttribute("languagecode")===String(t)))!==null&&n!==void 0?n:o[0];return(r=a?.getAttribute("description"))!==null&&r!==void 0?r:""}function dAe(e){var t;let n={},r=Oe(e,"parameters")[0];if(!r)return n;let i=r.childNodes;for(let o=0;o<i.length;o+=1){let a=i[o];a.nodeType===1&&(n[a.tagName]=((t=a.textContent)!==null&&t!==void 0?t:"").trim())}return n}function fAe(e,t,n){var r;let i=rAe.get(e.toUpperCase());return i?i==="chart"?t.ChartGridMode==="Chart"?"chart":"list":i==="assistant"?((r=n.getAttribute("uniqueid"))!==null&&r!==void 0?r:"").toUpperCase()===iAe?"assistant":t.ChartGridMode!==void 0||n.getAttribute("indicationOfSubgrid")==="true"?t.ChartGridMode==="Chart"?"chart":"list":"unknown":i:"unknown"}function fb(e,t,n){var r;let i=parseInt((r=e.getAttribute(t))!==null&&r!==void 0?r:"",10);return Number.isNaN(i)?n:i}function MW(e){return e.replace(/^\{/,"").replace(/\}$/,"")}function pAe(e,t){let n={n:"form",a:(0,Lm.mergeAttrs)(e.bag.a,[]),c:(0,Lm.spliceChildren)(e.bag.c,[])};return(0,Lm.rebuildRaw)(n,(0,so.domEngine)(t),null)}function TW(e,t){let n=new DOMParser().parseFromString("<root/>","text/xml"),r=pAe(e,n);return gAe(n,r,e.components,t),mAe(n,r,e.components,t),(0,so.serializeNode)(r)}function mAe(e,t,n,r){let i=xW(t);for(let o of n)i.has(Mm(o.position))||hAe(e,t,o,r)}function hAe(e,t,n,r){var i,o,a,s;let u=(o=(i=n.position)===null||i===void 0?void 0:i.sectionIndex)!==null&&o!==void 0?o:0,l=wAe(t,e,u);for(let N of Oe(l,"row"))Oe(N,"cell").some(S=>Oe(S,"control").length>0)||l.removeChild(N);let c=n.classId||Ca.TILE_CLASS_ID[n.type]||Ca.TILE_CLASS_ID.iframe,d=n.rowspan&&n.rowspan>0?n.rowspan:4,f=n.bag&&OW(n.bag,"id")?String(OW(n.bag,"id")):cb((0,ql.newId)()),p=n.id?cb(n.id):cb((0,ql.newId)()),m=l.parentNode,h=Math.max(1,parseInt(m&&m.getAttribute&&m.getAttribute("columns")||"1",10)||1),g=Math.min(Math.max(1,n.colspan&&n.colspan>0?n.colspan:1),h),y=Oe(l,"row"),b=y[y.length-1],E=b?Oe(b,"cell").reduce((N,S)=>N+fb(S,"colspan",1),0):0;(!b||E+g>h)&&(b=e.createElement("row"),l.appendChild(b));let w=e.createElement("cell");w.setAttribute("id",f),w.setAttribute("colspan",String(g)),w.setAttribute("rowspan",String(d)),w.setAttribute("showlabel","true");let _=e.createElement("labels"),I=e.createElement("label");I.setAttribute("description",(a=n.name)!==null&&a!==void 0?a:""),I.setAttribute("languagecode",String(r)),_.appendChild(I),w.appendChild(_);let T=e.createElement("control");T.setAttribute("id",p),T.setAttribute("classid",cb(c));let O=e.createElement("parameters"),v=(s=n.parameters)!==null&&s!==void 0?s:{};for(let N of Object.keys(v)){let S=(0,RW.createSafeXmlElement)(e,N,"dashboard tile parameter");S.textContent=v[N],O.appendChild(S)}T.appendChild(O),w.appendChild(T),b.appendChild(w)}function OW(e,t){if(!e)return;let n=e.a.find(r=>r[0]===t);return n?n[1]:void 0}function gAe(e,t,n,r){var i;let o=xW(t),a=new Set(n.map(s=>Mm(s.position)));for(let s of n){let u=o.get(Mm(s.position));if(!u)continue;let l=Oe(u,"control")[0];l&&(yAe(e,u,s.name,r),bAe(e,l,s.parameters),DW(u,"colspan",s.colspan),DW(u,"rowspan",s.rowspan),s.icProperties!==void 0&&cAe(e,l,s.icProperties))}for(let[s,u]of o)a.has(s)||(i=u.parentNode)===null||i===void 0||i.removeChild(u)}function xW(e){let t=new Map;return Oe(e,"tabs").flatMap(r=>Oe(r,"tab")).forEach((r,i)=>{Oe(r,"columns").flatMap(a=>Oe(a,"column")).forEach((a,s)=>{Oe(a,"sections").flatMap(l=>Oe(l,"section")).forEach((l,c)=>{Oe(l,"rows").flatMap(f=>Oe(f,"row")).forEach((f,p)=>{Oe(f,"cell").forEach((m,h)=>{var g;MW((g=m.getAttribute("id"))!==null&&g!==void 0?g:"").toLowerCase().startsWith("spacer")||Oe(m,"control")[0]&&t.set(Mm({tabIndex:i,columnIndex:s,sectionIndex:c,rowIndex:p,cellIndex:h}),m)})})})})}),t}function Mm(e){let t=e??{};return`${t.tabIndex}.${t.columnIndex}.${t.sectionIndex}.${t.rowIndex}.${t.cellIndex}`}function yAe(e,t,n,r){if(n===LW(t,r))return;let i=Oe(t,"labels")[0];i||(i=e.createElement("labels"),t.appendChild(i));let o=Oe(i,"label").find(a=>a.getAttribute("languagecode")===String(r));o||(o=e.createElement("label"),o.setAttribute("languagecode",String(r)),i.appendChild(o)),o.setAttribute("description",n)}function bAe(e,t,n){var r;if(!n)return;let i=Object.keys(n);if(i.length===0)return;let o=Oe(t,"parameters")[0];o||(o=e.createElement("parameters"),t.appendChild(o));let a=new Map,s=o.childNodes;for(let u=0;u<s.length;u+=1){let l=s[u];l.nodeType===1&&a.set(l.tagName,l)}for(let u of i){let l=n[u],c=a.get(u);if(c)((r=c.textContent)!==null&&r!==void 0?r:"")!==l&&(c.textContent=l);else{let d=(0,RW.createSafeXmlElement)(e,u,"dashboard component parameter");d.textContent=l,o.appendChild(d)}}}function DW(e,t,n){fb(e,t,1)!==n&&e.setAttribute(t,String(n))}function vAe(e=2){let t=`{${(0,ql.newId)()}}`,n=`{${(0,ql.newId)()}}`,r=`{${(0,ql.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="${n}" name="Section 1" showlabel="false" columns="${i}"><rows><row><cell id="${r}" rowspan="12" colspan="${i}" showlabel="true" /></row></rows></section></sections></column></columns></tab></tabs></form>`}Ca.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 cb(e){return`{${e.replace(/[{}]/g,"")}}`}function wAe(e,t,n){var r;let i=Oe(e,"tabs").flatMap(l=>Oe(l,"tab"))[0];if(!i)throw new Error("addDashboardTile: dashboard formxml has no <tab>");let o=Oe(i,"columns").flatMap(l=>Oe(l,"column"))[0];if(!o)throw new Error("addDashboardTile: dashboard formxml has no <column>");let a=Oe(o,"sections").flatMap(l=>Oe(l,"section")),s=(r=a[n])!==null&&r!==void 0?r:a[0];if(!s)throw new Error("addDashboardTile: dashboard formxml has no <section>");let u=Oe(s,"rows")[0];return u||(u=t.createElement("rows"),s.appendChild(u)),u}function EAe(e=kW.DEFAULT_LCID){let t=new db(e);return{adapter:t,api:PW.dashboardApi,languageSensitive:!0,publish:(n,r,i)=>i?.entityLogicalName?(0,Q_.publishBoundEntity)(n,i):(0,Q_.publishDashboardById)(n,r),publishScope:(n,r)=>r?.entityLogicalName?(0,Q_.boundEntityPublishScope)(r):{envelope:"dashboard",targetIds:[n]},rebaselineAfterPublish:"bracket",inspect:(n,r,i)=>(0,nAe.inspectDashboard)(n,r,i,t,e)}}Ca.dashboardRegistration=EAe});var tI=C(Ei=>{"use strict";Object.defineProperty(Ei,"__esModule",{value:!0});Ei.readEveryInOrder=Ei.readInOrder=Ei.plainRead=Ei.resolveReadConcurrency=Ei.MAX_READ_CONCURRENCY=void 0;var UW=Y();Ei.MAX_READ_CONCURRENCY=8;function AAe(e){if(e===void 0)return 1;if(typeof e!="number"||!Number.isInteger(e)||e<1||e>Ei.MAX_READ_CONCURRENCY)throw new UW.InvalidArgumentError(`readConcurrency must be a whole number from 1 to ${Ei.MAX_READ_CONCURRENCY} (got ${typeof e=="string"?`'${e}'`:String(e)})`);return e}Ei.resolveReadConcurrency=AAe;var CAe=e=>({ok:!0,value:e}),eI=e=>({ok:!1,error:e});function SAe(e){let t=(async()=>e())().then(CAe,eI);return{outcome:t,finish:async n=>{await n()},discard:async()=>{await t}}}Ei.plainRead=SAe;async function qW(e,t,n,r,i){if(!Number.isInteger(t)||t<1)throw new UW.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(),u=!1,l=0,c,d=async f=>{if(u)return{refusal:new Error("The read was not started: an earlier read had already failed.")};try{let p=await n(e[f],f),m=p.outcome.catch(eI);return i==="stop"&&m.then(h=>{u=u||!h.ok}),{read:p,outcome:m}}catch(p){return u=u||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 y=s.then(()=>d(g));o.set(g,y),s=y}let p=await o.get(f),m="read"in p?await p.outcome:eI(p.refusal);if(!m.ok&&i==="stop"){c={error:m.error};break}l=f+1,o.delete(f);let h=()=>r(m,e[f],f);"read"in p?await p.read.finish(h):await h()}}finally{u=!0;for(let f=l;f<a;f+=1){let p=await o.get(f);"read"in p&&await p.read.discard().catch(()=>{})}}if(c)throw c.error}function NAe(e,t,n,r){return qW(e,t,n,(i,o,a)=>r(i.value,o,a),"stop")}Ei.readInOrder=NAe;function _Ae(e,t,n,r){return qW(e,t,n,r,"continue")}Ei.readEveryInOrder=_Ae});var iz=C(Bm=>{"use strict";Object.defineProperty(Bm,"__esModule",{value:!0});Bm.genPageApi=void 0;var pb=Ke(),ZW=Zo(),Bl=qi(),Ft=pe(),$e=ae(),xo=ia(),tn=Y(),ez=ft(),BW=tI();function IAe(e){if(ArrayBuffer.isView(e)){let n=e;return new Uint8Array(n.buffer,n.byteOffset,n.byteLength)}if(Object.prototype.toString.call(e)==="[object ArrayBuffer]")return new Uint8Array(e);let t=globalThis;if(t.Buffer&&t.Buffer.isBuffer(e)){let n=e;return new Uint8Array(n.buffer,n.byteOffset,n.byteLength)}}var Mo="uxagentprojects",Gl="uxagentprojectfiles",Um="agentconversationmessages",Kd="uxagentprojectid",cr="uxagentprojectfileid",jl="agentconversationmessageid",xm=`${Kd},name`,TAe=`${cr},filename,filetype`,tz=2e8,nz=200000001,_u={"MSCRM.IncludeUnpublished":"true"},nI={};function Vl(e,t){return{"MSCRM.VersioningChangeset":e,..._u,...t}}async function oI(e,t,n,r){var i;let o=`/${t}(${n})`+(0,$e.odataQuery)([["$select",r]]),a=(0,Ft.ensureSuccess)(await e.get(o,{headers:{..._u}}),e.apiUrl(o));return{row:(i=a.body)!==null&&i!==void 0?i:{},etag:(0,Ft.readEtag)(a)}}async function qm(e,t,n=_u){let r=`/${Gl}(${t})/filecontent/$value`,i=await e.get(r,{headers:{...n}});if(i.status===404)return{status:"unavailable",reason:"missing"};(0,Ft.ensureSuccess)(i,e.apiUrl(r));let o=i.body,a=IAe(o);if(a)return{status:"available",data:(0,xo.bytesToBase64)(a)};if(typeof o=="string")return{status:"available",data:(0,xo.utf8ToBase64)(o)};throw new tn.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 rz(e){let t=e.lastIndexOf("/");return t>=0?e.slice(t+1):e}async function OAe(e,t,n,r,i,o){if(!e.supportsBinaryPatch)throw new tn.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=`/${Gl}(${t})/filecontent`,s=(0,xo.base64ToBytes)(r);(0,$e.assertNoControlChars)(n,"generative-page file name"),(0,Ft.ensureSuccess)(await e.patchRaw(a,s,{headers:Vl(i,{"Content-Type":"application/octet-stream","Content-Length":String(s.byteLength),"x-ms-file-name":rz(n),...o?{"If-Match":"*"}:{}})}),e.apiUrl(a))}async function Fm(e,t,n=_u){let r=`/${Gl}`+(0,$e.odataQuery)([["$select",TAe],["$filter",`_${Kd}_value eq ${t}`]]);return(await(0,pb.collectPages)(e,r,"fetchArtifact('genPage')",void 0,{headers:{...n}})).map(o=>({row:o,etag:typeof o["@odata.etag"]=="string"?o["@odata.etag"]:null}))}async function rI(e,t){let n=`/${Um}`+(0,$e.odataQuery)([["$select",`${jl},message,messagesender,createdon`],["$filter",`_regardingobjectid_value eq ${t}`],["$orderby","createdon asc,versionnumber asc"]]);return(0,pb.collectPages)(e,n,"fetchArtifact('genPage')",void 0,{headers:{..._u}})}async function VW(e,t){var n,r,i;let{row:o,etag:a}=await oI(e,Mo,t,xm),s=new Map;for(let{row:u,etag:l}of await Fm(e,t))s.set((0,$e.normalizeGuid)(String((n=u[cr])!==null&&n!==void 0?n:""),cr),{filename:String((r=u.filename)!==null&&r!==void 0?r:""),filetype:Number(u.filetype),etag:l});return{name:String((i=o.name)!==null&&i!==void 0?i:""),etag:a,rows:s}}function GW(e,t,n){var r,i,o,a,s;let u=[];n||u.push({kind:"createProject",name:t.name});let l=new Set;for(let c of(r=t.files)!==null&&r!==void 0?r:[]){let d=(0,$e.normalizeGuid)(c.id,"file id");l.add(d);let f=n?.rows.get(d);if(c.content.status==="retain"){if(!n)throw new tn.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 tn.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)&&u.push({kind:"renameRow",file:c}):u.push({kind:"createRow",file:c}),c.content.status==="available"&&u.push({kind:"content",file:c,data:c.content.data,existing:f!==void 0}))}for(let c of(i=n?.rows.keys())!==null&&i!==void 0?i:[])l.has(c)||u.push({kind:"deleteRow",fileId:c});(!n||u.length>0||n.name!==t.name||((a=(o=t.messages)===null||o===void 0?void 0:o.length)!==null&&a!==void 0?a:0)>0)&&u.push({kind:"patchProject",name:t.name});for(let c of(s=t.messages)!==null&&s!==void 0?s:[])u.push({kind:"message",turn:c});return u}function aI(e){let t=(0,xo.base64ToUtf8)(e);return(0,xo.utf8ToBase64)(t)===(0,xo.bytesToBase64)((0,xo.base64ToBytes)(e))?t:void 0}function DAe(e,t,n,r){var i,o,a,s,u,l,c,d;let f=t.sender==="user"?{changeSet:r,dataSources:(o=(i=n.messageContext)===null||i===void 0?void 0:i.dataSources)!==null&&o!==void 0?o:[],model:(s=(a=n.messageContext)===null||a===void 0?void 0:a.model)!==null&&s!==void 0?s:"",enabledTools:(l=(u=n.messageContext)===null||u===void 0?void 0:u.enabledTools)!==null&&l!==void 0?l:[],configurableTools:(d=(c=n.messageContext)===null||c===void 0?void 0:c.configurableTools)!==null&&d!==void 0?d:[]}:{changeSet:r};return{...t.id?{[jl]:(0,$e.normalizeGuid)(t.id,"message id")}:{},"[email protected]":`/${Mo}(${e})`,message:t.message,messagecontext:JSON.stringify(f),messagesender:t.sender==="user"?tz:nz}}async function PAe(e,t,n){var r,i,o,a;let s=((r=n.messages)!==null&&r!==void 0?r:[]).map(f=>f.id).filter(f=>typeof f=="string"&&f!=="").map(f=>(0,$e.normalizeGuid)(f,"message id"));if(s.length===0)return n;let u=`/${Um}`+(0,$e.odataQuery)([["$select",`${jl},message,messagesender,_regardingobjectid_value`],["$filter",s.map(f=>`${jl} eq ${f}`).join(" or ")]]),l=await(0,pb.collectPages)(e,u,"pushArtifact('genPage')",void 0,{headers:{..._u}});if(l.length===0)return n;let c=new Map(l.map(f=>{var p;return[String((p=f[jl])!==null&&p!==void 0?p:"").toLowerCase(),f]})),d=[];for(let f of(i=n.messages)!==null&&i!==void 0?i:[]){let p=f.id?c.get((0,$e.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"?tz:nz)&&String((a=p._regardingobjectid_value)!==null&&a!==void 0?a:"").toLowerCase()===t))throw new tn.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{...n,messages:d}}function iI(e,t,n,r){switch(t.kind){case"createProject":return{method:"POST",path:`/${Mo}`,body:(0,Ft.withClientMintedId)({name:t.name},Kd,e),headers:Vl(r)};case"createRow":return{method:"POST",path:`/${Gl}`,body:(0,Ft.withClientMintedId)({filename:t.file.name,filetype:t.file.fileType,[`${Kd}@odata.bind`]:`/${Mo}(${e})`},cr,(0,$e.normalizeGuid)(t.file.id,"file id")),headers:Vl(r)};case"renameRow":return{method:"PATCH",path:`/${Gl}(${(0,$e.normalizeGuid)(t.file.id,"file id")})`,body:{filename:t.file.name,filetype:t.file.fileType},headers:Vl(r,{"If-Match":"*"})};case"content":{let i=aI(t.data);if(i===void 0)throw new tn.SdkError("GENPAGE_CONTENT_NOT_TEXT",`File '${t.file.name}' is not UTF-8 text and cannot ride in a change set.`);return(0,$e.assertNoControlChars)(t.file.name,"generative-page file name"),{method:"PATCH",path:`/${Gl}(${(0,$e.normalizeGuid)(t.file.id,"file id")})/filecontent`,rawBody:i,contentType:"application/octet-stream; charset=utf-8",headers:Vl(r,{"x-ms-file-name":rz(t.file.name),...t.existing?{"If-Match":"*"}:{}})}}case"deleteRow":return{method:"DELETE",path:`/${Gl}(${t.fileId})`,headers:Vl(r,{"If-Match":"*"})};case"patchProject":return{method:"PATCH",path:`/${Mo}(${e})`,body:{name:t.name},headers:Vl(r,{"If-Match":"*"})};case"message":return{method:"POST",path:`/${Um}`,body:DAe(e,t.turn,n,r)};default:{let i=t;throw new tn.SdkError("GENPAGE_WRITE_UNKNOWN",`Unknown generative-page write: ${JSON.stringify(i)}`)}}}function jW(e,t){return e.supportsAtomicBatch&&t.every(n=>n.kind!=="content"||aI(n.data)!==void 0)}async function WW(e,t,n,r,i){await(0,ZW.postChangeSet)(e,n.map(o=>iI(t,o,r,i)),`generative page '${t}' (${n.length} operation(s))`)}async function zW(e,t,n,r,i){var o;let a=[];for(let s of n){if(s.kind==="message"){a.push(s);continue}if(s.kind==="content"){await OAe(e,(0,$e.normalizeGuid)(s.file.id,"file id"),s.file.name,s.data,i,s.existing);continue}let u=iI(t,s,r,i),l={headers:(o=u.headers)!==null&&o!==void 0?o:{}},c=u.method==="POST"?await e.post(u.path,u.body,l):u.method==="PATCH"?await e.patch(u.path,u.body,l):await e.delete(u.path,l);(0,Ft.ensureSuccess)(c,e.apiUrl(u.path))}if(a.length===0)return{warnings:[],turnRecorded:!0};try{let s=a.map(u=>iI(t,u,r,i));if(e.supportsAtomicBatch)await(0,ZW.postChangeSet)(e,s,`the conversation turn of generative page '${t}'`);else for(let u of s)(0,Ft.ensureSuccess)(await e.post(u.path,u.body),e.apiUrl(u.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 HW(e,t,n,r,i,o,a){var s;let u=l=>({id:t,etag:null,memberEtags:{},warnings:[...a,l]});try{let l=await VW(e,t),c=new Map;for(let E of n)(E.kind==="createRow"||E.kind==="renameRow"||E.kind==="content")&&c.set((0,$e.normalizeGuid)(E.file.id,"file id"),E.file);let d=[];l.name!==r.name&&d.push(`the page is named '${l.name}', not '${r.name}'`);for(let[E,w]of c){let _=l.rows.get(E);_&&(_.filename!==w.name||_.filetype!==w.fileType)&&d.push(`file '${w.name}' is stored as '${_.filename}' (type ${_.filetype})`)}for(let E of n){if(E.kind!=="content")continue;let w=await qm(e,(0,$e.normalizeGuid)(E.file.id,"file id")),_=(0,xo.bytesToBase64)((0,xo.base64ToBytes)(E.data));(w.status!=="available"||w.data!==_)&&d.push(w.status==="available"?`file '${E.file.name}' holds ${(0,xo.base64ToBytes)(w.data).byteLength} byte(s) that differ from the ${(0,xo.base64ToBytes)(_).byteLength} written`:`file '${E.file.name}' holds no content`)}let f=new Set(n.filter(E=>E.kind==="content").map(E=>(0,$e.normalizeGuid)(E.file.id,"file id")));for(let[E,w]of c)!f.has(E)&&(await qm(e,E)).status==="available"&&d.push(`file '${w.name}' holds content this push did not write`);if(d.length>0)return u(`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 VW(e,t),m=[...p.rows.keys()],h=p.etag!==l.etag||p.rows.size!==l.rows.size||m.some(E=>{var w,_;return((w=l.rows.get(E))===null||w===void 0?void 0:w.etag)!==((_=p.rows.get(E))===null||_===void 0?void 0:_.etag)}),g=m.length!==i.size||m.some(E=>!i.has(E)),y={},b=[];for(let[E,w]of p.rows){let _=c.has(E)||!o?w.etag:(s=o.get(E))!==null&&s!==void 0?s:null;y[E]=_,_!==w.etag&&b.push(w.filename)}return h||g||!p.etag||Object.values(y).some(E=>!E)?u(`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.`):RAe({id:t,etag:p.etag,memberEtags:y},[...a,...b.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(l){return u(`The generative page was written, but reading it back failed (${l instanceof Error?l.message:String(l)}). The local baseline is unusable: re-fetch the page before editing it \u2014 the next push will refuse rather than overwrite blind.`)}}async function KW(e,t,n,r=e.readConcurrency){var i;let o=(0,$e.normalizeGuid)(t,"id"),{row:a,etag:s}=await oI(e,Mo,o,xm),u=await Fm(e,o),l={},c=[];if(r>1)await(0,BW.readInOrder)(u,r,({row:f})=>{var p;let m=(0,$e.normalizeGuid)(String((p=f[cr])!==null&&p!==void 0?p:""),cr);return(0,BW.plainRead)(async()=>({fileId:m,content:await qm(e,m)}))},({fileId:f,content:p},{row:m,etag:h})=>{l[f]=h,c.push({...m,content:p})});else for(let{row:f,etag:p}of u){let m=(0,$e.normalizeGuid)(String((i=f[cr])!==null&&i!==void 0?i:""),cr);l[m]=p;let h=await qm(e,m);c.push({...f,content:h})}return{raw:n?{project:a,files:c,conversation:await rI(e,o)}:{project:a,files:c},etag:s,memberEtags:l}}Bm.genPageApi={get(e,t,n){return KW(e,t,!0,n?.fileConcurrency)},getForRebaseline(e,t){return KW(e,t,!1)},async getPublished(e,t){var n,r;let i=(0,$e.normalizeGuid)(t,"id"),o=`/${Mo}(${i})`+(0,$e.odataQuery)([["$select",xm]]),a=await e.get(o);if(a.status===404)return null;(0,Ft.ensureSuccess)(a,e.apiUrl(o));let s=(n=a.body)!==null&&n!==void 0?n:{},u={},l=[],c=await Fm(e,i,nI);for(let{row:g,etag:y}of c){let b=(0,$e.normalizeGuid)(String((r=g[cr])!==null&&r!==void 0?r:""),cr);u[b]=y,l.push({...g,content:await qm(e,b,nI)})}let d=g=>g.map(({row:y,etag:b})=>`${String(y[cr])}@${String(b)}`).sort().join("|"),f=()=>new tn.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,Ft.ensureSuccess)(p,e.apiUrl(o));let m=await Fm(e,i,nI);if([(0,Ft.readEtag)(a),(0,Ft.readEtag)(p),...[...c,...m].map(g=>g.etag)].some(g=>!g))throw new tn.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,Ft.readEtag)(p)!==(0,Ft.readEtag)(a)||d(m)!==d(c))throw f();return{raw:{project:s,files:l,conversation:[]},etag:(0,Ft.readEtag)(a),memberEtags:u}},async list(e,t){let n=`/${Mo}`+(0,$e.odataQuery)([["$select",xm]]);return(await(0,pb.collectPages)(e,n,"listArtifacts('genPage')",void 0,{headers:{..._u}})).map(i=>{var o,a;return{type:"genPage",id:String((o=i[Kd])!==null&&o!==void 0?o:""),name:String((a=i.name)!==null&&a!==void 0?a:""),isDirty:!1}})},async create(e,t,n,r=void 0){var i;let o=t,a=n?(0,$e.normalizeGuid)(n,"id"):(0,ez.newId)(),s=GW(a,o,void 0);if(XW(e,s),QW(e,a,o),r)return r.reached({effects:JW(a,s),attemptsWrite:!0},()=>(0,Bl.existsByKey)(e,r,{collection:`/${Mo}`,key:Kd,id:a,componentName:"uxagentproject",headers:{..._u}}));let u=YW(o),l=[],c=!0;jW(e,s)?await WW(e,a,s,o,u):{warnings:l,turnRecorded:c}=await zW(e,a,s,o,u);let d=new Set(((i=o.files)!==null&&i!==void 0?i:[]).map(p=>(0,$e.normalizeGuid)(p.id,"file id"))),f=await HW(e,a,s,o,d,void 0,l);return c?f:{...f,intentPending:!0}},async update(e,t,n,r,i,o=void 0,a){var s,u;let l=n,c=(0,$e.normalizeGuid)(t,"id"),d={componentName:"uxagentproject",componentId:c},f=R=>({componentName:"uxagentprojectfile",componentId:R});if(!Array.isArray(l.files))throw new tn.SdkError("GENPAGE_FILES_REQUIRED",`Refusing to update generative page '${c}': 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 p=await PAe(e,c,l);QW(e,c,p);let m;try{m=await Fm(e,c)}catch(R){throw a?.observe({guard:"membership",...d,status:"readFailed",detail:(0,Bl.failureDetail)(R)}),R}let h;try{h=await oI(e,Mo,c,xm)}catch(R){throw a?.observe({guard:"parentToken",...d,held:r,status:(0,Bl.failedReadStatus)(R),detail:(0,Bl.failureDetail)(R)}),R}let{row:g,etag:y}=h;if(a?.observe({guard:"parentToken",...d,held:r,server:y,status:(0,Bl.compareTokens)(r,y)}),r&&y&&r!==y)throw new tn.SdkError(Ft.VERSION_CONFLICT_CODE,`Generative page '${c}' changed on the server after it was fetched (baseline ${r}, server ${y}) \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(!r||!y)throw new tn.SdkError(Ft.VERSION_CONFLICT_CODE,`Cannot verify generative page '${c}' before writing: ${r?"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 b=new Map(m.map(({row:R})=>{var x,G;return[(0,$e.normalizeGuid)(String((x=R[cr])!==null&&x!==void 0?x:""),cr),{filename:String((G=R.filename)!==null&&G!==void 0?G:""),filetype:Number(R.filetype)}]})),E=new Set(b.keys()),w=new Set(((s=p.files)!==null&&s!==void 0?s:[]).map(R=>(0,$e.normalizeGuid)(R.id,"file id")));if(!i)throw a?.observe({guard:"membership",...d,status:"missingHeld",detail:"no child baseline recorded"}),new tn.SdkError(Ft.VERSION_CONFLICT_CODE,`Cannot verify the files of generative page '${c}' 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 _=new Set(Object.keys(i).map(R=>R.toLowerCase()));for(let R of w)if(!E.has(R)&&_.has(R))throw a?.observe({guard:"membership",...f(R),status:"goneOnServer"}),new tn.SdkError(Ft.VERSION_CONFLICT_CODE,`Generative-page file '${R}' 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 R of E)if(!_.has(R))throw a?.observe({guard:"membership",...f(R),status:"addedOnServer"}),new tn.SdkError(Ft.VERSION_CONFLICT_CODE,`Generative-page file '${R}' 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.`);a?.observe({guard:"membership",...d,status:"equal"});let I=new Map(m.map(({row:R,etag:x})=>{var G;return[(0,$e.normalizeGuid)(String((G=R[cr])!==null&&G!==void 0?G:""),cr),x]}));for(let[R,x]of Object.entries(i)){let G=R.toLowerCase();if(!E.has(G))continue;let U=I.get(G);if(a?.observe({guard:"memberToken",...f(G),held:x,server:U??null,status:(0,Bl.compareTokens)(x,U)}),!x||!U)throw new tn.SdkError(Ft.VERSION_CONFLICT_CODE,`Cannot verify generative-page file '${G}' before writing: ${x?"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(x!==U)throw new tn.SdkError(Ft.VERSION_CONFLICT_CODE,`Generative-page file '${G}' changed on the server after this page was fetched (baseline ${x}, server ${U}) \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 T=GW(c,p,{rows:b,name:String((u=g.name)!==null&&u!==void 0?u:"")});if(XW(e,T),a)return a.reached({effects:JW(c,T),attemptsWrite:T.length>0});if(T.length===0)return{id:c,etag:y,memberEtags:Object.fromEntries(m.map(({row:R,etag:x})=>{var G;return[(0,$e.normalizeGuid)(String((G=R[cr])!==null&&G!==void 0?G:""),cr),x]}))};let O=YW(p),v=[],N=!0;jW(e,T)?await WW(e,c,T,p,O):{warnings:v,turnRecorded:N}=await zW(e,c,T,p,O);let S=await HW(e,c,T,p,w,I,v);return N?S:{...S,intentPending:!0}},planPush(e,t,n){return(0,Bl.planPushThrough)(Bm.genPageApi,e,t,n)},async delete(e,t){var n;let r=(0,$e.normalizeGuid)(t,"id"),i=await rI(e,r);await(0,Ft.deleteRecord)(e,Mo,r);let o=new Set(i.map(u=>{var l;return String((l=u[jl])!==null&&l!==void 0?l:"")}).filter(u=>u!=="")),a=!1;try{for(let u of await rI(e,r)){let l=String((n=u[jl])!==null&&n!==void 0?n:"");l!==""&&o.add(l)}}catch{a=!0}let s=[];for(let u of o)try{await(0,Ft.deleteRecord)(e,Um,u)}catch(l){l instanceof tn.ConnectionError&&l.statusCode===404||s.push(u)}if(s.length>0||a)throw new tn.SdkError("GENPAGE_HISTORY_NOT_DELETED",`Generative page '${r}' 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 ${Um} rows regarding '${r}'.`)}};function JW(e,t){let n=new Map,r=(i,o,a)=>{let s=`${i}:${o}`;n.has(s)||n.set(s,{componentName:i,componentId:o,identity:"known",operation:a})};for(let i of t)i.kind==="createProject"?r("uxagentproject",e,"create"):i.kind==="patchProject"?r("uxagentproject",e,"update"):i.kind==="createRow"?r("uxagentprojectfile",(0,$e.normalizeGuid)(i.file.id,"file id"),"create"):i.kind==="renameRow"?r("uxagentprojectfile",(0,$e.normalizeGuid)(i.file.id,"file id"),"update"):i.kind==="content"?r("uxagentprojectfile",(0,$e.normalizeGuid)(i.file.id,"file id"),i.existing?"update":"create"):i.kind==="deleteRow"&&r("uxagentprojectfile",i.fileId,"delete");return[...n.values()]}function YW(e){var t,n;return((n=(t=e.messages)===null||t===void 0?void 0:t.length)!==null&&n!==void 0?n:0)>0&&e.turnId!==void 0?`uxagentproject_${(0,$e.normalizeGuid)(e.turnId,"newTurn.id")}`:`uxagentproject_${(0,ez.newId)()}`}function RAe(e,t){var n;return t.length===0?e:{...e,warnings:[...(n=e.warnings)!==null&&n!==void 0?n:[],...t]}}function QW(e,t,n){var r,i;if(((i=(r=n.messages)===null||r===void 0?void 0:r.length)!==null&&i!==void 0?i:0)>1&&!e.supportsAtomicBatch)throw new tn.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 XW(e,t){let n=t.filter(i=>i.kind==="content");if(n.length>0&&!e.supportsBinaryPatch&&!e.supportsAtomicBatch)throw new tn.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.some(i=>aI(i.data)===void 0)&&!e.supportsBinaryPatch)throw new tn.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 wz=C(Yd=>{"use strict";Object.defineProperty(Yd,"__esModule",{value:!0});Yd.genPageRegistration=Yd.GenPageAdapter=void 0;var kAe=iz(),$Ae=mo(),lt=Vi(),bb=ft(),vb=ia(),mz=ae(),Iu=Y(),uI=gC(),sI=yE(),Tu=2e8,hz=200000001,As={source:{name:"src/pages/page.tsx",fileType:Tu},output:{name:"src/pages/page.compiled",fileType:hz},config:{name:"config.json",fileType:Tu},prompt:{name:"firstPrompt.json",fileType:Tu}},gz=Object.keys(As),LAe=["dataSources","model","connectorBindings","actionBindings"],MAe=["userMessage","agentMessage"];function lI(e){if(typeof e!="string")throw new Iu.InvalidArgumentError(`newTurn.id must be a valid GUID (got ${JSON.stringify(e)})`);return(0,mz.normalizeGuid)(e,"newTurn.id")}function xAe(e){try{return lI(e)}catch{return}}var FAe={source:"6f1c2a4e9b3d47a1b85c0e2f7d914a63",output:"a8e53d17c2f64b09a1d7e4b8c3f2069d",config:"3b97f0c64e2a4d8f95b1c7a0e6d3f814",prompt:"d24e8b51f7a34c6e8b09d5f1a2c7e3b6"},UAe="9c3e7a15d2b84f6e8a01c5d7b3f9e240";function yz(e,t,n){let r=(0,mz.normalizeGuid)(e,n).replace(/-/g,""),i=[];for(let a=0;a<32;a+=1)i.push(parseInt(r[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 mb(e,t){return yz(e,FAe[t],"id")}function qAe(e,t){let n=yz(e,UAe,"newTurn.id"),r=parseInt(n.slice(24),16)%2**47+(t==="agent"?1:0);return`${n.slice(0,24)}${r.toString(16).padStart(12,"0")}`}function oz(e){return typeof e=="string"&&e.trim()!==""?e:(0,bb.newId)()}function Es(e){return(0,lt.isJsonObject)(e)?e:{}}function Jd(e,t){return JSON.stringify(e??null)===JSON.stringify(t??null)}function hb(e){return JSON.parse(JSON.stringify(e))}function BAe(e){let t=Es(e);return t.status==="available"&&typeof t.data=="string"?{status:"available",data:t.data}:{status:"unavailable",reason:t.reason==="unpublished"?"unpublished":"missing"}}function Gm(e){if(!e||e.status!=="available")return;let t=(0,vb.base64ToUtf8)(e.data);return(0,vb.utf8ToBase64)(t)===e.data?t:void 0}function bz(e,t,n){var r,i,o,a;return e.source!==void 0&&t!==void 0&&t?.source===e.source&&Jd((r=t?.dataSources)!==null&&r!==void 0?r:[],(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,uI.isLoadableGenPageOutput)(n)}function VAe(e,t){var n;try{return bz(e,t,Gm((n=e.bag)===null||n===void 0?void 0:n.output))}catch{return!1}}function gb(e){if(e!==void 0)try{let t=JSON.parse(e.replace(/^\uFEFF/,""));return(0,lt.isJsonObject)(t)?t:void 0}catch{return}}function az(e,t){if(t===Tu&&e.includes("page.tsx"))return"source";if(t===hz&&e.includes(".compiled"))return"output";if(t===Tu&&e===As.config.name)return"config";if(t===Tu&&e===As.prompt.name)return"prompt"}function sz(e){let t=e.toLowerCase();return gz.some(n=>As[n].name.toLowerCase()===t)}function cI(e){return Object.fromEntries(e)}function vz(e,t,n,r){let i=[],o=new Set,a=new Set(t),s=u=>{if(o.has(u))return;let l=a.has(u)?e[u]:n&&Object.prototype.hasOwnProperty.call(n,u)?n[u]:void 0;l!==void 0&&(o.add(u),i.push([u,l]))};return(r??[]).forEach(s),t.forEach(s),Object.keys(n??{}).forEach(s),cI(i)}function uz(e){var t,n,r;return vz({dataSources:(t=e.dataSources)!==null&&t!==void 0?t:[],model:e.model,connectorBindings:e.connectorBindings,actionBindings:e.actionBindings},LAe,(n=e.bag)===null||n===void 0?void 0:n.config,(r=e.bag)===null||r===void 0?void 0:r.configKeys)}function lz(e){var t,n;return vz({userMessage:e.firstPrompt,agentMessage:e.firstAgentMessage},MAe,(t=e.bag)===null||t===void 0?void 0:t.prompt,(n=e.bag)===null||n===void 0?void 0:n.promptKeys)}function cz(e,t,n){let r=[];for(let[i,o]of Object.entries(n))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:r.push([i,o]);return t.configKeys=Object.keys(n),r.length>0&&(t.config=cI(r)),!0}function dz(e,t,n){let r=[];for(let[i,o]of Object.entries(n))if(i==="userMessage"||i==="agentMessage"){if(typeof o!="string")return!1;i==="userMessage"?e.firstPrompt=o:e.firstAgentMessage=o}else r.push([i,o]);return t.promptKeys=Object.keys(n),r.length>0&&(t.prompt=cI(r)),!0}function jm(e){var t,n;return e.source!==void 0||Object.keys((n=(t=e.bag)===null||t===void 0?void 0:t.rows)!==null&&n!==void 0?n:{}).length>0}var GAe=["dataSources","model","connectorBindings","actionBindings","firstPrompt","firstAgentMessage"];function fz(e){return jm(e)?[]:GAe.filter(t=>e[t]!==void 0).map(t=>(0,lt.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 pz(){return(0,lt.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 yb(e){return{status:"available",data:(0,vb.utf8ToBase64)(e)}}function Vm(e,t){var n,r;return{id:String((n=e.uxagentprojectid)!==null&&n!==void 0?n:""),name:String((r=e.name)!==null&&r!==void 0?r:""),files:t}}var wb=class{toArtifact(t){return t}fromArtifact(t){return t}fromApiResponse(t){let n=t,r=Es(n?.project),i=(Array.isArray(n?.files)?n.files:[]).map(g=>{var y,b,E;let w=Es(g);return{id:String((y=w.uxagentprojectfileid)!==null&&y!==void 0?y:""),name:String((b=w.filename)!==null&&b!==void 0?b:""),fileType:Number((E=w.filetype)!==null&&E!==void 0?E:Tu),content:BAe(w.content)}}),o=Array.isArray(n?.conversation)?n.conversation.map(g=>{var y,b;let E=Es(g);return{sender:Number(E.messagesender)===200000001?"agent":"user",message:String((y=E.message)!==null&&y!==void 0?y:""),createdOn:String((b=E.createdon)!==null&&b!==void 0?b:"")}}):void 0,a=g=>o?{...g,conversation:o}:g,s=new Map,u=[],l=!0;for(let g of i){let y=az(g.name,g.fileType);y?((s.has(y)||g.name!==As[y].name)&&(l=!1),s.set(y,g)):(sz(g.name)&&(l=!1),u.push(g))}if(!l||s.size===0)return a(Vm(r,i));let c=Vm(r,u),d={rows:{}};for(let[g,y]of s)d.rows[g]=y.id;let f=s.get("source");if(f){let g=Gm(f.content);if(g===void 0)return a(Vm(r,i));c.source=g}let p=s.get("output");p&&(d.output=p.content);let m=s.get("config");if(m){let g=gb(Gm(m.content));if(!g||!cz(c,d,g))return a(Vm(r,i))}let h=s.get("prompt");if(h){let g=gb(Gm(h.content));if(!g||!dz(c,d,g))return a(Vm(r,i))}return c.bag=d,a(c)}async toApiPayload(t,n,r){var i,o,a,s,u,l,c,d,f,p,m,h,g;if(n&&!Jd((i=t.conversation)!==null&&i!==void 0?i:[],(o=n.conversation)!==null&&o!==void 0?o:[]))throw new Iu.ValidationError("genPage",t.id,[(0,lt.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 y=fz(t);if(y.length>0)throw new Iu.ValidationError("genPage",t.id,y);let b=[],E=n===void 0,w=E&&t.firstPrompt===void 0&&t.newTurn?{...t,firstPrompt:t.newTurn.prompt,...t.newTurn.agentMessage!==void 0?{firstAgentMessage:t.newTurn.agentMessage}:{}}:t;if(jm(w)){let O=(s=(a=w.bag)===null||a===void 0?void 0:a.rows)!==null&&s!==void 0?s:{},v=U=>{var M;return(M=O[U])!==null&&M!==void 0?M:mb(w.id,U)},N=(U,M,q)=>{b.push({id:v(U),name:As[U].name,fileType:As[U].fileType,content:M,unchanged:q})};if(w.source!==void 0){N("source",yb(w.source),!E&&n?.source===w.source&&O.source!==void 0);let U=Gm((u=w.bag)===null||u===void 0?void 0:u.output);bz(w,n,U)?N("output",{status:"retain"},!0):N("output",yb(await this.compile(w,w.source,r)),!1)}else{if(O.source!==void 0)throw new Iu.ValidationError("genPage",w.id,[pz()]);if(O.output!==void 0){if(!E&&!Jd((l=n?.dataSources)!==null&&l!==void 0?l:[],(c=w.dataSources)!==null&&c!==void 0?c:[]))throw new Iu.ValidationError("genPage",w.id,[(0,lt.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.")]);N("output",{status:"retain"},!0)}}let S=uz(w),R=!E&&n!==void 0&&Jd(uz(n),S);(E||O.config!==void 0||!R)&&N("config",yb(JSON.stringify(S)),R&&O.config!==void 0);let x=lz(w),G=!E&&n!==void 0&&Jd(lz(n),x);(O.prompt!==void 0||Object.keys(x).length>0&&!G)&&N("prompt",yb(JSON.stringify(x)),G&&O.prompt!==void 0)}for(let O of(d=w.files)!==null&&d!==void 0?d:[]){let v=(f=n?.files)===null||f===void 0?void 0:f.find(N=>N.id===O.id);b.push({id:O.id,name:O.name,fileType:O.fileType,content:O.content,unchanged:v!==void 0&&Jd(v,O)})}let _=[],I;if(w.newTurn){I=w.newTurn.id===void 0?void 0:lI(w.newTurn.id);let O=v=>I===void 0?{}:{id:qAe(I,v)};_.push({...O("user"),sender:"user",message:w.newTurn.prompt}),w.newTurn.agentMessage&&_.push({...O("agent"),sender:"agent",message:w.newTurn.agentMessage})}let T=(m=(p=w.bag)===null||p===void 0?void 0:p.config)!==null&&m!==void 0?m:{};return{name:w.name,files:b,..._.length>0?{messages:_,messageContext:{dataSources:(h=w.dataSources)!==null&&h!==void 0?h:[],model:(g=w.model)!==null&&g!==void 0?g:"",enabledTools:Array.isArray(T.enabledTools)?T.enabledTools:[],configurableTools:Array.isArray(T.configurableTools)?T.configurableTools:[]},...I!==void 0?{turnId:I}:{}}:{}}}committed(t,n,r={intentPending:!1}){let i=this.serverState(t,n);return r.intentPending&&t.newTurn!==void 0?{artifact:{...i,newTurn:hb(t.newTurn)},baseline:i}:{artifact:i,baseline:i}}serverState(t,n){var r,i,o,a,s,u;if(!jm(t)&&!t.newTurn)return t;let l=hb(t);if(delete l.newTurn,!jm(t))return l;let c={...(r=l.bag)!==null&&r!==void 0?r:{},rows:{...(o=(i=l.bag)===null||i===void 0?void 0:i.rows)!==null&&o!==void 0?o:{}}};for(let d of(a=n.files)!==null&&a!==void 0?a:[]){let f=gz.find(m=>As[m].name===d.name&&As[m].fileType===d.fileType);if(!f||l.files.some(m=>m.id===d.id)||(c.rows[f]=d.id,d.content.status!=="available"))continue;let p=(0,vb.base64ToUtf8)(d.content.data);f==="output"?c.output={status:"available",data:d.content.data}:f==="config"?(delete c.config,delete l.dataSources,delete l.model,delete l.connectorBindings,delete l.actionBindings,cz(l,c,(s=gb(p))!==null&&s!==void 0?s:{})):f==="prompt"&&(delete c.prompt,delete l.firstPrompt,delete l.firstAgentMessage,dz(l,c,(u=gb(p))!==null&&u!==void 0?u:{}))}return l.bag=c,l}baselineContent(t){var n;let r={...t};return delete r.conversation,delete r.newTurn,r.files=[...(n=t.files)!==null&&n!==void 0?n:[]].sort((i,o)=>i.id<o.id?-1:i.id>o.id?1:0),r}normalize(t){let n=t.newTurn;if(!(0,lt.isJsonObject)(n))return t;if(n.id===void 0)return{...t,newTurn:{...n,id:(0,bb.newId)()}};let r=lI(n.id);return r===n.id?t:{...t,newTurn:{...n,id:r}}}async compile(t,n,r){var i,o;let a=(i=t.dataSources)!==null&&i!==void 0?i:[],s=[],u=[];if(a.forEach((p,m)=>{var h;let g=(h=r?.resolveEntity)===null||h===void 0?void 0:h.call(r,p);g&&g.columnDetailComplete===!0?s.push(g):u.push((0,lt.issue)(`/dataSources/${m}`,g?"genpage-data-source-incomplete":"genpage-data-source-unresolved",g?`the column metadata of data source '${p}' 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 '${p}' could not be read, so the page cannot be compiled with its enums. Check the table's logical name and that it exists in this environment.`))}),u.length>0)throw new Iu.ValidationError("genPage",t.id,u);if(!r?.loadTypeScript)throw new Iu.ValidationError("genPage",t.id,[(0,lt.issue)("/source","genpage-compiler-unavailable","no TypeScript compiler is available to compile the page")]);let l=await r.loadTypeScript(),c=s.length>0?(0,sI.buildGenPageRuntimeTypes)(s):void 0,d=s.length>0?(0,sI.buildGenPageLegacyEnums)(s):void 0,f=(0,uI.compileGenPage)(l,n,c,d,{iteration:(o=r.genPageIteration)!==null&&o!==void 0?o:uI.GENPAGE_ITERATION_DEFAULT});if(f.diagnostics.length>0)throw new Iu.ValidationError("genPage",t.id,f.diagnostics.map(jAe));return f.code}metadataNeeds(t,n){if(t.source===void 0||!Array.isArray(t.dataSources))return[];let r=VAe(t,n)?{fetchRequired:!1}:{};return t.dataSources.filter(i=>typeof i=="string"&&i!=="").map(i=>({entityLogicalName:i,fieldName:"",needsColumnDetail:!0,...r}))}createDefault(t){var n,r;let i=oz(t.id),o={id:i,name:(n=t.name)!==null&&n!==void 0?n:"New page",files:((r=t.files)!==null&&r!==void 0?r:[]).map(a=>{var s,u,l;return{id:oz(a.id),name:(s=a.name)!==null&&s!==void 0?s:"index.tsx",fileType:(u=a.fileType)!==null&&u!==void 0?u:Tu,content:(l=a.content)!==null&&l!==void 0?l:{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=hb(t.connectorBindings)),t.actionBindings!==void 0&&(o.actionBindings=hb(t.actionBindings)),o.source!==void 0&&(o.bag={rows:{source:mb(i,"source"),output:mb(i,"output"),config:mb(i,"config")}}),o}assignMissingIds(t){if(t==null)return{id:(0,bb.newId)()};if(!(0,lt.isJsonObject)(t))return t;let n=t;return(Object.keys(n).length===0||"id"in n||"content"in n||"fileType"in n||Array.isArray(n.files))&&(typeof n.id!="string"||n.id.trim()==="")&&(n.id=(0,bb.newId)()),n}validate(t){let n=[],r=t;for(let s of["source","model","firstPrompt","firstAgentMessage"])r[s]!==void 0&&typeof r[s]!="string"&&n.push((0,lt.issue)(`/${s}`,"genpage-field-type",`${s} must be a string, got ${typeof r[s]}`));if(r.source===void 0&&Es(Es(r.bag).rows).source!==void 0&&n.push(pz()),n.push(...fz(t)),r.newTurn!==void 0){let s=Es(r.newTurn);(!(0,lt.isJsonObject)(r.newTurn)||typeof s.prompt!="string"||s.prompt.trim()==="")&&n.push((0,lt.issue)("/newTurn/prompt","genpage-turn-prompt","newTurn needs a non-empty prompt")),s.agentMessage!==void 0&&typeof s.agentMessage!="string"&&n.push((0,lt.issue)("/newTurn/agentMessage","genpage-field-type","newTurn.agentMessage must be a string")),s.id!==void 0&&xAe(s.id)===void 0&&n.push((0,lt.issue)("/newTurn/id","genpage-turn-id","newTurn.id must be a GUID (case-insensitive, optionally brace-wrapped), or omitted so the SDK mints one. Reuse it only for the same page and intended turn."))}if(r.dataSources!==void 0)if(!Array.isArray(r.dataSources))n.push((0,lt.issue)("/dataSources","genpage-data-sources-array","dataSources must be an array of table logical names"));else{let s=new Set;r.dataSources.forEach((u,l)=>{typeof u!="string"||!sI.TABLE_LOGICAL_NAME.test(u)?n.push((0,lt.issue)(`/dataSources/${l}`,"genpage-data-source-name",`a data source must be a table logical name (lowercase, e.g. 'account'), got '${String(u)}'`)):s.has(u)?n.push((0,lt.issue)(`/dataSources/${l}`,"genpage-data-source-duplicate",`data source '${u}' is listed twice`)):s.add(u)})}r.conversation!==void 0&&!Array.isArray(r.conversation)&&n.push((0,lt.issue)("/conversation","genpage-conversation-array","conversation must be an array"));let i=r.files;if(i!==void 0&&!Array.isArray(i))return n.push((0,lt.issue)("/files","files-must-be-array",`files must be an array, got ${typeof i}`)),n;let o=jm(t),a=new Map;return(Array.isArray(i)?i:[]).forEach((s,u)=>{let l=`/files/${u}`,c=Es(s),d=typeof c.id=="string"?c.id.trim().toLowerCase():"";if(d==="")n.push((0,lt.issue)(l,"file-id-required","a generative-page file needs an id"));else{let g=a.get(d);g!==void 0?n.push((0,lt.issue)(l,"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,u)}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==="..")?n.push((0,lt.issue)(l+"/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&&(sz(f)||az(f,Number(c.fileType))!==void 0)&&n.push((0,lt.issue)(l+"/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){n.push((0,lt.issue)(l+"/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=Es(m);h.status==="available"?typeof h.data!="string"&&n.push((0,lt.issue)(l+"/content/data","file-content-data-invalid","available content needs base64 `data`")):h.status!=="unavailable"&&n.push((0,lt.issue)(l+"/content/status","file-content-status-invalid",`content.status must be 'available' or 'unavailable', got ${String(h.status)}`))}),n}};Yd.GenPageAdapter=wb;function jAe(e){let t=`line ${e.line}, column ${e.column}`;return e.rule==="genpage-source-syntax"?(0,lt.issue)("/source",e.rule,`${t}: ${e.message} (TS${e.code}) \u2014 the page cannot run, so it was not pushed`):(0,lt.issue)("/source",e.rule,`${t}: ${e.message}`)}function WAe(){return{adapter:new wb,api:kAe.genPageApi,publish:(e,t)=>(0,$Ae.publishGenPageById)(e,t),publishScope:e=>({envelope:"uxagentproject",targetIds:[e]}),rebaselineAfterPublish:"snapshot"}}Yd.genPageRegistration=WAe});var Az=C(Ab=>{"use strict";Object.defineProperty(Ab,"__esModule",{value:!0});Ab.reconcileBpfSecurityRoles=void 0;var Ez=Ke(),fI=Y(),Eb=pe(),Wm=ae(),zAe="Global",dI={create:"Create",read:"Read",write:"Write",delete:"Delete"};async function HAe(e,t){var n;let r=`/EntityDefinitions(LogicalName='${(0,Wm.odataPathLiteral)(t)}')?$select=LogicalName,Privileges`,i=(0,Eb.ensureSuccess)(await e.get(r),e.apiUrl(r)),o=(n=i.body)===null||n===void 0?void 0:n.Privileges;if(!Array.isArray(o))throw new fI.ConnectionError(e.apiUrl(r),i.status,`reading the privileges of business process flow table '${t}' returned no 'Privileges' array (got ${(0,Ez.describeMalformedValue)(o)}), so which access it can grant is unknown.`);let a=o,s={},u=new Set;return Object.keys(dI).forEach(l=>{let c=a.find(d=>d.PrivilegeType===dI[l]);if(c){let d=(0,Wm.normalizeGuid)(c.PrivilegeId,"PrivilegeId");s[l]=d,u.add(d)}}),{byAccess:s,all:u}}async function KAe(e,t){var n;let r=`/RetrieveRolePrivilegesRole(RoleId=${t})`,i=(0,Eb.ensureSuccess)(await e.get(r),e.apiUrl(r)),o=(n=i.body)===null||n===void 0?void 0:n.RolePrivileges;if(!Array.isArray(o))throw new fI.ConnectionError(e.apiUrl(r),i.status,`reading the privileges of role '${t}' returned no 'RolePrivileges' array (got ${(0,Ez.describeMalformedValue)(o)}), so what it holds is unknown.`);return new Set(o.map(a=>(0,Wm.normalizeGuid)(a.PrivilegeId,"PrivilegeId")))}async function JAe(e,t,n){if(n.length===0)return;let r={Privileges:n.map(o=>({Depth:zAe,PrivilegeId:o}))},i=`/roles(${t})/Microsoft.Dynamics.CRM.AddPrivilegesRole`;(0,Eb.ensureSuccess)(await e.post(i,r),e.apiUrl(i))}async function YAe(e,t,n){let r={Privilege:{"@odata.type":"Microsoft.Dynamics.CRM.privilege",privilegeid:n}},i=`/roles(${t})/Microsoft.Dynamics.CRM.RemovePrivilegeRole`;(0,Eb.ensureSuccess)(await e.post(i,r),e.apiUrl(i))}async function QAe(e,t,n){var r,i,o;if(!n||n.length===0)return;let a=await HAe(e,t.toLowerCase());for(let s of n){let u=(0,Wm.normalizeGuid)(s.roleId,"roleId"),l=((r=s.access)!==null&&r!==void 0?r:[]).find(c=>!a.byAccess[c]);if(l!==void 0)throw new fI.InvalidArgumentError(`Cannot grant '${l}' access to role '${u}' on business process flow table '${t.toLowerCase()}': its metadata lists no '${(i=dI[l])!==null&&i!==void 0?i:l}' privilege. No security role was changed.`)}for(let s of n){let u=(0,Wm.normalizeGuid)(s.roleId,"roleId"),l=new Set(((o=s.access)!==null&&o!==void 0?o:[]).map(m=>a.byAccess[m]).filter(m=>!!m)),c=await KAe(e,u),d=new Set([...c].filter(m=>a.all.has(m))),f=[...l].filter(m=>!d.has(m)),p=[...d].filter(m=>!l.has(m));await JAe(e,u,f);for(let m of p)await YAe(e,u,m)}}Ab.reconcileBpfSecurityRoles=QAe});var Lz=C(Hm=>{"use strict";Object.defineProperty(Hm,"__esModule",{value:!0});Hm.bpfApi=void 0;var Hr=Ds(),Cz=Zo(),XAe=Ke(),nn=Y(),pI=qi(),Gt=pe(),uo=ae(),ZAe=Az(),eCe=Dv(),zm=Rv(),tCe={"Content-Type":"application/json",Accept:"application/json"},mI={...tCe,Prefer:"return=representation"},nCe=`category eq ${Hr.WorkflowCategory.BusinessProcessFlow} and type eq ${Hr.WorkflowTypeCode.Definition} and businessprocesstype eq ${Hr.BusinessProcessType.BusinessFlow}`,rCe="workflowid,name,description,primaryentity,statecode,category,type,businessprocesstype,processorder",iCe="workflowid,name,uniquename,description,primaryentity,statecode,statuscode,category,type,businessprocesstype,processorder,xaml,clientdata",oCe=["xaml","name","description","processorder"];async function Cb(e,t){var n;if(t.status!=="Active"||!t.securityRoles||t.securityRoles.length===0)return;let r=String((n=t.record.uniquename)!==null&&n!==void 0?n:"");r!==""&&await(0,ZAe.reconcileBpfSecurityRoles)(e,r,t.securityRoles)}async function gI(e,t,n){let r={statecode:Hr.StateCode.Activated,statuscode:Hr.StatusCode.Activated},i=`/workflows(${t})`,{response:o,resent:a}=await $z(e,i,r,n,null);try{return(0,Gt.ensureSuccess)(o,e.apiUrl(i))}catch(s){throw a?Rz(s):s}}var Pz=new WeakSet;function Rz(e){return typeof e=="object"&&e!==null&&Pz.add(e),e}function kz(e){return typeof e=="object"&&e!==null&&Pz.has(e)}function Sz(e){return e instanceof nn.ConnectionError&&(e.statusCode===0||Gt.AMBIGUOUS_WRITE_STATUSES.has(e.statusCode))}async function $z(e,t,n,r,i){let o=r??i,a=0;try{return{response:await(0,Gt.resendWhile)(Gt.isConcurrencyLockRefusal,()=>{a+=1;let u=a===1?r:o,l={...mI};return u&&(l["If-Match"]=u),e.patch(t,n,{headers:l})},o?Gt.LOCK_BACKOFF_MS:[]),resent:a>1}}catch(s){throw a>1?Rz(s):s}}async function Nz(e,t,n){return(0,Gt.readEtag)(await gI(e,t,n))}function _z(e,t){return new nn.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. `+Sb(e))}async function Km(e,t){var n;let r=`/workflows(${t})${(0,uo.odataQuery)([["$select","statecode"]])}`,i=(0,Gt.ensureSuccess)(await e.get(r),e.apiUrl(r)),o=(n=i.body)===null||n===void 0?void 0:n.statecode,a=Number(o);if(o==null||o===""||!Number.isFinite(a))throw new nn.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 hI(e,t,n,r,i=null){if((r??await Km(e,t))!==Hr.StateCode.Activated)return{deactivated:!1,etag:null};let o={statecode:Hr.StateCode.Draft,statuscode:Hr.StatusCode.Draft},a=`/workflows(${t})`,s,u;try{({response:s,resent:u}=await $z(e,a,o,n,i))}catch(c){return await Iz(e,t,c,kz(c))}if(Gt.AMBIGUOUS_WRITE_STATUSES.has(s.status))return await Iz(e,t,new nn.SdkError("BPF_DEACTIVATE_OUTCOME_UNKNOWN",`Deactivating business process flow '${t}' answered HTTP ${s.status} from an intermediary, so whether it committed is unknown.`),u);let l=(0,Gt.ensureSuccess)(s,e.apiUrl(a));return{deactivated:!0,etag:(0,Gt.readEtag)(l)}}async function Iz(e,t,n,r){let i;try{i=await Km(e,t)}catch{i=void 0}if(i===Hr.StateCode.Draft&&!r)return{deactivated:!0,etag:null,uncertainCause:n};if(i===Hr.StateCode.Activated)throw n;let o=new nn.SdkError("BPF_DEACTIVATE_OUTCOME_UNKNOWN",i===Hr.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: ${n instanceof Error?n.message:String(n)}`:`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: ${n instanceof Error?n.message:String(n)}`);throw(0,nn.attachCause)(o,n),o}async function aCe(e,t){let n=(0,uo.normalizeGuid)(t,"workflowid");try{return await gI(e,n,null),"restored"}catch{return yI(e,n)}}async function sCe(e,t,n){let r=(0,uo.normalizeGuid)(t,"workflowid");try{let i=await gI(e,r,n);return{outcome:"restored",acknowledged:!0,echo:(0,Gt.readEtag)(i)}}catch(i){return i instanceof nn.SdkError&&i.code===Gt.VERSION_CONFLICT_CODE?{outcome:"changed",acknowledged:!1,echo:null}:{outcome:await yI(e,r),acknowledged:!1,echo:null}}}async function yI(e,t){try{let n=await Km(e,t);return n===Hr.StateCode.Activated?"restored":n===Hr.StateCode.Draft?"disabled":"unknown"}catch{return"unknown"}}async function Tz(e,t,n,r){return n?{...await sCe(e,t,n),attempted:!0}:r?{outcome:await yI(e,(0,uo.normalizeGuid)(t,"workflowid")),attempted:!1,acknowledged:!1,echo:null}:{outcome:await aCe(e,t),attempted:!0,acknowledged:!1,echo:null}}function uCe(e,t){let n=new nn.SdkError(zm.WORKFLOW_DELETE_UNSETTLED_CODE,`Deleting business process flow '${e}' failed${(0,zm.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,nn.attachCause)(n,t),n}function Oz(e,t,n,r,i=!0){let o=`Original failure: ${r instanceof Error?r.message:String(r)}`,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 n==="changed"?s=new nn.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}`):n==="disabled"?s=new nn.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 nn.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,nn.attachCause)(s,r),s}async function lCe(e,t){try{return await Km(e,t),"survived"}catch(n){return n instanceof nn.ConnectionError&&n.statusCode===404?"removed":"unknown"}}async function cCe(e,t,n){if(n)try{let{deactivated:r,etag:i}=await hI(e,t,n),o=r?i:n;if(o)return await(0,zm.deleteWorkflowResending)(e,t,{bindingToken:o,kindName:"business process flow",resendDeadlockVictim:!0,ifMatchOnFirst:!0}),"removed"}catch{}return lCe(e,t)}function Sb(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 Dz(e,t){return new nn.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. ${Sb(e)}`)}function dCe(e,t){let n=new nn.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.) ${Sb(e)} Or delete it. Original failure: ${t instanceof Error?t.message:String(t)}`);return(0,nn.attachCause)(n,t),n}function fCe(e,t){let n=new nn.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. ${Sb(e)} Or delete it. Original failure: ${t instanceof Error?t.message:String(t)}`);return(0,nn.attachCause)(n,t),n}function pCe(e,t){let n=new nn.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,nn.attachCause)(n,t),n}function bI(e){let t={};for(let n of oCe)e[n]!==void 0&&(t[n]=e[n]);return t}var mCe=["name,processorder","description,name,processorder"];function hCe(e){let{xaml:t,...n}=bI(e);return typeof t=="string"&&mCe.includes(Object.keys(n).sort().join(","))}async function gCe(e,t,n,r){let{xaml:i,...o}=bI(n),[,a]=await(0,Cz.sendChangeSet)(e,[{method:"PATCH",path:`/workflows(${t})`,body:o,etag:r},{method:"PATCH",path:`/workflows(${t})${(0,uo.odataQuery)([["$select","workflowid"]])}`,body:{xaml:i},headers:{Prefer:"return=representation"}}],`business process flow '${t}'`,{resendWhileLockRefused:!0});return(0,Gt.readEtag)((0,Cz.partResponse)(a))}Hm.bpfApi={async get(e,t){let r=`/workflows(${(0,uo.normalizeGuid)(t,"id")})${(0,uo.odataQuery)([["$select",iCe]])}`,i=(0,Gt.ensureSuccess)(await e.get(r),e.apiUrl(r));return{raw:i.body,etag:(0,Gt.readEtag)(i)}},async list(e,t){let n=[nCe];t?.entityLogicalName&&n.push(`primaryentity eq '${(0,uo.odataLiteral)(t.entityLogicalName)}'`);let r=`/workflows${(0,uo.odataQuery)([["$select",rCe],["$filter",n.join(" and ")]])}`;return(await(0,XAe.collectPages)(e,r,"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,n=void 0,r){let i=t,o=(0,uo.normalizeGuid)(i.record.workflowid,"workflowid"),a="/workflows";if(r)return r.reached({effects:[{componentName:"Workflow",componentId:o,identity:"known",operation:"create"}],attemptsWrite:!0},()=>(0,pI.existsByKey)(e,r,{collection:"/workflows",key:"workflowid",id:o,componentName:"Workflow"}));let s=(0,Gt.ensureSuccess)(await e.post(a,i.record,{headers:mI}),e.apiUrl(a)),u=(0,Gt.readEtag)(s);if(!u)throw Dz(o,i.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 l=u;try{i.status==="Active"&&(l=await Nz(e,o,u)),await Cb(e,i)}catch(c){let d=await cCe(e,o,l);throw d==="survived"?dCe(o,c):d==="unknown"?fCe(o,c):c instanceof nn.SdkError&&c.code===Gt.VERSION_CONFLICT_CODE?pCe(o,c):c}if(!l)throw Dz(o,"The process EXISTS and IS Active, but its activation returned no token.");return{id:o,etag:l}},async update(e,t,n,r,i=void 0,o,a){let s=n,u=(0,uo.normalizeGuid)(t,"id");a&&!(0,Gt.isVersionToken)(r)&&a.observe({guard:"ifMatch",componentName:"Workflow",componentId:u,held:r,status:"missingHeld"});let l=(0,Gt.requireEtag)(r,"bpf",u),c=await Km(e,u);if(a)return await(0,pI.observeIfMatch)(e,a,{entitySet:"workflows",idColumn:"workflowid",id:u,componentName:"Workflow",held:l}),a.reached({effects:[{componentName:"Workflow",componentId:u,identity:"known",operation:"update"}],attemptsWrite:!0});if(c===Hr.StateCode.Activated&&s.status==="Active"&&e.supportsAtomicBatch&&hCe(s.record)){let y=await gCe(e,u,s.record,l);return await Cb(e,s),{id:u,etag:y}}let{deactivated:d,etag:f,uncertainCause:p}=await hI(e,u,l,c),m=f,h=!1,g=!1;try{if(p!==void 0)throw p;let y=l;if(d){if(!f)throw _z(u,"deactivation");y=f}let b=`/workflows(${u})`,E;try{E=(0,Gt.ensureSuccess)(await e.patch(b,bI(s.record),{headers:{...mI,"If-Match":y}}),e.apiUrl(b))}catch(_){throw Sz(_)&&(m=null),_}let w=(0,Gt.readEtag)(E);if(m=w,s.status==="Active"){if(!w)throw _z(u,"definition write");try{w=await Nz(e,u,w)}catch(_){throw Sz(_)&&(m=null),g=(0,Gt.isConcurrencyLockRefusalError)(_),_}h=!0}return await Cb(e,s),{id:u,etag:w}}catch(y){if(d&&!h){let{outcome:b,attempted:E,acknowledged:w,echo:_}=await Tz(e,u,m,kz(y));if(g&&w)return h=!0,await Cb(e,s),{id:u,etag:_};if(b!=="restored")throw Oz(u,"to apply an edit, the edit failed",b,y,E)}throw y}},planPush(e,t,n){return(0,pI.planPushThrough)(Hm.bpfApi,e,t,n)},async delete(e,t){let n=(0,uo.normalizeGuid)(t,"id"),r=await(0,eCe.assertWorkflowKind)(e,n,Hr.WorkflowCategory.BusinessProcessFlow),{deactivated:i,etag:o}=await hI(e,n,null,void 0,r);try{await(0,zm.deleteWorkflowResending)(e,n,{bindingToken:i?o:r,kindName:"business process flow",deactivated:i,resendDeadlockVictim:!0})}catch(a){if(i&&!(0,zm.isWorkflowDeleteUnsettled)(a)){let{outcome:s,attempted:u}=await Tz(e,n,o,!1);if(s==="changed")throw uCe(n,a);if(s!=="restored")throw Oz(n,"so it could be deleted, the delete failed",s,a,u)}throw a}}}});var b9=C(Xd=>{"use strict";Object.defineProperty(Xd,"__esModule",{value:!0});Xd.bpfRegistration=Xd.BpfAdapter=void 0;var Nb=Ds(),yCe=Lz(),vI=Us(),Wl=ja(),Kz=Ga(),Mi=Vi(),Ai=ft(),Fo=Y(),bCe=100,wI='<?xml version="1.0" encoding="utf-16"?>',Mz=1033,Jz="mxswa:Workflow",vCe="mxswa:ActivityReference.Properties",wCe="mcwo:StepLabel",ECe="mcwb:Control",xz="mcwb:Control.ControlDisplayName",Yz="mcwb:Control.DataFieldName",Qz="DataFieldName",Fz="ControlDisplayName",Xz="Literal",Ib="x:Null",Uz="x:String",EI="x:Key",AI="DisplayName",Ob="Activities",ACe="StepLabels",Zz="StageId",e9="StageCategory",t9="NextStageId",n9="ProcessStepId",_b="IsProcessRequired",r9="EntityComposite",i9="StageComposite",o9="StepComposite";function Jm(e){return(0,Mi.isJsonObject)(e)?e:{}}function Na(e){if(!e)return[];let t=[],n=e.childNodes;for(let r=0;r<n.length;r+=1){let i=n[r];i.nodeType===1&&t.push(i)}return t}function zl(e,t){var n;return(n=Na(e).find(r=>r.tagName===t))!==null&&n!==void 0?n:null}function Ia(e){return zl(e,vCe)}function Kr(e,t){var n;return(n=Na(e).find(r=>r.getAttribute(EI)===t))!==null&&n!==void 0?n:null}function Qd(e,t){var n;return((n=e.getAttribute("AssemblyQualifiedName"))!==null&&n!==void 0?n:"").includes(t)}function _a(e){var t;return!e||!e.firstChild?"":(t=e.firstChild.nodeValue)!==null&&t!==void 0?t:""}function a9(e,t,n){e.firstChild?e.firstChild.nodeValue=n:e.appendChild(t.createTextNode(n))}function Ym(e){var t;let n=(t=e.getAttribute(AI))!==null&&t!==void 0?t:"",r=n.indexOf(": ");return r>=0?n.slice(r+2):n}function s9(e,t){var n;let r=(n=e.getAttribute(AI))!==null&&n!==void 0?n:"",i=r.indexOf(": ");e.setAttribute(AI,i>=0?r.slice(0,i+2)+t:t)}function u9(e,t){let n=Kr(e,ACe),r=zl(n,wCe);r&&r.setAttribute("Description",t)}function CCe(e){let t=Kr(e,e9);if(!t||t.tagName===Ib)return;let n=_a(t).trim();return n===""?void 0:Number(n)}function SCe(e){let t=Kr(e,t9);if(!t||t.tagName===Ib)return;let n=_a(t).trim();return n===""?void 0:n}function l9(e){let t=c9(e);if(!t)return;let n=f9(t,Qz,Yz);return n===""?void 0:n}function CI(e,t){let n=Na(e);for(;n.length>0;){let r=n.pop();if(r.tagName===t)return r;for(let i of Na(r))n.push(i)}return null}function c9(e){let t=Kr(Ia(e),Ob);return t?CI(t,ECe):null}function d9(e,t){let n=e.attributes;for(let r=0;r<n.length;r+=1)if(n[r].name===t)return!0;return!1}function f9(e,t,n){var r;return d9(e,t)?(r=e.getAttribute(t))!==null&&r!==void 0?r:"":OCe(e,n)}function qz(e,t,n,r){if(d9(e,t)){e.setAttribute(t,r);return}if(zl(e,n)){NCe(e,n,r);return}throw new Fo.InvalidArgumentError(`BPF step control exposes neither a '${t}' attribute nor a <${n}> wrapper to bind a column`)}function NCe(e,t,n){let r=zl(e,t),i=r?CI(r,Xz):null;if(!i)throw new Fo.InvalidArgumentError(`BPF step control's <${t}> wrapper holds no <Literal> to bind a column`);i.setAttribute("Value",n)}function p9(e){return Ym(e)}function Db(e){let t=zl(e,Jz),n=[];for(let r of Na(t).filter(i=>Qd(i,r9))){let i=Kr(Ia(r),Ob);for(let o of Na(i).filter(a=>Qd(a,i9)))n.push({el:o,entity:p9(r)})}return n}function SI(e){let t=Kr(Ia(e),Ob);return Na(t).filter(n=>Qd(n,o9))}function _Ce(e){let t=Ia(e),n=_a(Kr(t,_b)).trim().toLowerCase(),r=l9(e),i={id:_a(Kr(t,n9)),name:Ym(e)};return r!==void 0&&(i.fieldName=r),n==="true"&&(i.required=!0),i}function ICe(e,t){let n=Ia(e),r=CCe(n),i=SCe(n),o={id:_a(Kr(n,Zz)),name:Ym(e),entityLogicalName:t,steps:SI(e).map(_Ce)};return r!==void 0&&(o.category=r),i!==void 0&&(o.nextStageId=i),o}function TCe(e){return Db(e).map(({el:t,entity:n})=>ICe(t,n))}function Sa(e){return new Fo.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 OCe(e,t){var n;let r=zl(e,t),i=r?CI(r,Xz):null;return(n=i?.getAttribute("Value"))!==null&&n!==void 0?n:""}function NI(e,t){var n;let r=e.createElement(t.tagName),i=t.attributes;for(let a=0;a<i.length;a+=1)r.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?r.appendChild(NI(e,s)):s.nodeType===3&&r.appendChild(e.createTextNode((n=s.nodeValue)!==null&&n!==void 0?n:""))}return r}function m9(e){return Kr(Ia(e),Ob)}function DCe(e,t,n){var r;let i=t.entityLogicalName&&t.entityLogicalName.trim()!==""?t.entityLogicalName:n,o=!((r=t.steps[0])===null||r===void 0)&&r.id&&t.steps[0].id.trim()!==""?t.steps[0].id:(0,Ai.newId)(),{body:a}=Pb(_I(i,(0,Ai.newId)(),t.id,o));return NI(e,Db((0,Wl.parseXmlRoot)(a,"<Activity/>"))[0].el)}function PCe(e,t){let{body:n}=Pb(_I("account",(0,Ai.newId)(),(0,Ai.newId)(),t.id));return NI(e,SI(Db((0,Wl.parseXmlRoot)(n,"<Activity/>"))[0].el)[0])}function h9(e,t){for(;e.firstChild;)e.removeChild(e.firstChild);for(let n of t)e.appendChild(n)}function g9(e,t,n,r){let i=Kr(e,n);if(!i||!i.parentNode){if(r!==void 0&&r!=="")throw Sa(`setting '${n}' on a stage whose xaml does not expose that slot`);return}let o=i.parentNode;if(r===void 0||r===""){if(i.tagName!==Ib&&_a(i).trim()!==""){let s=t.createElement(Ib);s.setAttribute(EI,n),o.replaceChild(s,i)}return}if(i.tagName===Uz){_a(i).trim()!==r&&a9(i,t,r);return}let a=t.createElement(Uz);a.setAttribute(EI,n),a.appendChild(t.createTextNode(r)),o.replaceChild(a,i)}function RCe(e,t,n){g9(e,t,e9,n===void 0?void 0:String(n))}function kCe(e,t,n){g9(e,t,t9,n)}function y9(e,t,n){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r+=1)if(n(e[r])!==t[r])return!1;return!0}function Bz(e){return _a(Kr(Ia(e),Zz))}function Vz(e){return _a(Kr(Ia(e),n9))}function Gz(e,t,n){var r,i,o,a;let s=Ia(e);n.name!==Ym(e)&&(s9(e,n.name),u9(s,n.name));let u=_a(Kr(s,_b)).trim().toLowerCase()==="true";if(((r=n.required)!==null&&r!==void 0?r:!1)!==u){let l=Kr(s,_b);if(!l)throw Sa(`setting '${_b}' on a step whose xaml does not expose that slot`);a9(l,t,n.required?"True":"False")}if(((i=n.fieldName)!==null&&i!==void 0?i:"")!==((o=l9(e))!==null&&o!==void 0?o:"")){let l=c9(e);if(!l)throw new Fo.InvalidArgumentError("BPF step has no <mcwb:Control> element to bind a column to");let c=(a=n.fieldName)!==null&&a!==void 0?a:"";qz(l,Qz,Yz,c),c!==""&&f9(l,Fz,xz)===""&&qz(l,Fz,xz,c)}}function jz(e,t,n,r){var i;let o=Ia(e);if(!o)throw new Fo.InvalidArgumentError("BPF stage composite has no <\u2026ActivityReference.Properties>");if(n.name!==Ym(e)&&(s9(e,n.name),u9(o,n.name)),RCe(o,t,n.category),kCe(o,t,r),n.relationshipName&&n.relationshipName.trim()!=="")throw Sa("a stage relationship / table change (multi-table authoring)");if(n.actions&&n.actions.length>0||n.branch)throw Sa("stage actions or conditional branching");let a=m9(e);if(!a)throw new Fo.InvalidArgumentError("BPF stage has no [Activities] collection");let s=(i=n.steps)!==null&&i!==void 0?i:[];if(s.length===0)throw new Fo.InvalidArgumentError(`BPF stage '${n.name}' must have at least one step`);let u=SI(e);if(y9(u,s.map(d=>d.id),Vz)){u.forEach((d,f)=>Gz(d,t,s[f]));return}let l=new Map(u.map(d=>[Vz(d),d]));if(Na(a).some(d=>!Qd(d,o9)))throw Sa("adding, removing or reordering steps on a stage that also contains branching or actions");let c=s.map(d=>{var f;return(f=l.get(d.id))!==null&&f!==void 0?f:PCe(t,d)});h9(a,c),c.forEach((d,f)=>Gz(d,t,s[f]))}function $Ce(e,t,n){let r=zl(e,Jz);if(!r)throw new Fo.InvalidArgumentError("BPF xaml has no <mxswa:Workflow> root activity");if(n.globalActions&&n.globalActions.length>0)throw Sa("global (process-completed/abandoned) actions");if(!n.stages||n.stages.length===0)throw new Fo.InvalidArgumentError("a BPF must have at least one stage");let i=Db(e),o=i.map(f=>f.el);if(y9(o,n.stages.map(f=>f.id),Bz)){i.forEach(({el:f,entity:p},m)=>{let h=n.stages[m];if(h.entityLogicalName&&h.entityLogicalName.trim()!==""&&h.entityLogicalName!==p)throw Sa(`changing a stage's table ('${h.entityLogicalName}' vs the process's '${p}')`);jz(f,t,h,h.nextStageId)});return}let a=Na(r).filter(f=>Qd(f,r9));if(a.length!==1)throw Sa("adding, removing or reordering stages on a multi-table process");let s=a[0],u=p9(s),l=m9(s);if(!l)throw new Fo.InvalidArgumentError("BPF primary entity composite has no [Activities] collection");if(Na(l).some(f=>!Qd(f,i9)))throw Sa("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 n.stages)if(f.entityLogicalName&&f.entityLogicalName.trim()!==""&&f.entityLogicalName!==u)throw Sa(`a stage on a different table ('${f.entityLogicalName}') than the process primary ('${u}')`);let c=new Map(o.map(f=>[Bz(f),f])),d=n.stages.map(f=>{var p;return(p=c.get(f.id))!==null&&p!==void 0?p:DCe(t,f,u)});h9(l,d),d.forEach((f,p)=>{let m=p<d.length-1?n.stages[p+1].id:void 0;jz(f,t,n.stages[p],m)})}function Pb(e){let t=e.match(/^<\?xml[^>]*\?>\s*/),n=t?t[0]:"";return{prolog:n,body:e.slice(n.length)}}function LCe(e){var t,n,r,i,o,a;(0,Kz.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,vI.mergeAttrs)(s.a,[]),c:(0,vI.spliceChildren)(s.c,[])};return{root:(0,vI.rebuildRaw)(p,(0,Wl.domEngine)(f),null),prolog:(r=(n=e.bag)===null||n===void 0?void 0:n.xamlProlog)!==null&&r!==void 0?r:wI,eol:(o=(i=e.bag)===null||i===void 0?void 0:i.xamlEol)!==null&&o!==void 0?o:"lf"}}let u=e.stages[0],l=(a=u?.steps)===null||a===void 0?void 0:a[0],c=_I(e.entityLogicalName,(0,Ai.newId)(),u?.id&&u.id.trim()!==""?u.id:(0,Ai.newId)(),l?.id&&l.id.trim()!==""?l.id:(0,Ai.newId)()),{body:d}=Pb(c);return{root:(0,Wl.parseXmlRoot)(d,"<Activity/>"),prolog:wI,eol:"lf"}}function MCe(e){let{root:t,prolog:n,eol:r}=LCe(e);$Ce(t,t.ownerDocument,e);let i=(0,Wl.serializeNode)(t);return r==="crlf"&&(i=i.replace(/\n/g,`\r+`)),n+i}function xCe(e){return e.uniqueName&&e.uniqueName.trim()!==""?e.uniqueName:`new_${(e.name||"businessprocessflow").toLowerCase().replace(/[^a-z0-9]/g,"")||"businessprocessflow"}`}var Tb=class{toArtifact(t){return t}fromArtifact(t){return t}fromApiResponse(t){var n,r;(0,Kz.installDomShim)();let i=t,o=typeof i.xaml=="string"?i.xaml:"",a={id:i.workflowid?String(i.workflowid):null,name:String((n=i.name)!==null&&n!==void 0?n:""),entityLogicalName:String((r=i.primaryentity)!==null&&r!==void 0?r:""),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:u}=Pb(o),l=(0,Wl.parseXmlRoot)(u,"<Activity/>");a.stages=TCe(l),a.bag={xaml:(0,Wl.projectElementBag)(l),xamlProlog:s,xamlEol:/\r\n/.test(o)?"crlf":"lf"}}return a}toApiPayload(t){var n;let r={workflowid:t.id&&t.id.trim()!==""?t.id:(0,Ai.newId)(),name:t.name,uniquename:xCe(t),primaryentity:t.entityLogicalName,xaml:MCe(t),category:Nb.WorkflowCategory.BusinessProcessFlow,type:Nb.WorkflowTypeCode.Definition,businessprocesstype:Nb.BusinessProcessType.BusinessFlow,scope:Nb.WorkflowScope.Organization,processorder:(n=t.order)!==null&&n!==void 0?n:bCe};t.description!==void 0&&(r.description=t.description);let i={record:r,status:t.status};if(t.securityRoles&&t.securityRoles.length>0){if(t.status!=="Active")throw new Fo.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 n,r,i;let o=t.stages&&t.stages.length>0?t.stages.map(zz):[zz({id:(0,Ai.newId)(),name:"New Stage",steps:[]})],a={id:t.id&&t.id.trim()!==""?t.id:(0,Ai.newId)(),name:(n=t.name)!==null&&n!==void 0?n:"New business process flow",entityLogicalName:(r=t.entityLogicalName)!==null&&r!==void 0?r:"",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 n=Jm(t);(typeof n.id!="string"||n.id.trim()==="")&&(n.id=(0,Ai.newId)());for(let r of["stages","steps","actions","globalActions"]){let i=n[r];Array.isArray(i)&&i.forEach(o=>this.assignMissingIds(o))}return n}validate(t){let n=[],r=t.stages;if(r!==void 0&&!Array.isArray(r))return n.push((0,Mi.issue)("/stages","stages-must-be-array",`stages must be an array, got ${typeof r}`)),n;let i=Array.isArray(r)?r:[];i.length>30&&n.push((0,Mi.issue)("/stages","too-many-stages",`a BPF allows at most 30 stages, got ${i.length}`));let o=new Set,a=new Map;i.forEach((u,l)=>{let c=`/stages/${l}`,d=Jm(u),f=typeof d.id=="string"?d.id.trim():"";f===""?n.push((0,Mi.issue)(`${c}/id`,"stage-id-required","a stage needs an id")):a.has(f.toLowerCase())?n.push((0,Mi.issue)(`${c}/id`,"stage-id-duplicate",`two stages share the id '${d.id}' (also at /stages/${a.get(f.toLowerCase())})`)):a.set(f.toLowerCase(),l),typeof d.entityLogicalName=="string"&&d.entityLogicalName!==""&&o.add(d.entityLogicalName);let p=Array.isArray(d.steps)?d.steps:[];p.length===0&&n.push((0,Mi.issue)(`${c}/steps`,"stage-needs-step","a BPF stage must have at least one step")),p.length>30&&n.push((0,Mi.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 y=`${c}/steps/${g}`,b=typeof Jm(h).id=="string"?h.id.trim():"";b===""?n.push((0,Mi.issue)(`${y}/id`,"step-id-required","a step needs an id")):m.has(b.toLowerCase())?n.push((0,Mi.issue)(`${y}/id`,"step-id-duplicate",`two steps in this stage share the id '${h.id}'`)):m.set(b.toLowerCase(),g)}),d.branch&&!Wz(i,d.branch.nextStageId)&&n.push((0,Mi.issue)(`${c}/branch/nextStageId`,"branch-target-unknown",`branch nextStageId '${d.branch.nextStageId}' does not match any stage id`)),typeof d.nextStageId=="string"&&d.nextStageId!==""&&!Wz(i,d.nextStageId)&&n.push((0,Mi.issue)(`${c}/nextStageId`,"next-stage-unknown",`nextStageId '${d.nextStageId}' does not match any stage id`))}),o.size>5&&n.push((0,Mi.issue)("/stages","too-many-tables",`a BPF spans at most 5 tables, got ${o.size}`));let s=FCe(i);return s>=0&&n.push((0,Mi.issue)(`/stages/${s}/nextStageId`,"next-stage-cycle","the stage nextStageId links form a cycle; the flow must be acyclic")),n}};Xd.BpfAdapter=Tb;function FCe(e){let t=new Map(e.map(n=>[Jm(n).id,n]));for(let n=0;n<e.length;n+=1){let r=new Set,i=e[n];for(;i&&typeof i.nextStageId=="string"&&i.nextStageId!=="";){if(r.has(i.id))return n;r.add(i.id),i=t.get(i.nextStageId)}}return-1}function Wz(e,t){return e.some(n=>Jm(n).id===t)}function zz(e){var t,n;let r=e.steps&&e.steps.length>0?e.steps.map(Hz):[Hz({id:(0,Ai.newId)(),name:"New Step"})],i={id:e.id&&e.id.trim()!==""?e.id:(0,Ai.newId)(),name:(t=e.name)!==null&&t!==void 0?t:"New Stage",entityLogicalName:(n=e.entityLogicalName)!==null&&n!==void 0?n:"",steps:r};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 Hz(e){var t;let n={id:e.id&&e.id.trim()!==""?e.id:(0,Ai.newId)(),name:(t=e.name)!==null&&t!==void 0?t:"New Step"};return e.fieldName!==void 0&&(n.fieldName=e.fieldName),e.required!==void 0&&(n.required=e.required),n}function _I(e,t,n,r){return`${wI}<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="${r}" LanguageCode="${Mz}" /></sco:Collection><x:String x:Key="ProcessStepId">${r}</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="${n}" LanguageCode="${Mz}" /></sco:Collection><x:String x:Key="StageId">${n}</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 UCe(){return{adapter:new Tb,api:yCe.bpfApi,languageSensitive:!0}}Xd.bpfRegistration=UCe});var E9=C(Zd=>{"use strict";Object.defineProperty(Zd,"__esModule",{value:!0});Zd.environmentVariableRegistration=Zd.EnvironmentVariableAdapter=void 0;var Qm=cp(),OI=Jc(),TI=Y(),II=Eu(),qCe=Rs(),v9=ft(),Xm=ae(),BCe=new Map(Object.entries(OI.ENVIRONMENT_VARIABLE_TYPE_CODES).map(([e,t])=>[t,e]));function w9(e){var t,n,r,i,o;let a=new Map((n=(t=e.bag)===null||t===void 0?void 0:t.a)!==null&&n!==void 0?n:[]);return{displayname:e.name,description:e.description,defaultvalue:e.defaultValue,isrequired:e.isRequired,valueschema:(r=e.valueSchema)!==null&&r!==void 0?r:null,apiid:(i=e.connectorId)!==null&&i!==void 0?i:null,parameterkey:(o=e.parameterKey)!==null&&o!==void 0?o:null,"[email protected]":e.parentId?`/environmentvariabledefinitions(${(0,Xm.normalizeGuid)(e.parentId,"parentId")})`:null,...Object.fromEntries(Qm.ENVIRONMENT_VARIABLE_BAG_COLUMNS.map(s=>{var u;return[s,(u=a.get(s))!==null&&u!==void 0?u:null]}))}}var VCe=["displayname","description","defaultvalue","isrequired","valueschema"],Rb=class{toArtifact(t){return t}fromArtifact(t){return t}fromApiResponse(t){var n,r,i,o,a,s,u,l,c,d,f;let p=t??{},m=BCe.get(Number(p.type));if(m===void 0)throw new TI.InvalidArgumentError(`Unknown environment variable type ${JSON.stringify(p.type)}`);let h=(n=p.environmentvariabledefinition_environmentvariablevalue)===null||n===void 0?void 0:n[0],g=String((r=p.schemaname)!==null&&r!==void 0?r:"");return{id:(0,Xm.normalizeGuid)(String((i=p.environmentvariabledefinitionid)!==null&&i!==void 0?i:""),"environmentvariabledefinitionid"),schemaName:g,name:(o=p.displayname)!==null&&o!==void 0?o:g,description:(a=p.description)!==null&&a!==void 0?a:null,type:m,defaultValue:(s=p.defaultvalue)!==null&&s!==void 0?s:null,currentValue:h?{value:(u=h.value)!==null&&u!==void 0?u:null,id:(0,Xm.normalizeGuid)(String((l=h.environmentvariablevalueid)!==null&&l!==void 0?l:""),"environmentvariablevalueid")}:null,isRequired:p.isrequired===!0,valueSchema:(c=p.valueschema)!==null&&c!==void 0?c:null,connectorId:(d=p.apiid)!==null&&d!==void 0?d:null,parameterKey:(f=p.parameterkey)!==null&&f!==void 0?f:null,parentId:p._parentdefinitionid_value?(0,Xm.normalizeGuid)(p._parentdefinitionid_value,"_parentdefinitionid_value"):null,bag:{a:Qm.ENVIRONMENT_VARIABLE_BAG_COLUMNS.filter(y=>p[y]!==void 0&&p[y]!==null).map(y=>[y,p[y]])}}}toApiPayload(t,n){var r,i;let o=[...(0,Qm.environmentVariableShapeIssues)(t),...(0,Qm.environmentVariablePushIssues)(t,n)];if(o.length>0)throw new TI.ValidationError("environmentVariable",t.id,o);let a=GCe(t.currentValue,(r=n?.currentValue)!==null&&r!==void 0?r:null),s=!((i=n?.currentValue)===null||i===void 0)&&i.id?(0,Xm.normalizeGuid)(n.currentValue.id,"currentValue.id"):null,u=w9(t);if(!n){let f={schemaname:t.schemaName,type:OI.ENVIRONMENT_VARIABLE_TYPE_CODES[t.type]};for(let[p,m]of Object.entries(u))(m!==null||p==="isrequired")&&(f[p]=m);return{schemaName:t.schemaName,definition:f,heldRowId:s,value:a}}let l=w9(n),c=Object.keys(u).filter(f=>!(0,qCe.deepEqual)(u[f],l[f])),d;return c.length>0?d=Object.fromEntries(c.map(f=>[f,u[f]])):a.op==="none"&&(d=Object.fromEntries(VCe.map(f=>[f,u[f]]))),{schemaName:t.schemaName,...d?{definition:d}:{},heldRowId:s,value:a}}createDefault(t){var n,r,i,o,a,s,u,l,c,d,f,p;return{id:(n=t.id)!==null&&n!==void 0?n:(0,v9.newId)(),schemaName:(r=t.schemaName)!==null&&r!==void 0?r:"",name:(o=(i=t.name)!==null&&i!==void 0?i:t.schemaName)!==null&&o!==void 0?o:"",description:(a=t.description)!==null&&a!==void 0?a:null,type:(s=t.type)!==null&&s!==void 0?s:"string",defaultValue:(u=t.defaultValue)!==null&&u!==void 0?u:null,currentValue:t.currentValue?(0,II.cloneJson)(t.currentValue):null,isRequired:(l=t.isRequired)!==null&&l!==void 0?l:!1,valueSchema:(c=t.valueSchema)!==null&&c!==void 0?c:null,connectorId:(d=t.connectorId)!==null&&d!==void 0?d:null,parameterKey:(f=t.parameterKey)!==null&&f!==void 0?f:null,parentId:(p=t.parentId)!==null&&p!==void 0?p:null,bag:t.bag?(0,II.cloneJson)(t.bag):{a:[]}}}assignMissingIds(t){return t}validate(t,n){return(0,Qm.environmentVariableMutationIssues)(t,n)}normalize(t,n){var r,i;let o=t.currentValue;return!o||o.id!==void 0&&o.id!==null?t:{...t,currentValue:{...o,id:(i=(r=n?.currentValue)===null||r===void 0?void 0:r.id)!==null&&i!==void 0?i:(0,v9.newId)()}}}committed(t,n,r){let i=n.value;if(i.op==="none")return{artifact:t,baseline:t};if(r.intentPending){let o=i.op==="create"?null:(0,II.cloneJson)(i.baseline);return{artifact:t,baseline:{...t,currentValue:o}}}if(i.op==="delete"){let o={...t,currentValue:null};return{artifact:o,baseline:o}}return{artifact:t,baseline:t}}};Zd.EnvironmentVariableAdapter=Rb;function GCe(e,t){if(e===null)return t?{op:"delete",id:t.id,baseline:t}:{op:"none"};if(t===null){if(!e.id)throw new TI.InvalidArgumentError("environment variable value row has no id: normalize must run before the payload");return{op:"create",id:e.id,value:e.value}}return e.value===t.value?{op:"none"}:{op:"update",id:t.id,value:e.value,baseline:t}}function jCe(){return{adapter:new Rb,api:OI.environmentVariableApi,guardedDelete:!0}}Zd.environmentVariableRegistration=jCe});var DI=C(Pu=>{"use strict";Object.defineProperty(Pu,"__esModule",{value:!0});Pu.findConnectionReference=Pu.resolveConnectionReferences=Pu.connectionReferenceApi=void 0;var kb=Ke(),WCe=Jc(),zCe=il(),Ou=Y(),Tr=pe(),Du=ae(),HCe="connectionreferenceid,connectionreferencelogicalname,connectionreferencedisplayname,description,connectorid,connectionid,_customconnectorid_value,connectionparametersconfig,connectionparametersetconfig,promptingbehavior",ef="connectionreferences";async function KCe(e,t,n){var r,i,o;let a=(0,Du.normalizeGuid)(t,"id"),s=(r=n?.token)!==null&&r!==void 0?r:null;if(!(0,Tr.isVersionToken)(s))throw new Ou.SdkError(Tr.DELETE_NO_ETAG_CODE,`Refusing to delete connectionReference '${a}': no usable concurrency token is held for it, so the delete could not be made conditional and could remove what another writer changed. Fetch it first (fetchArtifact).`);let u=`/connectioninstances${(0,Du.odataQuery)([["$select","connectioninstanceid"],["$filter",`_connectionreferenceid_value eq ${a}`],["$top","1"]])}`,l=e.apiUrl(u),c=(0,Tr.ensureSuccess)(await e.get(u),l).body,d=c?.value;if(!Array.isArray(d)||!(0,kb.boundedPageComplete)(c,d.length))throw new Ou.ConnectionError(l,200,"the reference's connection instances could not be read, so whether the delete would cascade is unknown");if(d.length>0)throw new Ou.ArtifactInUseError("connectionReference",a,`Refusing to delete connectionReference '${a}': connection instances use it, and the platform would delete them with it. Nothing was deleted.`,d.map(h=>{var g;return{table:"connectioninstance",id:String((g=h.connectioninstanceid)!==null&&g!==void 0?g:"").toLowerCase()}}));let f=`/${ef}(${a})`,p=await e.delete(f,{headers:{"If-Match":s}});if(p.status===412)throw new Ou.VersionConflictError("connectionReference",a,s,null,"Another writer changed it since it was fetched; nothing was deleted.");let m=(o=(i=p.body)===null||i===void 0?void 0:i.error)===null||o===void 0?void 0:o.code;if(typeof m=="string"&&m.toLowerCase()==="0x8004f01f"){let h;try{h=await(0,zCe.resolveConnectionReferenceComponentType)(e)}catch{h=void 0}throw new Ou.ArtifactInUseError("connectionReference",a,`Refusing to delete connectionReference '${a}': another component (a flow, an app) depends on it; nothing was deleted. Remove the dependency first.`,await(0,WCe.readDeleteDependents)(e,a,h))}(0,Tr.ensureSuccess)(p,e.apiUrl(f))}Pu.connectionReferenceApi={async get(e,t){let n=(0,Du.normalizeGuid)(t,"id"),r=`/${ef}(${n})${(0,Du.odataQuery)([["$select",HCe]])}`,i=(0,Tr.ensureSuccess)(await e.get(r),e.apiUrl(r));return{raw:i.body,etag:(0,Tr.readEtag)(i)}},async list(e){let t=`/${ef}${(0,Du.odataQuery)([["$select","connectionreferenceid,connectionreferencelogicalname,connectionreferencedisplayname"]])}`;return(await(0,kb.collectPages)(e,t,"listArtifacts('connectionReference')")).map(r=>{var i,o,a;return{type:"connectionReference",id:String((i=r.connectionreferenceid)!==null&&i!==void 0?i:""),name:String((a=(o=r.connectionreferencedisplayname)!==null&&o!==void 0?o:r.connectionreferencelogicalname)!==null&&a!==void 0?a:""),isDirty:!1}})},async create(e,t,n){let r=t,i=(0,Tr.echoWrite)("connectionreferenceid"),o=`/${ef}${i.query}`,a=(0,Tr.ensureSuccess)(await e.post(o,(0,Tr.withClientMintedId)(r.columns,"connectionreferenceid",n),i.options),e.apiUrl(o));return{id:(0,Tr.resolveCreatedId)(a,"connectionreferenceid","connection reference",n),etag:(0,Tr.readEtag)(a)}},async update(e,t,n,r){let i=n,o=(0,Du.normalizeGuid)(t,"id"),a=(0,Tr.echoWrite)("connectionreferenceid",{"If-Match":(0,Tr.requireEtag)(r,"connectionReference",o)}),s=`/${ef}(${o})${a.query}`,u=(0,Tr.ensureSuccess)(await e.patch(s,i.columns,a.options),e.apiUrl(s));return{id:o,etag:(0,Tr.readEtag)(u)}},delete(e,t,n){return KCe(e,t,n)}};async function A9(e,t,n){let r=`/${ef}${(0,Du.odataQuery)([["$select","connectionreferenceid,connectionreferencelogicalname"],["$filter",`connectionreferencelogicalname eq '${(0,Du.odataLiteral)(t)}'`],...n!==void 0?[["$top",String(n)]]:[]])}`,i=e.apiUrl(r),o;if(n===void 0)o=await(0,kb.collectPages)(e,r,"resolveArtifact('connectionReference')");else{let a=(0,Tr.ensureSuccess)(await e.get(r),i).body;if(o=a?.value,Array.isArray(o)&&!(0,kb.boundedPageComplete)(a,o.length,n))throw new Ou.ConnectionError(i,200,"the list of connection references is incomplete (the answer says more rows exist), so it proves neither absence nor a single match")}if(!Array.isArray(o))throw new Ou.ConnectionError(i,200,"the response could not be read as a list of connection references");return o.map(a=>({id:String(a.connectionreferenceid),name:String(a.connectionreferencelogicalname)}))}Pu.resolveConnectionReferences=A9;async function JCe(e,t){let n=await A9(e,t,2);if(n.length>1)throw new Ou.AmbiguousArtifactError("connectionReference",t,n.length);return n.length===1?n[0].id:null}Pu.findConnectionReference=JCe});var N9=C(Uo=>{"use strict";Object.defineProperty(Uo,"__esModule",{value:!0});Uo.connectionReferenceRegistration=Uo.ConnectionReferenceAdapter=Uo.CONNECTION_REFERENCE_BAG_COLUMNS=void 0;var Zm=cp(),YCe=DI(),QCe=Y(),XCe=Eu(),ZCe=Rs(),eSe=ft(),PI=ae();Uo.CONNECTION_REFERENCE_BAG_COLUMNS=["connectionparametersconfig","connectionparametersetconfig","promptingbehavior"];var tSe=["connectionreferencedisplayname","description","connectorid","connectionid"];function tf(e,t,n){return{pointer:e,rule:t,message:n}}function C9(e){let t=e,n=[];return(0,Zm.isGuidText)(t.id)||n.push(tf("/id","guid","must be a GUID")),(typeof t.logicalName!="string"||t.logicalName.trim()==="")&&n.push(tf("/logicalName","required","must be a non-empty string (with a publisher prefix)")),typeof t.name!="string"&&n.push(tf("/name","type","must be a string")),n.push(...(0,Zm.requiredStringOrNull)(t.description,"/description")),(typeof t.connectorId!="string"||t.connectorId.trim()==="")&&n.push(tf("/connectorId","required","must be a non-empty string, e.g. /providers/Microsoft.PowerApps/apis/shared_sharepointonline")),n.push(...(0,Zm.requiredStringOrNull)(t.connectionId,"/connectionId","a connection id (a string)")),t.customConnectorId!==null&&t.customConnectorId!==void 0&&!(0,Zm.isGuidText)(t.customConnectorId)&&n.push(tf("/customConnectorId","guid","must be a GUID or null")),n.push(...(0,Zm.rowBagIssues)(t.bag,Uo.CONNECTION_REFERENCE_BAG_COLUMNS)),n}function S9(e){var t,n;let r=new Map((n=(t=e.bag)===null||t===void 0?void 0:t.a)!==null&&n!==void 0?n:[]);return{connectionreferencedisplayname:e.name,description:e.description,connectorid:e.connectorId,connectionid:e.connectionId,"[email protected]":e.customConnectorId?`/connectors(${(0,PI.normalizeGuid)(e.customConnectorId,"customConnectorId")})`:null,...Object.fromEntries(Uo.CONNECTION_REFERENCE_BAG_COLUMNS.map(i=>{var o;return[i,(o=r.get(i))!==null&&o!==void 0?o:null]}))}}var $b=class{toArtifact(t){return t}fromArtifact(t){return t}fromApiResponse(t){var n,r,i,o,a,s;let u=t??{},l=String((n=u.connectionreferencelogicalname)!==null&&n!==void 0?n:"");return{id:(0,PI.normalizeGuid)(String((r=u.connectionreferenceid)!==null&&r!==void 0?r:""),"connectionreferenceid"),logicalName:l,name:(i=u.connectionreferencedisplayname)!==null&&i!==void 0?i:l,description:(o=u.description)!==null&&o!==void 0?o:null,connectorId:String((a=u.connectorid)!==null&&a!==void 0?a:""),connectionId:(s=u.connectionid)!==null&&s!==void 0?s:null,customConnectorId:u._customconnectorid_value?(0,PI.normalizeGuid)(u._customconnectorid_value,"_customconnectorid_value"):null,bag:{a:Uo.CONNECTION_REFERENCE_BAG_COLUMNS.filter(c=>u[c]!==void 0&&u[c]!==null).map(c=>[c,u[c]])}}}toApiPayload(t,n){let r=C9(t);if(n&&t.logicalName!==n.logicalName&&r.push(tf("/logicalName","immutable-after-create","logicalName is fixed once the reference exists (the platform ignores a change)")),r.length>0)throw new QCe.ValidationError("connectionReference",t.id,r);let i=S9(t);if(!n){let u={connectionreferencelogicalname:t.logicalName};for(let[l,c]of Object.entries(i))c!==null&&(u[l]=c);return{columns:u}}let o=S9(n),a=Object.keys(i).filter(u=>!(0,ZCe.deepEqual)(i[u],o[u])),s=a.length>0?a:tSe;return{columns:Object.fromEntries(s.map(u=>[u,i[u]]))}}createDefault(t){var n,r,i,o,a,s,u,l;return{id:(n=t.id)!==null&&n!==void 0?n:(0,eSe.newId)(),logicalName:(r=t.logicalName)!==null&&r!==void 0?r:"",name:(o=(i=t.name)!==null&&i!==void 0?i:t.logicalName)!==null&&o!==void 0?o:"",description:(a=t.description)!==null&&a!==void 0?a:null,connectorId:(s=t.connectorId)!==null&&s!==void 0?s:"",connectionId:(u=t.connectionId)!==null&&u!==void 0?u:null,customConnectorId:(l=t.customConnectorId)!==null&&l!==void 0?l:null,bag:t.bag?(0,XCe.cloneJson)(t.bag):{a:[]}}}assignMissingIds(t){return t}validate(t){return C9(t)}};Uo.ConnectionReferenceAdapter=$b;function nSe(){return{adapter:new $b,api:YCe.connectionReferenceApi,guardedDelete:!0}}Uo.connectionReferenceRegistration=nSe});var T9=C(Ta=>{"use strict";Object.defineProperty(Ta,"__esModule",{value:!0});Ta.fieldSecurityProfilePushIssues=Ta.fieldSecurityProfileShapeIssues=Ta.permissionIdentity=Ta.permissionKey=void 0;var RI=cp(),rSe=o0(),iSe=/^[a-z_][a-z0-9_]*$/,_9=["none","oneRecord","allRecords"],oSe=["read","create","update"];function Ci(e,t,n){return{pointer:e,rule:t,message:n}}function nf(e){return`${e.table}\0${e.column}`}Ta.permissionKey=nf;function eh(e){var t;return(t=(0,rSe.canonicalGuid)(e))!==null&&t!==void 0?t:String(e??"").toLowerCase()}Ta.permissionIdentity=eh;function I9(e){let t=e,n=[];if((0,RI.isGuidText)(t.id)||n.push(Ci("/id","guid","must be a GUID")),typeof t.name!="string"&&n.push(Ci("/name","type","must be a string")),n.push(...(0,RI.requiredStringOrNull)(t.description,"/description")),!Array.isArray(t.permissions))return n.push(Ci("/permissions","type","must be an array of permissions")),n;let r=new Map;return t.permissions.forEach((i,o)=>{let a=`/permissions/${o}`;if(!i||typeof i!="object"||Array.isArray(i)){n.push(Ci(a,"type","must be a permission object"));return}let s=i;for(let u of["table","column"])s[u]!==void 0&&(typeof s[u]!="string"||!iSe.test(s[u]))&&n.push(Ci(`${a}/${u}`,"logical-name",`must be a lower-case logical name, e.g. contoso_${u==="table"?"employee":"salary"}`));for(let u of oSe)s[u]!==void 0&&typeof s[u]!="boolean"&&n.push(Ci(`${a}/${u}`,"type","must be true or false"));if(s.readUnmasked!==void 0&&!_9.includes(s.readUnmasked)&&n.push(Ci(`${a}/readUnmasked`,"type",`must be one of ${_9.join(", ")}`)),s.id!==void 0&&!(0,RI.isGuidText)(s.id)&&n.push(Ci(`${a}/id`,"guid","must be a GUID")),typeof s.table=="string"&&typeof s.column=="string"){let u=nf(s);r.has(u)?n.push(Ci(a,"duplicate-permission",`${s.table}.${s.column} already has a permission at /permissions/${r.get(u)}; a profile holds one per column`)):r.set(u,o)}}),n}Ta.fieldSecurityProfileShapeIssues=I9;function aSe(e,t){var n;let r=I9(e);if((typeof e.name!="string"||e.name.trim()==="")&&r.push(Ci("/name","name-required","a field security profile needs a non-empty name")),!Array.isArray(e.permissions))return r;let i=((n=t?.permissions)!==null&&n!==void 0?n:[]).filter(s=>s&&typeof s.id=="string"),o=new Map(i.map(s=>[eh(s.id),s])),a=new Map(i.map(s=>[nf(s),s]));return e.permissions.forEach((s,u)=>{var l,c;let d=`/permissions/${u}`;if(!s||typeof s!="object")return;if(typeof s.table!="string"||typeof s.column!="string"){r.push(Ci(d,"permission-key-required","every permission needs its table and column"));return}let f=typeof s.id=="string"?o.get(eh(s.id)):void 0;f&&nf(f)!==nf(s)&&r.push(Ci(d,"permission-key-immutable",`this permission is ${f.table}.${f.column} on the server; its table and column cannot change (the platform would ignore it). Remove it and add a new permission instead.`));let p=a.get(nf(s));p&&typeof s.id=="string"&&eh(s.id)!==eh(p.id)&&r.push(Ci(`${d}/id`,"permission-id-conflict",`${s.table}.${s.column} is the server row '${p.id}'; remove the id (the SDK manages it) instead of setting another`));let m=(l=p?.readUnmasked)!==null&&l!==void 0?l:"none";((c=s.readUnmasked)!==null&&c!==void 0?c:"none")!==m&&r.push(Ci(`${d}/readUnmasked`,"read-unmasked-not-authored","the read-unmasked level is carried as fetched, not authored: it needs a masking rule on the column, which this SDK does not manage. Leave it as fetched (absent for a new permission)."))}),r}Ta.fieldSecurityProfilePushIssues=aSe});var D9=C(rf=>{"use strict";Object.defineProperty(rf,"__esModule",{value:!0});rf.fieldSecurityProfileRegistration=rf.FieldSecurityProfileAdapter=void 0;var qo=T9(),sSe=s0(),$I=o0(),uSe=Y(),kI=ft(),O9=ae(),lo=e=>e===!0?$I.ALLOWED:$I.NOT_ALLOWED;function lSe(e,t){return e.table<t.table?-1:e.table>t.table?1:e.column<t.column?-1:e.column>t.column?1:0}var Lb=class{toArtifact(t){return t}fromArtifact(t){return t}fromApiResponse(t){var n;let r=t??{},i=(0,O9.normalizeGuid)(String((n=r.fieldsecurityprofileid)!==null&&n!==void 0?n:""),"fieldsecurityprofileid"),a=(Array.isArray(r.lk_fieldpermission_fieldsecurityprofileid)?r.lk_fieldpermission_fieldsecurityprofileid:[]).map(s=>{var u,l,c;return(0,$I.toFieldPermission)({id:(0,O9.normalizeGuid)(String((u=s.fieldpermissionid)!==null&&u!==void 0?u:""),"fieldpermissionid"),token:"",table:String((l=s.entityname)!==null&&l!==void 0?l:""),column:String((c=s.attributelogicalname)!==null&&c!==void 0?c:""),canread:s.canread,cancreate:s.cancreate,canupdate:s.canupdate,canreadunmasked:s.canreadunmasked},{profileId:i})}).sort(lSe);return{id:i,name:typeof r.name=="string"?r.name:"",description:typeof r.description=="string"?r.description:null,permissions:a}}toApiPayload(t,n){let r=(0,qo.fieldSecurityProfilePushIssues)(t,n);if(r.length>0)throw new uSe.ValidationError("fieldSecurityProfile",t.id,r);let i=l=>{var c;return{id:(0,qo.permissionIdentity)((c=l.id)!==null&&c!==void 0?c:(0,kI.newId)()),table:l.table,column:l.column,canread:lo(l.read),cancreate:lo(l.create),canupdate:lo(l.update)}};if(!n)return{profile:{name:t.name,description:t.description},creates:t.permissions.map(i),updates:[],deletes:[]};let o={};t.name!==n.name&&(o.name=t.name),t.description!==n.description&&(o.description=t.description);let a=new Map(n.permissions.map(l=>[(0,qo.permissionKey)(l),l])),s=new Set(t.permissions.map(l=>(0,qo.permissionKey)(l))),u={profile:o,creates:[],updates:[],deletes:[]};for(let l of t.permissions){let c=a.get((0,qo.permissionKey)(l));if(!c){u.creates.push(i(l));continue}let d={};lo(l.read)!==lo(c.read)&&(d.canread=lo(l.read)),lo(l.create)!==lo(c.create)&&(d.cancreate=lo(l.create)),lo(l.update)!==lo(c.update)&&(d.canupdate=lo(l.update)),Object.keys(d).length>0&&u.updates.push({id:(0,qo.permissionIdentity)(c.id),table:l.table,column:l.column,set:d})}for(let l of n.permissions)s.has((0,qo.permissionKey)(l))||u.deletes.push({id:(0,qo.permissionIdentity)(l.id),table:l.table,column:l.column});return u}createDefault(t){var n,r,i,o;return{id:(n=t.id)!==null&&n!==void 0?n:(0,kI.newId)(),name:(r=t.name)!==null&&r!==void 0?r:"",description:(i=t.description)!==null&&i!==void 0?i:null,permissions:((o=t.permissions)!==null&&o!==void 0?o:[]).map(a=>{var s,u,l;return{...a,read:(s=a.read)!==null&&s!==void 0?s:!1,create:(u=a.create)!==null&&u!==void 0?u:!1,update:(l=a.update)!==null&&l!==void 0?l:!1}})}}assignMissingIds(t){return t}validate(t){return(0,qo.fieldSecurityProfileShapeIssues)(t)}normalize(t,n){var r;if(!Array.isArray(t.permissions))return t;let i=new Map(((r=n?.permissions)!==null&&r!==void 0?r:[]).filter(s=>s&&typeof s.id=="string").map(s=>[(0,qo.permissionKey)(s),s.id])),o=!1,a=t.permissions.map(s=>{var u;return!s||typeof s!="object"||typeof s.table!="string"||typeof s.column!="string"||s.id!==void 0&&s.id!==null&&s.id!==""?s:(o=!0,{...s,id:(u=i.get((0,qo.permissionKey)(s)))!==null&&u!==void 0?u:(0,kI.newId)()})});return o?{...t,permissions:a}:t}};rf.FieldSecurityProfileAdapter=Lb;function cSe(){return{adapter:new Lb,api:sSe.fieldSecurityProfileApi,guardedDelete:!0}}rf.fieldSecurityProfileRegistration=cSe});var k9=C(of=>{"use strict";Object.defineProperty(of,"__esModule",{value:!0});of.customApiPushIssues=of.customApiMutationIssues=void 0;var Oa=v0(),LI=/^\{?[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}\}?$/,xI=["requestParameters","responseProperties"];function jt(e,t,n){return{pointer:e,rule:t,message:n}}var MI=(e,t)=>typeof t=="string"&&Object.prototype.hasOwnProperty.call(e,t),dSe=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),P9=e=>e==null||typeof e=="string";function R9(e){let t=e,n=[];t.id!==void 0&&(typeof t.id!="string"||!LI.test(t.id))&&n.push(jt("/id","guid","must be a GUID"));for(let r of["uniqueName","name","displayName","description"])t[r]!==void 0&&typeof t[r]!="string"&&n.push(jt(`/${r}`,"type","must be a string"));for(let r of["boundEntityLogicalName","executePrivilegeName"])P9(t[r])||n.push(jt(`/${r}`,"type","must be a string or null"));t.pluginTypeId!==void 0&&t.pluginTypeId!==null&&(typeof t.pluginTypeId!="string"||!LI.test(t.pluginTypeId))&&n.push(jt("/pluginTypeId","guid","must be a GUID or null")),t.binding!==void 0&&!MI(Oa.CUSTOM_API_BINDING_CODES,t.binding)&&n.push(jt("/binding","enum",`must be one of ${Object.keys(Oa.CUSTOM_API_BINDING_CODES).join(", ")}`)),t.allowedProcessingSteps!==void 0&&!MI(Oa.CUSTOM_API_STEP_CODES,t.allowedProcessingSteps)&&n.push(jt("/allowedProcessingSteps","enum",`must be one of ${Object.keys(Oa.CUSTOM_API_STEP_CODES).join(", ")}`));for(let r of["isFunction","isPrivate","enabledForWorkflow"])t[r]!==void 0&&typeof t[r]!="boolean"&&n.push(jt(`/${r}`,"type","must be true or false"));for(let r of xI){let i=t[r];if(i===void 0)continue;if(!Array.isArray(i)){n.push(jt(`/${r}`,"type","must be an array"));continue}let o=new Map;i.forEach((a,s)=>{let u=`/${r}/${s}`;if(!dSe(a)){n.push(jt(u,"type","must be an object"));return}a.id!==void 0&&(typeof a.id!="string"||!LI.test(a.id))&&n.push(jt(`${u}/id`,"guid","must be a GUID (or omitted, and the SDK mints one)")),a.uniqueName!==void 0&&typeof a.uniqueName!="string"&&n.push(jt(`${u}/uniqueName`,"type","must be a string")),a.type!==void 0&&!MI(Oa.CUSTOM_API_TYPE_CODES,a.type)&&n.push(jt(`${u}/type`,"enum",`must be one of ${Object.keys(Oa.CUSTOM_API_TYPE_CODES).join(", ")}`)),a.isOptional!==void 0&&typeof a.isOptional!="boolean"&&n.push(jt(`${u}/isOptional`,"type","must be true or false"));for(let l of["entityLogicalName","name","displayName","description"])P9(a[l])||n.push(jt(`${u}/${l}`,"type","must be a string or null"));if(typeof a.uniqueName=="string"&&a.uniqueName!==""){let l=a.uniqueName.toLowerCase(),c=o.get(l);c!==void 0?n.push(jt(`${u}/uniqueName`,"duplicate-unique-name",`'${a.uniqueName}' is already used by ${r}/${c} (names compare ignoring case)`)):o.set(l,s)}})}return n}function fSe(e,t){return R9(e)}of.customApiMutationIssues=fSe;var pSe=["uniqueName","binding","boundEntityLogicalName","isFunction","allowedProcessingSteps","enabledForWorkflow"],mSe=["uniqueName","type","isOptional","entityLogicalName"];function hSe(e,t){var n,r,i,o;let a=R9(e);for(let u of["uniqueName","name","displayName","description"])(typeof e[u]!="string"||e[u].trim()==="")&&a.push(jt(`/${u}`,"required","must be a non-empty string"));e.binding!=="global"&&(!e.boundEntityLogicalName||e.boundEntityLogicalName.trim()==="")&&a.push(jt("/boundEntityLogicalName","bound-entity-required",`an '${e.binding}' binding needs a table`));for(let u of xI)((n=e[u])!==null&&n!==void 0?n:[]).forEach((l,c)=>{(typeof l.uniqueName!="string"||l.uniqueName.trim()==="")&&a.push(jt(`/${u}/${c}/uniqueName`,"required","must be a non-empty string")),l.type===void 0&&a.push(jt(`/${u}/${c}/type`,"required","must be set (the platform would default it to boolean)"))});if((t?e.pluginTypeId!==t.pluginTypeId:((r=e.pluginTypeId)!==null&&r!==void 0?r:null)!==null)&&a.push(jt("/pluginTypeId","plugin-type-read-only","the plug-in type is read-only in this SDK (definitions only); bind a plug-in with the Plug-in Registration tool or the maker portal")),!t)return a;(0,Oa.canonicalGuid)(e.id)!==(0,Oa.canonicalGuid)(t.id)&&a.push(jt("/id","immutable-after-create","is the id of the API this artifact was fetched from and cannot change; to work on another API, fetch it"));for(let u of pSe)e[u]!==t[u]&&a.push(jt(`/${String(u)}`,"immutable-after-create","cannot be changed once the API exists (the platform ignores the change). Deleting and re-creating the API makes a different API for its callers and for anything attached to it; the SDK does not do it for you"));for(let u of xI){let l=new Map(((i=t[u])!==null&&i!==void 0?i:[]).map(c=>[(0,Oa.canonicalGuid)(c.id),c]));((o=e[u])!==null&&o!==void 0?o:[]).forEach((c,d)=>{var f,p;let m=l.get((0,Oa.canonicalGuid)(c.id));if(!(!m||c.id===void 0))for(let h of mSe){let g=(f=c[h])!==null&&f!==void 0?f:null,y=(p=m[h])!==null&&p!==void 0?p:null;(h==="isOptional"?!!g!=!!y:g!==y)&&a.push(jt(`/${u}/${d}/${h}`,"immutable-after-create","cannot be changed once the row exists (the platform ignores the change): remove it and add a new one \u2014 the push deletes and re-creates it in one change set"))}})}return a}of.customApiPushIssues=hSe});var U9=C(Da=>{"use strict";Object.defineProperty(Da,"__esModule",{value:!0});Da.customApiRegistration=Da.CustomApiAdapter=Da.CUSTOM_API_CHILDREN=void 0;var $9=k9(),gSe=C0(),xi=v0(),ySe=Y(),L9=Eu(),FI=Rs(),Mb=ft(),Hl=ae();Da.CUSTOM_API_CHILDREN=[{list:"requestParameters",kind:"requestParameter",nav:"CustomAPIRequestParameters",set:"customapirequestparameters",pk:"customapirequestparameterid"},{list:"responseProperties",kind:"responseProperty",nav:"CustomAPIResponseProperties",set:"customapiresponseproperties",pk:"customapiresponsepropertyid"}];var bSe=["name","displayname","description","isprivate","executeprivilegename"],vSe=["name","isprivate","executeprivilegename"],M9=new Set(["displayname","description"]),wSe=["name","displayname","description"];function x9(e,t){let n=e.uniqueName.toLowerCase(),r=t.uniqueName.toLowerCase();if(n!==r)return n<r?-1:1;let i=String(e.id),o=String(t.id);return i<o?-1:i>o?1:0}var Cs=e=>typeof e=="string"?e:null;function F9(e,t,n){var r,i;return{id:(0,Hl.normalizeGuid)(String((r=e[t])!==null&&r!==void 0?r:""),t),uniqueName:String((i=e.uniquename)!==null&&i!==void 0?i:""),type:(0,xi.optionName)(xi.CUSTOM_API_TYPE_CODES,e.type),...n?{isOptional:e.isoptional===!0}:{},entityLogicalName:Cs(e.logicalentityname),name:Cs(e.name),displayName:Cs(e.displayname),description:Cs(e.description)}}function UI(e){var t,n;return{uniquename:e.uniqueName,name:e.name,displayname:e.displayName,description:e.description,bindingtype:xi.CUSTOM_API_BINDING_CODES[e.binding],boundentitylogicalname:(t=e.boundEntityLogicalName)!==null&&t!==void 0?t:null,isfunction:e.isFunction,isprivate:e.isPrivate,allowedcustomprocessingsteptype:xi.CUSTOM_API_STEP_CODES[e.allowedProcessingSteps],workflowsdkstepenabled:e.enabledForWorkflow,executeprivilegename:(n=e.executePrivilegeName)!==null&&n!==void 0?n:null}}function xb(e,t){var n,r,i,o;return{uniquename:e.uniqueName,name:(n=e.name)!==null&&n!==void 0?n:null,displayname:(r=e.displayName)!==null&&r!==void 0?r:null,description:(i=e.description)!==null&&i!==void 0?i:null,type:xi.CUSTOM_API_TYPE_CODES[e.type],logicalentityname:(o=e.entityLogicalName)!==null&&o!==void 0?o:null,...t==="requestParameters"?{isoptional:e.isOptional===!0}:{}}}var Fb=class{toArtifact(t){return t}fromArtifact(t){return t}fromApiResponse(t){var n,r,i,o,a,s,u;let l=t??{},c=String((n=l.uniquename)!==null&&n!==void 0?n:"");return{id:(0,Hl.normalizeGuid)(String((r=l.customapiid)!==null&&r!==void 0?r:""),"customapiid"),uniqueName:c,name:(i=Cs(l.name))!==null&&i!==void 0?i:c,displayName:(o=Cs(l.displayname))!==null&&o!==void 0?o:"",description:(a=Cs(l.description))!==null&&a!==void 0?a:"",binding:(0,xi.optionName)(xi.CUSTOM_API_BINDING_CODES,l.bindingtype),boundEntityLogicalName:Cs(l.boundentitylogicalname),isFunction:l.isfunction===!0,isPrivate:l.isprivate===!0,allowedProcessingSteps:(0,xi.optionName)(xi.CUSTOM_API_STEP_CODES,l.allowedcustomprocessingsteptype),enabledForWorkflow:l.workflowsdkstepenabled===!0,executePrivilegeName:Cs(l.executeprivilegename),pluginTypeId:l._plugintypeid_value?(0,Hl.normalizeGuid)(l._plugintypeid_value,"_plugintypeid_value"):null,requestParameters:((s=l.CustomAPIRequestParameters)!==null&&s!==void 0?s:[]).map(d=>F9(d,"customapirequestparameterid",!0)).sort(x9),responseProperties:((u=l.CustomAPIResponseProperties)!==null&&u!==void 0?u:[]).map(d=>F9(d,"customapiresponsepropertyid",!1)).sort(x9)}}toApiPayload(t,n){var r,i;let o=(0,$9.customApiPushIssues)(t,n);if(o.length>0)throw new ySe.ValidationError("customApi",t.id,o);let a=t.isFunction&&t.responseProperties.length===0?[`customApi '${t.uniqueName}' is a function with no response property: a function needs at least one response property to be callable (it is not listed in $metadata and a call answers 404); right after the last one is removed, a call may still succeed for a while.`]:[],s={deletes:[],posts:[],patches:[],held:{requestParameters:((r=n?.requestParameters)!==null&&r!==void 0?r:[]).map(d=>(0,xi.canonicalGuid)(String(d.id))),responseProperties:((i=n?.responseProperties)!==null&&i!==void 0?i:[]).map(d=>(0,xi.canonicalGuid)(String(d.id)))},labelEdits:[],warnings:a};if(!n)return s.create={customapiid:(0,Hl.normalizeGuid)(t.id,"id"),...UI(t),...Object.fromEntries(Da.CUSTOM_API_CHILDREN.map(({list:d,nav:f,pk:p})=>[f,t[d].map(m=>({[p]:(0,Hl.normalizeGuid)(String(m.id),`${d}.id`),...xb(m,d)}))]))},s;let u=UI(t),l=UI(n),c=bSe.filter(d=>!(0,FI.deepEqual)(u[d],l[d]));c.length>0&&(s.api=Object.fromEntries(c.map(d=>[d,u[d]])),s.labelEdits.push(...c.filter(d=>M9.has(d)).map(d=>`/${d==="displayname"?"displayName":"description"}`)));for(let{list:d,kind:f}of Da.CUSTOM_API_CHILDREN){let p=new Map(n[d].map(h=>[(0,xi.canonicalGuid)(String(h.id)),h])),m=new Map;t[d].forEach((h,g)=>{let y=(0,xi.canonicalGuid)((0,Hl.normalizeGuid)(String(h.id),`${d}.id`));m.set(y,h);let b=p.get(y);if(!b){s.posts.push({kind:f,id:y,body:{[f==="requestParameter"?"customapirequestparameterid":"customapiresponsepropertyid"]:y,...xb(h,d),"[email protected]":`/customapis(${(0,Hl.normalizeGuid)(t.id,"id")})`}});return}let E=xb(h,d),w=xb(b,d),_=wSe.filter(I=>!(0,FI.deepEqual)(E[I],w[I]));_.length>0&&(s.patches.push({kind:f,id:y,body:Object.fromEntries(_.map(I=>[I,E[I]]))}),s.labelEdits.push(..._.filter(I=>M9.has(I)).map(I=>`/${d}/${g}/${I==="displayname"?"displayName":"description"}`)))});for(let h of p.keys())m.has(h)||s.deletes.push({kind:f,id:h})}return!s.api&&s.posts.length+s.patches.length+s.deletes.length===0&&(s.api=Object.fromEntries(vSe.map(d=>[d,u[d]]))),s}createDefault(t){var n,r,i,o,a,s,u,l,c,d,f,p,m,h,g;let y=(n=t.uniqueName)!==null&&n!==void 0?n:"",b=(r=t.displayName)!==null&&r!==void 0?r:y;return{id:(i=t.id)!==null&&i!==void 0?i:(0,Mb.newId)(),uniqueName:y,name:(o=t.name)!==null&&o!==void 0?o:y,displayName:b,description:(a=t.description)!==null&&a!==void 0?a:b,binding:(s=t.binding)!==null&&s!==void 0?s:"global",boundEntityLogicalName:(u=t.boundEntityLogicalName)!==null&&u!==void 0?u:null,isFunction:(l=t.isFunction)!==null&&l!==void 0?l:!1,isPrivate:(c=t.isPrivate)!==null&&c!==void 0?c:!1,allowedProcessingSteps:(d=t.allowedProcessingSteps)!==null&&d!==void 0?d:"none",enabledForWorkflow:(f=t.enabledForWorkflow)!==null&&f!==void 0?f:!1,executePrivilegeName:(p=t.executePrivilegeName)!==null&&p!==void 0?p:null,pluginTypeId:(m=t.pluginTypeId)!==null&&m!==void 0?m:null,requestParameters:(0,L9.cloneJson)((h=t.requestParameters)!==null&&h!==void 0?h:[]),responseProperties:(0,L9.cloneJson)((g=t.responseProperties)!==null&&g!==void 0?g:[])}}assignMissingIds(t){return(0,Mb.assignMissingIds)(t)}validate(t,n){return(0,$9.customApiMutationIssues)(t,n)}normalize(t){var n,r;let i=!1,o=t.id?t.id:(i=!0,(0,Mb.newId)()),a=(l,c)=>{let d={...l};return d.id||(d.id=(0,Mb.newId)()),d.name===void 0&&(d.name=`${t.uniqueName}.${l.uniqueName}`),d.displayName===void 0&&(d.displayName=l.uniqueName),d.description===void 0&&(d.description=d.displayName),c==="requestParameters"&&d.isOptional===void 0&&(d.isOptional=!1),(0,FI.deepEqual)(d,l)||(i=!0),d},s=((n=t.requestParameters)!==null&&n!==void 0?n:[]).map(l=>a(l,"requestParameters")),u=((r=t.responseProperties)!==null&&r!==void 0?r:[]).map(l=>a(l,"responseProperties"));return(!t.requestParameters||!t.responseProperties)&&(i=!0),i?{...t,id:o,requestParameters:s,responseProperties:u}:t}};Da.CustomApiAdapter=Fb;function ESe(){return{adapter:new Fb,api:gSe.customApiApi,guardedDelete:!0}}Da.customApiRegistration=ESe});var B9=C(Pa=>{"use strict";Object.defineProperty(Pa,"__esModule",{value:!0});Pa.pushIssues=Pa.shapeIssues=Pa.MATCHES=void 0;Pa.MATCHES=["exact","firstCharacters","lastCharacters","sameDate","sameDateAndTime","exactChoiceLabel","exactChoiceValue"];var ASe=["published","unpublished","publishing"],q9=/^\{?[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}\}?$/,af=e=>e.toLowerCase().replace(/^\{|\}$/g,"");function Ut(e,t,n){return{pointer:e,rule:t,message:n}}var th=e=>typeof e=="string"&&e.trim()!=="";function CSe(e){let t=e,n=[];(typeof t.id!="string"||!q9.test(t.id))&&n.push(Ut("/id","guid","must be the rule's GUID (adapter-managed)")),th(t.name)||n.push(Ut("/name","required",'must be a non-empty string, e.g. "Contacts with the same email"')),th(t.entityLogicalName)||n.push(Ut("/entityLogicalName","required",'must be a table logical name, e.g. "contact"')),t.description!==void 0&&t.description!==null&&typeof t.description!="string"&&n.push(Ut("/description","type","must be a string or null")),t.matchingEntityLogicalName!==void 0&&!th(t.matchingEntityLogicalName)&&n.push(Ut("/matchingEntityLogicalName","type","must be a table logical name, or omitted"));for(let i of["caseSensitive","excludeInactiveRecords"])t[i]!==void 0&&typeof t[i]!="boolean"&&n.push(Ut(`/${i}`,"type","must be a boolean"));if(ASe.includes(t.status)||n.push(Ut("/status","enum","must be 'published' or 'unpublished'")),!Array.isArray(t.conditions))return n.push({...Ut("/conditions","type","must be an array of conditions"),fatal:!0}),n;let r=new Set;return t.conditions.forEach((i,o)=>{let a=`/conditions/${o}`;if(i===null||typeof i!="object"||Array.isArray(i)){n.push(Ut(a,"type","must be an object { column, match }"));return}let s=i;s.id!==void 0&&(typeof s.id!="string"||!q9.test(s.id)?n.push(Ut(`${a}/id`,"guid","must be a GUID (adapter-managed \u2014 omit it)")):r.has(af(s.id))?n.push(Ut(`${a}/id`,"duplicate-condition-id","another condition has the same id")):r.add(af(s.id))),th(s.column)||n.push(Ut(`${a}/column`,"required",'must be a column logical name, e.g. "emailaddress1"')),s.matchingColumn!==void 0&&!th(s.matchingColumn)&&n.push(Ut(`${a}/matchingColumn`,"type","must be a column logical name, or omitted")),Pa.MATCHES.includes(s.match)||n.push(Ut(`${a}/match`,"enum",`must be one of ${Pa.MATCHES.join(", ")}`)),s.characters!==void 0&&s.characters!==null&&!(typeof s.characters=="number"&&Number.isInteger(s.characters)&&s.characters>0)&&n.push(Ut(`${a}/characters`,"type","must be a positive integer, or null")),s.ignoreBlankValues!==void 0&&typeof s.ignoreBlankValues!="boolean"&&n.push(Ut(`${a}/ignoreBlankValues`,"type","must be a boolean"))}),n}Pa.shapeIssues=CSe;function SSe(e,t){var n,r,i,o;let a=[],s=e.entityLogicalName,u=(n=e.matchingEntityLogicalName)!==null&&n!==void 0?n:s;if(e.conditions.forEach((l,c)=>{let d=`/conditions/${c}`;(l.match==="firstCharacters"||l.match==="lastCharacters")&&!(typeof l.characters=="number"&&l.characters>0)&&a.push(Ut(`${d}/characters`,"characters-required",`'${l.match}' needs how many characters, e.g. 3`)),u===s&&l.matchingColumn!==void 0&&l.matchingColumn!==l.column&&a.push(Ut(`${d}/matchingColumn`,"matching-column-same-table","a same-table rule compares a column with itself"))}),e.status==="published"&&e.conditions.length===0&&a.push(Ut("/status","published-without-conditions","a published rule needs at least one condition")),(e.status==="publishing"||t?.status==="publishing")&&a.push(Ut("/status","status-publishing","'publishing' is never authored, and a rule fetched while it was publishing must be re-fetched before a push")),t){af(String((r=e.id)!==null&&r!==void 0?r:""))!==af(String((i=t.id)!==null&&i!==void 0?i:""))&&a.push(Ut("/id","immutable-after-create","the rule's id is fixed once it exists \u2014 to copy a rule, create a new one")),e.entityLogicalName!==t.entityLogicalName&&a.push(Ut("/entityLogicalName","immutable-after-create","the table is fixed once the rule exists")),u!==((o=t.matchingEntityLogicalName)!==null&&o!==void 0?o:t.entityLogicalName)&&a.push(Ut("/matchingEntityLogicalName","immutable-after-create","the matching table is fixed once the rule exists"));let l=new Set(t.conditions.map(d=>{var f;return af((f=d.id)!==null&&f!==void 0?f:"")})),c=e.conditions.some(d=>!d.id||!l.has(af(d.id)));e.name!==t.name&&t.conditions.length===0&&!c&&a.push(Ut("/name","rename-empty-rule","a rule with no condition can be renamed only in a push that also adds one"))}return a}Pa.pushIssues=SSe});var G9=C(uf=>{"use strict";Object.defineProperty(uf,"__esModule",{value:!0});uf.duplicateRuleRegistration=uf.DuplicateRuleAdapter=void 0;var qI=B9(),NSe=S0(),sf=lC(),_Se=Y(),ISe=Eu(),GI=ft(),V9=e=>e.toLowerCase().replace(/^\{|\}$/g,""),TSe="Microsoft.Dynamics.CRM.duplicaterule",OSe="Microsoft.Dynamics.CRM.duplicaterulecondition";function DSe(e){var t,n,r;return{...e,id:e.id?V9(e.id):(0,GI.newId)(),matchingColumn:(t=e.matchingColumn)!==null&&t!==void 0?t:e.column,characters:(n=e.characters)!==null&&n!==void 0?n:null,ignoreBlankValues:(r=e.ignoreBlankValues)!==null&&r!==void 0?r:!1}}function BI(e){var t,n,r,i;return{...e,description:(t=e.description)!==null&&t!==void 0?t:null,matchingEntityLogicalName:(n=e.matchingEntityLogicalName)!==null&&n!==void 0?n:e.entityLogicalName,caseSensitive:(r=e.caseSensitive)!==null&&r!==void 0?r:!1,excludeInactiveRecords:(i=e.excludeInactiveRecords)!==null&&i!==void 0?i:!1,conditions:e.conditions.map(DSe)}}function nh(e){var t,n;return{duplicateruleconditionid:e.id,baseattributename:e.column,matchingattributename:(t=e.matchingColumn)!==null&&t!==void 0?t:e.column,operatorcode:sf.MATCH_CODES[e.match],...e.characters!==null&&e.characters!==void 0?{operatorparam:e.characters}:{},ignoreblankvalues:(n=e.ignoreBlankValues)!==null&&n!==void 0?n:!1}}var PSe=(e,t)=>JSON.stringify(nh(e))===JSON.stringify(nh(t)),VI=(e,t)=>e.id<t.id?-1:e.id>t.id?1:0,Ub=class{toArtifact(t){return t}fromArtifact(t){return t}fromApiResponse(t){var n;return(0,sf.projectAggregate)(t,String((n=t?.duplicateruleid)!==null&&n!==void 0?n:""))}toApiPayload(t,n){let r=(0,qI.shapeIssues)(t);if(r.length===0&&r.push(...(0,qI.pushIssues)(t,n)),r.length>0)throw new _Se.ValidationError("duplicateRule",t.id,r);let i=BI(t),o=V9(i.id);if(!n)return{desired:i,ops:[{method:"POST",path:`/${sf.DUPLICATE_RULE_SET}`,body:{duplicateruleid:o,name:i.name,...i.description!==null?{description:i.description}:{},baseentityname:i.entityLogicalName,matchingentityname:i.matchingEntityLogicalName,iscasesensitive:i.caseSensitive,excludeinactiverecords:i.excludeInactiveRecords,[sf.CONDITIONS_NAV]:i.conditions.map(nh)}}],statusAfterContent:"unpublished"};let a=BI(n),s=a.status==="published"?"published":"unpublished",u=new Map(a.conditions.map(I=>[I.id,I])),l=new Set(i.conditions.map(I=>I.id)),c=i.conditions.filter(I=>!u.has(I.id)).sort(VI),d=i.conditions.filter(I=>u.has(I.id)).sort(VI),f=a.conditions.filter(I=>!l.has(I.id)),p=d.some(I=>!PSe(I,u.get(I.id))),m=i.name!==a.name,h={...i.description!==a.description?{description:i.description}:{},...i.caseSensitive!==a.caseSensitive?{iscasesensitive:i.caseSensitive}:{},...i.excludeInactiveRecords!==a.excludeInactiveRecords?{excludeinactiverecords:i.excludeInactiveRecords}:{}},g="iscasesensitive"in h||"excludeinactiverecords"in h,y=c.length>0||f.length>0||p,b=I=>({method:"PATCH",path:`/${sf.DUPLICATE_RULE_SET}(${o})`,body:I,etag:"*"}),E=I=>({method:"POST",path:"/duplicateruleconditions",body:{...nh(I),"[email protected]":`/${sf.DUPLICATE_RULE_SET}(${o})`}}),w=I=>({method:"POST",path:"/CompoundUpdateDuplicateDetectionRule",body:{Entity:{"@odata.type":TSe,duplicateruleid:o,...m?{name:i.name}:{},...h},ChildEntities:I.map(T=>{let O=u.get(T.id);return{"@odata.type":OSe,...nh(T),...(T.characters===null||T.characters===void 0)&&O&&O.characters!==null?{operatorparam:null}:{}}})}});if(!m&&!y&&(!g||s==="unpublished")){let I=g?h:{description:i.description};return{desired:i,heldStatus:s,ops:[b(I)],statusAfterContent:g?"unpublished":s}}if(a.conditions.length>0){let I=d.length===0?[...a.conditions].sort(VI)[0]:void 0,T=[w(I?[I]:d)];return I&&T.push({method:"DELETE",path:`/duplicateruleconditions(${I.id})`}),T.push(...c.map(E)),{desired:i,heldStatus:s,ops:T,statusAfterContent:"unpublished"}}if(m)return{desired:i,heldStatus:s,ops:[...c.map(E),w(c)],statusAfterContent:"unpublished"};let _=Object.keys(h).length>0?[b(h)]:[];return _.push(...c.map(E)),{desired:i,heldStatus:s,ops:_,statusAfterContent:"unpublished"}}createDefault(t){var n,r,i,o,a,s,u,l,c;return{id:(n=t.id)!==null&&n!==void 0?n:(0,GI.newId)(),name:(r=t.name)!==null&&r!==void 0?r:"",description:(i=t.description)!==null&&i!==void 0?i:null,entityLogicalName:(o=t.entityLogicalName)!==null&&o!==void 0?o:"",matchingEntityLogicalName:(s=(a=t.matchingEntityLogicalName)!==null&&a!==void 0?a:t.entityLogicalName)!==null&&s!==void 0?s:"",caseSensitive:(u=t.caseSensitive)!==null&&u!==void 0?u:!1,excludeInactiveRecords:(l=t.excludeInactiveRecords)!==null&&l!==void 0?l:!1,status:(c=t.status)!==null&&c!==void 0?c:"published",conditions:t.conditions?(0,ISe.cloneJson)(t.conditions):[]}}assignMissingIds(t){if(t===null||typeof t!="object"||Array.isArray(t))return t;let n=t;return Array.isArray(n.conditions)?{...n,conditions:n.conditions.map(r=>this.assignMissingIds(r))}:"column"in n&&n.id===void 0?{...n,id:(0,GI.newId)()}:t}validate(t){return(0,qI.shapeIssues)(t)}normalize(t){return Array.isArray(t.conditions)?t.description!==void 0&&t.matchingEntityLogicalName!==void 0&&t.caseSensitive!==void 0&&t.excludeInactiveRecords!==void 0&&t.conditions.every(r=>r!==null&&typeof r=="object"&&r.id!==void 0&&r.matchingColumn!==void 0&&r.characters!==void 0&&r.ignoreBlankValues!==void 0)?t:BI(t):t}committed(t,n,r){let i=r.serverState;return(i==="published"||i==="unpublished")&&i!==t.status?{artifact:t,baseline:{...t,status:i}}:{artifact:t,baseline:t}}};uf.DuplicateRuleAdapter=Ub;function RSe(){return{adapter:new Ub,api:NSe.duplicateRuleApi,guardedDelete:!0,publishesOnPush:e=>{var t;let n=e;return((t=n?.desired)===null||t===void 0?void 0:t.status)==="published"&&n.statusAfterContent==="unpublished"}}}uf.duplicateRuleRegistration=RSe});var j9=C(qb=>{"use strict";Object.defineProperty(qb,"__esModule",{value:!0});qb.buildRegistrations=void 0;var kSe=r4(),$Se=_4(),LSe=uj(),MSe=Nj(),xSe=Hj(),FSe=fW(),USe=FW(),qSe=wz(),BSe=b9(),VSe=E9(),GSe=N9(),jSe=D9(),WSe=U9(),zSe=G9();function HSe(e){let t=new Map;return t.set("form",(0,kSe.formRegistration)(e)),t.set("view",(0,$Se.viewRegistration)()),t.set("businessRule",(0,LSe.businessRuleRegistration)()),t.set("app",(0,MSe.appRegistration)(e)),t.set("command",(0,xSe.commandRegistration)()),t.set("chart",(0,FSe.chartRegistration)()),t.set("dashboard",(0,USe.dashboardRegistration)(e)),t.set("genPage",(0,qSe.genPageRegistration)()),t.set("bpf",(0,BSe.bpfRegistration)()),t.set("environmentVariable",(0,VSe.environmentVariableRegistration)()),t.set("connectionReference",(0,GSe.connectionReferenceRegistration)()),t.set("fieldSecurityProfile",(0,jSe.fieldSecurityProfileRegistration)()),t.set("customApi",(0,WSe.customApiRegistration)()),t.set("duplicateRule",(0,zSe.duplicateRuleRegistration)()),t}qb.buildRegistrations=HSe});var X9=C(lf=>{"use strict";Object.defineProperty(lf,"__esModule",{value:!0});lf.findArtifact=lf.resolveArtifact=void 0;var dr=ae(),Ss=p0(),KSe=vc(),W9=Ke(),JSe=pe(),jI=Y(),z9=Jc(),H9=DI(),K9=s0(),J9=C0(),Y9=S0();async function Q9(e,t,n){let r="/uxagentprojects"+(0,dr.odataQuery)([["$select","uxagentprojectid,name"],["$filter",`name eq '${(0,dr.odataLiteral)(t)}'`],...n!==void 0?[["$top",String(n)]]:[]]);return(await(0,W9.collectPages)(e,r,"resolveArtifact('genPage')",void 0,{headers:{"MSCRM.IncludeUnpublished":"true"}})).map(o=>({id:String(o.uxagentprojectid),name:String(o.name)}))}async function YSe(e,t,n){var r,i,o,a,s,u,l,c,d,f,p,m,h,g,y,b,E,w;switch(t){case"app":{let _=(0,KSe.unpublishedAppModulesQuery)("appmoduleid,name,appmoduleidunique",`uniquename eq '${(0,dr.odataLiteral)((r=n.uniqueName)!==null&&r!==void 0?r:"")}'`,1),I=(0,JSe.ensureSuccess)(await e.get(_),e.apiUrl(_)),T=(i=I.body)===null||i===void 0?void 0:i.value;if(Array.isArray(T)&&!(0,W9.boundedPageComplete)(I.body,T.length))throw new jI.ConnectionError(e.apiUrl(_),I.status,`the app lookup for '${(o=n.uniqueName)!==null&&o!==void 0?o:""}' answered no app but says more rows exist`);let O=T&&T[0];return O?[{id:String(O.appmoduleid),name:String(O.name),appModuleIdUnique:String(O.appmoduleidunique)}]:[]}case"dashboard":return(await(0,Ss.queryRecords)(e,"systemform",{select:["formid","name"],filter:`name eq '${(0,dr.odataLiteral)((a=n.name)!==null&&a!==void 0?a:"")}' and type eq 0`,top:10})||[]).map(I=>({id:String(I.formid),name:String(I.name)}));case"command":{if(!n.entity)return[];let _=await(0,Ss.queryRecords)(e,"appaction",{select:["appactionid","buttonlabeltext"],filter:`contextvalue eq '${(0,dr.odataLiteral)(n.entity)}'`,top:1});return _&&_.length?[{id:n.entity,entity:n.entity}]:[]}case"form":return(await(0,Ss.queryRecords)(e,"systemform",{select:["formid","name"],filter:`name eq '${(0,dr.odataLiteral)((s=n.name)!==null&&s!==void 0?s:"")}' and objecttypecode eq '${(0,dr.odataLiteral)((u=n.entity)!==null&&u!==void 0?u:"")}'`,top:10})||[]).map(I=>({id:String(I.formid),name:String(I.name)}));case"chart":return(await(0,Ss.queryRecords)(e,"savedqueryvisualization",{select:["savedqueryvisualizationid","name"],filter:`name eq '${(0,dr.odataLiteral)((l=n.name)!==null&&l!==void 0?l:"")}' and primaryentitytypecode eq '${(0,dr.odataLiteral)((c=n.entity)!==null&&c!==void 0?c:"")}'`,top:10})||[]).map(I=>({id:String(I.savedqueryvisualizationid),name:String(I.name)}));case"view":return(await(0,Ss.queryRecords)(e,"savedquery",{select:["savedqueryid","name"],filter:`name eq '${(0,dr.odataLiteral)((d=n.name)!==null&&d!==void 0?d:"")}' and returnedtypecode eq '${(0,dr.odataLiteral)((f=n.entity)!==null&&f!==void 0?f:"")}'`,top:10})||[]).map(I=>({id:String(I.savedqueryid),name:String(I.name)}));case"webResource":return(await(0,Ss.queryRecords)(e,"webresource",{select:["webresourceid","name"],filter:`name eq '${(0,dr.odataLiteral)((p=n.name)!==null&&p!==void 0?p:"")}'`,top:1})||[]).map(I=>({id:String(I.webresourceid),name:String(I.name)}));case"solution":return(await(0,Ss.queryRecords)(e,"solution",{select:["solutionid","uniquename"],filter:`uniquename eq '${(0,dr.odataLiteral)((m=n.uniqueName)!==null&&m!==void 0?m:"")}'`,top:1})||[]).map(I=>({id:String(I.solutionid),name:String(I.uniquename)}));case"genPage":return Q9(e,(h=n.name)!==null&&h!==void 0?h:"");case"environmentVariable":return(0,z9.resolveEnvironmentVariables)(e,(g=n.uniqueName)!==null&&g!==void 0?g:"");case"connectionReference":return(0,H9.resolveConnectionReferences)(e,(y=n.uniqueName)!==null&&y!==void 0?y:"");case"fieldSecurityProfile":return(0,K9.resolveFieldSecurityProfiles)(e,(b=n.name)!==null&&b!==void 0?b:"");case"customApi":return(0,J9.resolveCustomApis)(e,(E=n.uniqueName)!==null&&E!==void 0?E:"");case"duplicateRule":return(0,Y9.resolveDuplicateRules)(e,(w=n.name)!==null&&w!==void 0?w:"",n.entity);default:return[]}}lf.resolveArtifact=YSe;async function QSe(e,t,n){var r,i,o,a,s,u,l,c,d,f,p;let m=(0,dr.odataLiteral)((r=n.name)!==null&&r!==void 0?r:""),h=(0,dr.odataLiteral)((i=n.entity)!==null&&i!==void 0?i:"");if(t==="command"){if(!n.entity)return null;let w=await(0,Ss.queryRecords)(e,"appaction",{select:["appactionid"],filter:`contextvalue eq '${(0,dr.odataLiteral)(n.entity)}'`,top:1});return w&&w.length?n.entity:null}if(t==="genPage"){let w=await Q9(e,(o=n.name)!==null&&o!==void 0?o:"",2);if(w.length>1)throw new jI.AmbiguousArtifactError(t,(a=n.name)!==null&&a!==void 0?a:"",w.length);return w.length===1?w[0].id:null}if(t==="environmentVariable")return(0,z9.findEnvironmentVariable)(e,(s=n.uniqueName)!==null&&s!==void 0?s:"");if(t==="connectionReference")return(0,H9.findConnectionReference)(e,(u=n.uniqueName)!==null&&u!==void 0?u:"");if(t==="fieldSecurityProfile")return(0,K9.findFieldSecurityProfile)(e,(l=n.name)!==null&&l!==void 0?l:"");if(t==="customApi")return(0,J9.findCustomApi)(e,(c=n.uniqueName)!==null&&c!==void 0?c:"");if(t==="duplicateRule")return(0,Y9.findDuplicateRule)(e,(d=n.name)!==null&&d!==void 0?d:"",n.entity);let g=XSe(t,m,h,n),y=t!=="app",b=await(0,Ss.queryRecords)(e,g.set,{select:[g.idField],filter:g.filter,top:y?2:1});if(y&&b&&b.length>1)throw new jI.AmbiguousArtifactError(t,(p=(f=n.name)!==null&&f!==void 0?f:n.uniqueName)!==null&&p!==void 0?p:"",b.length);let E=b&&b[0]&&b[0][g.idField];return E!=null?String(E):null}lf.findArtifact=QSe;function XSe(e,t,n,r){var i;switch(e){case"view":return{set:"savedquery",idField:"savedqueryid",filter:`returnedtypecode eq '${n}' and name eq '${t}'`};case"chart":return{set:"savedqueryvisualization",idField:"savedqueryvisualizationid",filter:`primaryentitytypecode eq '${n}' and name eq '${t}'`};case"form":return{set:"systemform",idField:"formid",filter:`objecttypecode eq '${n}' and name eq '${t}'`};case"app":return{set:"appmodule",idField:"appmoduleid",filter:`uniquename eq '${(0,dr.odataLiteral)((i=r.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 e8=C(Vb=>{"use strict";Object.defineProperty(Vb,"__esModule",{value:!0});Vb.seedRecordGraph=void 0;var Z9=p0(),ZSe=u0(),Bb=ae(),eNe=Y();async function tNe(e,t,n={}){var r,i,o,a,s;let u=(r=n.createdIds)!==null&&r!==void 0?r:{},l=(i=n.entitySetFor)!==null&&i!==void 0?i:(f=>(0,ZSe.resolveEntitySetName)(e,f)),c={},d=f=>{var p;return(p=c[f])!==null&&p!==void 0?p:u[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 I of f.records){let T={...I.body};for(let O of(a=I.binds)!==null&&a!==void 0?a:[]){let v=O.parentEntity.toLowerCase(),N=(s=d(v))===null||s===void 0?void 0:s[O.parentIndex];if(!N)throw new eNe.InvalidArgumentError(`Cannot resolve bind '${O.navProperty}' on a '${p}' record: parent '${O.parentEntity}'[${O.parentIndex}] has no created id. Seed the parent group before the child, or supply it via options.createdIds.`);let S=(0,Bb.assertODataName)(await l(v),`entity set for parent '${O.parentEntity}'`),R=(0,Bb.normalizeGuid)(N,`parent id for bind '${O.navProperty}'`);T[`${O.navProperty}@odata.bind`]=`/${S}(${R})`}h.push(T)}let g=m?h.map(I=>{let T=I[m];return T!=null&&T!==""?String(T):null}):h.map(()=>null),y=new Map;if(m){let I=(0,Bb.assertODataName)(m,"RecordGraph matchOn key"),T=[...new Set(g.filter(O=>O!==null))];if(T.length){let O=T.map(N=>`${I} eq '${(0,Bb.odataLiteral)(N)}'`).join(" or "),v=await(0,Z9.queryRecords)(e,p,{select:[I,`${p}id`],filter:O,top:5e3});for(let N of v??[]){let S=N[I];S!=null&&y.set(String(S).toLowerCase(),String(N[`${p}id`]))}}}let b=[],E=new Map,w=h.map((I,T)=>{let O=g[T];if(O&&y.has(O.toLowerCase()))return null;if(O){let v=O.toLowerCase(),N=E.get(v);if(N!==void 0)return N;let S=b.push(I)-1;return E.set(v,S),S}return b.push(I)-1}),_=b.length?await(0,Z9.createRecordsBulk)(e,p,b):[];c[p]=h.map((I,T)=>{let O=g[T];return O&&y.has(O.toLowerCase())?y.get(O.toLowerCase()):_[w[T]]})}return{createdIds:c}}Vb.seedRecordGraph=tNe});var i8=C(St=>{"use strict";Object.defineProperty(St,"__esModule",{value:!0});St.encodeValue=St.hasPlanShape=St.validateRequested=St.decodeValue=St.readKey=St.sameValue=St.isGuid=St.isNumericKind=St.kindOf=St.inSafeDomain=St.MAX_TEXT_LENGTH=void 0;St.MAX_TEXT_LENGTH=1048576;var nNe=[1e15,1e14,1e13,1e12,1e11,1e10,1e9,1e8,1e7,1e6,1e5],rNe=1e-6;function cf(e,t){if(typeof e!="number"||!Number.isFinite(e)||!Number.isInteger(t)||t<0||t>10)return!1;let n=Math.abs(e);return n>=nNe[t]||e!==0&&n<rNe?!1:Number(e.toFixed(t))===e}St.inSafeDomain=cf;function iNe(e,t){switch(e){case"String":return"string";case"Memo":return"memo";case"Integer":return"integer";case"Decimal":return"decimal";case"Double":return"double";case"Money":return"money";case"Boolean":return"boolean";case"Picklist":return"choice";case"State":return"state";case"Status":return"status";case"DateTime":return"dateTime";case"Lookup":return"lookup";case"Virtual":return t==="MultiSelectPicklistType"?"multiSelect":void 0;default:return}}St.kindOf=iNe;function oNe(e){return e==="decimal"||e==="double"||e==="money"}St.isNumericKind=oNe;var aNe=/^[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 jb(e){return typeof e=="string"&&aNe.test(e)}St.isGuid=jb;var n8=/^(\d{4})-(\d{2})-(\d{2})$/,sNe=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(|:\d{2}|:\d{2}\.\d{1,7})(Z|[+-]\d{2}:\d{2})$/;function rh(e){let t=n8.exec(e);if(!t)return!1;let n=new Date(Date.UTC(Number(t[1]),Number(t[2])-1,Number(t[3])));return n.getUTCFullYear()===Number(t[1])&&n.getUTCMonth()===Number(t[2])-1&&n.getUTCDate()===Number(t[3])}function ih(e){return rh(e)||sNe.test(e)&&Number.isFinite(Date.parse(e))&&rh(e.slice(0,10))}function t8(e){let t=n8.test(e)?`${e}T00:00:00Z`:e;return Math.floor(Date.parse(t)/1e3)}function Gb(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let t=Object.keys(e),n=e;return t.length===2&&typeof n.table=="string"&&typeof n.id=="string"}function WI(e){if(e===null)return[];if(Array.isArray(e)&&e.every(t=>Number.isInteger(t)))return[...e].sort((t,n)=>t-n)}function uNe(e,t,n,r){switch(e.kind){case"multiSelect":{let i=WI(t),o=WI(n);return i!==void 0&&o!==void 0&&i.length===o.length&&i.every((a,s)=>a===o[s])}case"lookup":return t===null||n===null?t===null&&n===null:Gb(t)&&Gb(n)&&t.table===n.table&&t.id.toLowerCase()===n.id.toLowerCase();case"decimal":case"double":case"money":return t===null||n===null?t===null&&n===null:r!==void 0&&cf(t,r)&&cf(n,r)&&t.toFixed(r)===n.toFixed(r);case"dateTime":return t===null||n===null?t===null&&n===null:typeof t!="string"||typeof n!="string"?!1:e.dateTimeBehavior==="DateOnly"?t===n:e.dateTimeBehavior==="UserLocal"||e.dateTimeBehavior==="TimeZoneIndependent"?ih(t)&&ih(n)&&t8(t)===t8(n):!1;default:return t===n}}St.sameValue=uNe;function r8(e){return e.kind==="lookup"?`_${e.logicalName}_value`:e.logicalName}St.readKey=r8;function lNe(e,t,n){var r;let i=r8(e);if(!Object.prototype.hasOwnProperty.call(t,i))return{ok:!1,reason:"incompleteRead"};let o=t[i],a={ok:!1,reason:"unsafeValue"};if(o===null)return e.kind==="boolean"||e.kind==="state"||e.kind==="status"?a:{ok:!0,value:null};switch(e.kind){case"string":case"memo":return typeof o=="string"?{ok:!0,value:o}:a;case"integer":return Number.isSafeInteger(o)?{ok:!0,value:o}:a;case"decimal":case"double":case"money":return n!==void 0&&cf(o,n)?{ok:!0,value:o}:a;case"boolean":return typeof o=="boolean"?{ok:!0,value:o}:a;case"choice":case"state":case"status":return Number.isInteger(o)?{ok:!0,value:o}:a;case"multiSelect":return typeof o!="string"||!o.split(",").every(s=>/^-?\d+$/.test(s))?a:{ok:!0,value:o.split(",").map(Number).sort((s,u)=>s-u)};case"dateTime":return typeof o!="string"?a:e.dateTimeBehavior==="DateOnly"?rh(o)?{ok:!0,value:o}:a:ih(o)?{ok:!0,value:o}:a;case"lookup":{let s=t[`${i}@Microsoft.Dynamics.CRM.lookuplogicalname`];return!jb(o)||typeof s!="string"||s!==((r=e.lookupTarget)===null||r===void 0?void 0:r.table)?a:{ok:!0,value:{table:s,id:o.toLowerCase()}}}default:return a}}St.decodeValue=lNe;function cNe(e,t,n,r){var i,o,a;if(n===null)return e.kind==="boolean"||e.kind==="state"||e.kind==="status"?"invalidValue":void 0;let s=u=>(t.min===void 0||u>=t.min)&&(t.max===void 0||u<=t.max);switch(e.kind){case"string":case"memo":return typeof n=="string"&&n.length<=((i=t.maxLength)!==null&&i!==void 0?i:St.MAX_TEXT_LENGTH)?void 0:"invalidValue";case"integer":return Number.isSafeInteger(n)&&s(n)?void 0:"invalidValue";case"decimal":case"double":case"money":return typeof n!="number"||!Number.isFinite(n)||!s(n)?"invalidValue":r===void 0||cf(n,r)?void 0:"invalidValue";case"boolean":return typeof n=="boolean"?void 0:"invalidValue";case"choice":case"state":case"status":return Number.isInteger(n)&&((o=t.options)!==null&&o!==void 0?o:[]).includes(n)?void 0:"invalidValue";case"multiSelect":return!Array.isArray(n)||new Set(n).size!==n.length?"invalidValue":n.every(u=>{var l;return Number.isInteger(u)&&((l=t.options)!==null&&l!==void 0?l:[]).includes(u)})?void 0:"invalidValue";case"dateTime":return typeof n!="string"?"invalidValue":e.dateTimeBehavior==="DateOnly"?rh(n)?void 0:"invalidValue":ih(n)?void 0:"invalidValue";case"lookup":return Gb(n)&&n.table===((a=e.lookupTarget)===null||a===void 0?void 0:a.table)&&jb(n.id)?void 0:"invalidLookupTarget";default:return"invalidValue"}}St.validateRequested=cNe;function dNe(e,t,n){var r;if(t===null)return e.kind!=="boolean"&&e.kind!=="state"&&e.kind!=="status";switch(e.kind){case"string":case"memo":return typeof t=="string"&&t.length<=St.MAX_TEXT_LENGTH;case"integer":return Number.isSafeInteger(t);case"decimal":case"double":case"money":return n!==void 0&&cf(t,n);case"boolean":return typeof t=="boolean";case"choice":case"state":case"status":return Number.isInteger(t);case"multiSelect":return Array.isArray(t)&&new Set(t).size===t.length&&t.every(i=>Number.isInteger(i));case"dateTime":return typeof t!="string"?!1:e.dateTimeBehavior==="DateOnly"?rh(t):ih(t);case"lookup":return Gb(t)&&t.table===((r=e.lookupTarget)===null||r===void 0?void 0:r.table)&&jb(t.id);default:return!1}}St.hasPlanShape=dNe;function fNe(e,t){var n;if(e.kind==="lookup"){let r=e.lookupTarget;return{[`${r.navigationProperty}@odata.bind`]:t===null?null:`/${r.entitySetName}(${t.id.toLowerCase()})`}}if(e.kind==="multiSelect"){let r=(n=WI(t))!==null&&n!==void 0?n:[];return{[e.logicalName]:r.length===0?null:r.join(",")}}return{[e.logicalName]:t}}St.encodeValue=fNe});var v8=C(ku=>{"use strict";Object.defineProperty(ku,"__esModule",{value:!0});ku.applyDataFix=ku.planDataFix=ku.getOnlyDataverse=void 0;var zI=Zo(),Wt=i8(),YI=Ke(),Qe=Y(),Bo=pe(),f8=ft(),Si=ae(),pNe=5e3,Ru=5e4,mNe=5e3,Wb=100,ff=40,hNe=100,o8=1e3,gNe=4*1024*1024,yNe=512,bNe=3e5,a8=36e5,vNe=10,p8="Microsoft.Dynamics.CRM.lookuplogicalname",wNe="0x80040216",ENe="0x80040217";function QI(e){return{apiUrl:t=>e.apiUrl(t),get:(t,n)=>e.get(t,n),getAbsolute:(t,n)=>e.getAbsolute(t,n)}}ku.getOnlyDataverse=QI;function Qn(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}var Kl=e=>typeof e=="string"&&/^[A-Za-z_][A-Za-z0-9_]*$/.test(e);function KI(e){if(Array.isArray(e))return e.map(KI);if(Qn(e)){let t={};for(let n of Object.keys(e))Object.defineProperty(t,n,{value:KI(e[n]),enumerable:!0,writable:!0,configurable:!0});return t}return e}var ANe="transactioncurrencyid";function m8(e,t){let n=Object.keys(e??{}).find(r=>r.toLowerCase()===t);return n===void 0?void 0:e[n]}function h8(e){return new URL(e.apiUrl("/")).origin}async function XI(e,t,n){let r;try{r=await t()}catch(i){throw(0,Qe.attachCause)(new Qe.DataFixError("DATA_FIX_READ_FAILED",`Reading ${e} for the data fix failed in transport.`,0),i)}try{(0,Bo.ensureSuccess)(r,n)}catch(i){throw(0,Qe.attachCause)(new Qe.DataFixError("DATA_FIX_READ_FAILED",`Reading ${e} for the data fix failed: HTTP ${r.status}.`,r.status),i)}return r}function Jl(e,t,n,r){return XI(t,()=>e.get(n,r),e.apiUrl(n))}function pf(e,t){var n;let r=(n=e.body)===null||n===void 0?void 0:n.value;if(!Array.isArray(r)||!r.every(Qn))throw new Qe.DataFixError("DATA_FIX_READ_FAILED",`Reading ${t} for the data fix returned a malformed page.`,e.status);return r}async function s8(e,t,n,r,i){let o=[];for(let a=0;a<r.length;a+=ff){let s=r.slice(a,a+ff).map(l=>`LogicalName eq '${(0,Si.odataLiteral)(l)}'`).join(" or "),u=`${t}${(0,Si.odataQuery)([["$select",n],["$expand",i],["$filter",s]])}`;o.push(...pf(await Jl(e,"the column metadata",u),"the column metadata"))}return o}function u8(e,t){if(!Qn(e)||Object.keys(e).length===0)throw new Qe.InvalidArgumentError(`${t} must be an object naming at least one column`);return Object.keys(e).forEach((n,r)=>{if(!Kl(n))throw new Qe.InvalidArgumentError(`${t} key #${r+1} must be a column's logical name (letters, digits, underscores)`)}),KI(e)}function CNe(e){if(!Qn(e))throw new Qe.InvalidArgumentError("planDataFix needs a request object");let t=e;if(!Kl(t.table))throw new Qe.InvalidArgumentError("planDataFix `table` must be a table's logical name (letters, digits, underscores)");let n=t.table,r=t.filter!==void 0,i=t.rows!==void 0;if(r===i)throw new Qe.InvalidArgumentError("planDataFix needs exactly one of `filter` (with `set`) and `rows`");if(r){if(typeof t.filter!="string"||t.filter.trim()==="")throw new Qe.InvalidArgumentError('planDataFix `filter` must be a non-blank OData $filter \u2014 there is no "every row"');let u=t.maxRows===void 0?pNe:t.maxRows;if(!Number.isInteger(u)||u<1||u>Ru)throw new Qe.InvalidArgumentError(`planDataFix \`maxRows\` must be an integer 1..${Ru}`);let l=u8(t.set,"planDataFix `set`");return{table:n,filter:t.filter,maxRows:u,set:l,columnNames:Object.keys(l)}}if(!Array.isArray(t.rows)||t.rows.length===0||t.rows.length>Ru)throw new Qe.InvalidArgumentError(`planDataFix \`rows\` must hold 1..${Ru} rows`);let o=new Set,a=[],s=t.rows.map((u,l)=>{if(!Qn(u))throw new Qe.InvalidArgumentError(`planDataFix rows[${l}] must be an object`);let c=typeof u.id=="string"?u.id.replace(/^\{(.*)\}$/,"$1"):"";if(!(0,Wt.isGuid)(c))throw new Qe.InvalidArgumentError(`planDataFix rows[${l}].id must be a GUID`);let d=c.toLowerCase();if(o.has(d))throw new Qe.InvalidArgumentError(`planDataFix rows[${l}].id repeats an earlier row`);if(o.add(d),u.etag!==void 0&&(!(0,Bo.isVersionToken)(u.etag)||/[\u0000-\u001F\u007F]/.test(u.etag)))throw new Qe.InvalidArgumentError(`planDataFix rows[${l}].etag must be a row version token (W/"\u2026")`);let f=u8(u.set,`planDataFix rows[${l}].set`);for(let p of Object.keys(f))a.includes(p)||a.push(p);return{id:d,set:f,etag:u.etag}});return{table:n,maxRows:Ru,rows:s,columnNames:a}}async function g8(e,t){let n=`/EntityDefinitions(LogicalName='${(0,Si.odataPathLiteral)(t)}')`+(0,Si.odataQuery)([["$select","EntitySetName,PrimaryIdAttribute,PrimaryNameAttribute,IsOptimisticConcurrencyEnabled"]]),r;try{r=await e.get(n)}catch(s){throw(0,Qe.attachCause)(new Qe.DataFixError("DATA_FIX_READ_FAILED","Reading the table metadata for the data fix failed in transport.",0),s)}if(r.status===404)throw new Qe.DataFixError("DATA_FIX_TABLE_NOT_FOUND",`The table '${t}' was not found.`,404);await XI("the table metadata",()=>Promise.resolve(r),e.apiUrl(n));let i=r.body,o=[i?.EntitySetName,i?.PrimaryIdAttribute,i?.PrimaryNameAttribute];if(!o.every(s=>typeof s=="string"&&/^[A-Za-z_][A-Za-z0-9_]*$/.test(s)))throw new Qe.DataFixError("DATA_FIX_READ_FAILED","Reading the table metadata for the data fix returned a malformed answer.",r.status);let a=i?.IsOptimisticConcurrencyEnabled;if(a!==!0)throw new Qe.DataFixError("DATA_FIX_CONCURRENCY_UNSUPPORTED",`The table '${t}' does not have optimistic concurrency enabled, so its rows cannot be written conditionally; a data fix refuses it.`);return{logicalName:t,entitySetName:o[0],primaryIdAttribute:o[1],primaryNameAttribute:o[2],concurrency:a}}var SNe={string:{cast:"StringAttributeMetadata",select:"LogicalName,MaxLength"},memo:{cast:"MemoAttributeMetadata",select:"LogicalName,MaxLength"},integer:{cast:"IntegerAttributeMetadata",select:"LogicalName,MinValue,MaxValue"},decimal:{cast:"DecimalAttributeMetadata",select:"LogicalName,Precision,MinValue,MaxValue"},double:{cast:"DoubleAttributeMetadata",select:"LogicalName,Precision,MinValue,MaxValue"},money:{cast:"MoneyAttributeMetadata",select:"LogicalName,Precision,PrecisionSource,MinValue,MaxValue"},dateTime:{cast:"DateTimeAttributeMetadata",select:"LogicalName,DateTimeBehavior"},choice:{cast:"PicklistAttributeMetadata",select:"LogicalName",expand:"OptionSet($select=Options)"},state:{cast:"StateAttributeMetadata",select:"LogicalName",expand:"OptionSet($select=Options)"},status:{cast:"StatusAttributeMetadata",select:"LogicalName",expand:"OptionSet($select=Options)"},multiSelect:{cast:"MultiSelectPicklistAttributeMetadata",select:"LogicalName",expand:"OptionSet($select=Options)"},lookup:{cast:"LookupAttributeMetadata",select:"LogicalName,Targets"}},oh=e=>Number.isInteger(e)&&e>=0&&e<=10,df=e=>typeof e=="number"&&Number.isFinite(e);async function NNe(e,t,n){var r;let i=`/EntityDefinitions(LogicalName='${(0,Si.odataPathLiteral)(t.logicalName)}')`,o=await s8(e,`${i}/Attributes`,"LogicalName,AttributeType,AttributeTypeName,IsValidForRead,IsValidForUpdate,IsSecured",n),a=new Map(o.map(h=>[String(h.LogicalName),h])),s=new Map,u=new Map;for(let h of n){let g=a.get(h);if(h===t.primaryIdAttribute)s.set(h,"primaryKey");else if(!g)s.set(h,"notFound");else if(![g.IsSecured,g.IsValidForRead,g.IsValidForUpdate].every(y=>typeof y=="boolean"))s.set(h,"metadataIncomplete");else if(g.IsSecured===!0)s.set(h,"secured");else if(g.IsValidForRead===!1)s.set(h,"notReadable");else if(g.IsValidForUpdate===!1)s.set(h,"readOnly");else{let y=(0,Wt.kindOf)(g.AttributeType,(r=g.AttributeTypeName)===null||r===void 0?void 0:r.Value);y===void 0?s.set(h,"unsupportedType"):u.set(h,y)}}let l=new Map;for(let h of new Set(u.values())){let g=SNe[h];if(!g)continue;let y=[...u].filter(([,b])=>b===h).map(([b])=>b);for(let b of await s8(e,`${i}/Attributes/Microsoft.Dynamics.CRM.${g.cast}`,g.select,y,g.expand))l.set(String(b.LogicalName),b)}let c=[...u].filter(([,h])=>h==="lookup").map(([h])=>h),d=c.length>0?await _Ne(e,i,c):new Map,p=[...u].some(([h,g])=>{var y;return g==="money"&&((y=l.get(h))===null||y===void 0?void 0:y.PrecisionSource)===1})?await INe(e):void 0,m=new Map;for(let[h,g]of u){let y=await TNe(e,h,g,l.get(h),d,p);"issue"in y?s.set(h,y.issue):m.set(h,y)}return{planned:m,issues:s}}async function _Ne(e,t,n){var r;let i=new Map;for(let o=0;o<n.length;o+=ff){let a=n.slice(o,o+ff).map(u=>`ReferencingAttribute eq '${(0,Si.odataLiteral)(u)}'`).join(" or "),s=`${t}/ManyToOneRelationships${(0,Si.odataQuery)([["$select","ReferencingAttribute,ReferencedEntity,ReferencingEntityNavigationPropertyName"],["$filter",a]])}`;for(let u of pf(await Jl(e,"the lookup relationships",s),"the lookup relationships")){let l=String(u.ReferencingAttribute),c=(r=i.get(l))!==null&&r!==void 0?r:new Map;typeof u.ReferencedEntity=="string"&&typeof u.ReferencingEntityNavigationPropertyName=="string"&&c.set(u.ReferencedEntity,u.ReferencingEntityNavigationPropertyName),i.set(l,c)}}return i}async function INe(e){var t;let n=`/organizations${(0,Si.odataQuery)([["$select","pricingdecimalprecision"]])}`,i=(t=pf(await Jl(e,"the organization precision",n),"the organization precision")[0])===null||t===void 0?void 0:t.pricingdecimalprecision;return oh(i)?i:void 0}async function TNe(e,t,n,r,i,o){var a,s,u,l;let c={issue:"metadataIncomplete"},d={min:r?.MinValue,max:r?.MaxValue};switch(n){case"string":case"memo":return Number.isInteger(r?.MaxLength)?{column:{logicalName:t,kind:n},facts:{maxLength:r?.MaxLength}}:c;case"integer":return df(d.min)&&df(d.max)?{column:{logicalName:t,kind:n},facts:{min:d.min,max:d.max}}:c;case"decimal":case"double":return df(d.min)&&df(d.max)&&oh(r?.Precision)?{column:{logicalName:t,kind:n,precisionSource:"column"},facts:{min:d.min,max:d.max},precision:r?.Precision}:c;case"money":{if(!df(d.min)||!df(d.max))return c;let f={min:d.min,max:d.max};switch(r?.PrecisionSource){case 0:return oh(r.Precision)?{column:{logicalName:t,kind:n,precisionSource:"column"},facts:f,precision:r.Precision}:c;case 1:return o===void 0?c:{column:{logicalName:t,kind:n,precisionSource:"organization"},facts:f,precision:o};case 2:return{column:{logicalName:t,kind:n,precisionSource:"currency"},facts:f,perRowCurrency:!0};default:return c}}case"boolean":return{column:{logicalName:t,kind:n},facts:{}};case"dateTime":{let f=(a=r?.DateTimeBehavior)===null||a===void 0?void 0:a.Value;return f==="UserLocal"||f==="DateOnly"||f==="TimeZoneIndependent"?{column:{logicalName:t,kind:n,dateTimeBehavior:f},facts:{}}:c}case"choice":case"state":case"status":case"multiSelect":{let f=(s=r?.OptionSet)===null||s===void 0?void 0:s.Options,p=Array.isArray(f)?f.map(m=>m?.Value):[];return p.length>0&&p.every(m=>Number.isInteger(m))?{column:{logicalName:t,kind:n},facts:{options:p}}:c}case"lookup":{let f=r?.Targets;if(!Array.isArray(f)||f.length===0||!f.every(y=>typeof y=="string"))return c;if(f.length>1)return{issue:"invalidLookupTarget"};let p=f[0],m=(u=i.get(t))===null||u===void 0?void 0:u.get(p);if(m===void 0||!/^[A-Za-z_][A-Za-z0-9_]*$/.test(m))return c;let h=`/EntityDefinitions(LogicalName='${(0,Si.odataPathLiteral)(p)}')${(0,Si.odataQuery)([["$select","EntitySetName"]])}`,g=(l=(await Jl(e,"the lookup target",h)).body)===null||l===void 0?void 0:l.EntitySetName;return typeof g!="string"||!/^[A-Za-z_][A-Za-z0-9_]*$/.test(g)?c:{column:{logicalName:t,kind:n,lookupTarget:{table:p,entitySetName:g,navigationProperty:m}},facts:{}}}default:return{issue:"unsupportedType"}}}function ZI(e,t){let n=e[t];if(!(0,Wt.isGuid)(n))throw new Qe.DataFixError("DATA_FIX_READ_FAILED","Reading the rows for the data fix returned a row without a readable id.",200);return n.toLowerCase()}function y8(e,t){let n=[...e===void 0?[]:[`odata.maxpagesize=${e}`],...t?[`odata.include-annotations="${p8}"`]:[]];return n.length===0?void 0:{headers:{Prefer:n.join(",")}}}async function ONe(e,t,n,r,i,o){let a=new Map,s=new Set,u=`/${t.entitySetName}${(0,Si.odataQuery)([["$select",n.join(",")],["$filter",r]])}`,l;for(;;){let c=y8(Math.min(i+1-a.size,mNe),o),d=l,f=d===void 0?await Jl(e,"the rows",u,c):await XI("the rows",()=>e.getAbsolute(d,c),d);for(let m of pf(f,"the rows")){let h=ZI(m,t.primaryIdAttribute);a.has(h)||a.set(h,m)}if(a.size>i)throw new Qe.DataFixError("DATA_FIX_TOO_MANY_ROWS",`The filter selects more than ${i} rows of '${t.logicalName}'; narrow it or raise maxRows (at most ${Ru}).`,void 0,void 0,i);let p=(0,YI.pageEnd)(f.body);if(p.kind==="end")return[...a.values()];if(p.kind==="incomplete"||s.has(p.link))throw new Qe.DataFixError("DATA_FIX_READ_FAILED",p.kind==="incomplete"&&p.cause==="claim"?"Reading the rows for the data fix returned a page that says more rows exist and gives no next link.":"Reading the rows for the data fix returned a malformed next link.",f.status);s.add(p.link),l=p.link}}function b8(e,t){return`Microsoft.Dynamics.CRM.In(PropertyName='${e}',PropertyValues=[${t.map(n=>`'${n}'`).join(",")}])`}async function DNe(e,t,n,r,i){let o=new Map;for(let a=0;a<r.length;a+=Wb){let s=r.slice(a,a+Wb),u=`/${t.entitySetName}${(0,Si.odataQuery)([["$select",n.join(",")],["$filter",b8(t.primaryIdAttribute,s)]])}`,l=await Jl(e,"the rows",u,y8(void 0,i));if((0,YI.pageEnd)(l.body).kind!=="end")throw new Qe.DataFixError("DATA_FIX_READ_FAILED","Reading the rows for the data fix returned a partial page.",l.status);for(let c of pf(l,"the rows"))o.set(ZI(c,t.primaryIdAttribute),c)}return o}async function PNe(e,t){let n=new Map;for(let r=0;r<t.length;r+=ff){let i=t.slice(r,r+ff).map(a=>`transactioncurrencyid eq ${a}`).join(" or "),o=`/transactioncurrencies${(0,Si.odataQuery)([["$select","transactioncurrencyid,currencyprecision"],["$filter",i]])}`;try{for(let a of pf(await Jl(e,"the currency precision",o),"the currency precision"))(0,Wt.isGuid)(a.transactioncurrencyid)&&oh(a.currencyprecision)&&n.set(a.transactioncurrencyid.toLowerCase(),a.currencyprecision)}catch{}}return n}async function RNe(e,t){var n,r,i,o,a;let s=CNe(t),u=QI(e),l=await g8(u,s.table),{planned:c,issues:d}=await NNe(u,l,s.columnNames),f=s.set?[s.set]:((n=s.rows)!==null&&n!==void 0?n:[]).map(S=>S.set);for(let S of f)if(Object.prototype.hasOwnProperty.call(S,ANe))for(let R of Object.keys(S))!((r=c.get(R))===null||r===void 0)&&r.perRowCurrency&&!d.has(R)&&d.set(R,"changesWithCurrency");for(let S of f)for(let[R,x]of Object.entries(S)){let G=c.get(R);if(G&&!d.has(R)){let U=(0,Wt.validateRequested)(G.column,G.facts,x,G.precision);U&&d.set(R,U)}}if(d.size>0)throw new Qe.DataFixColumnsInvalidError(s.columnNames.filter(S=>d.has(S)).map(S=>({column:S,reason:d.get(S)})));let p=s.columnNames.map(S=>c.get(S)),m=p.some(S=>S.perRowCurrency),h=p.some(S=>S.column.kind==="lookup"),g=[...new Set([l.primaryIdAttribute,l.primaryNameAttribute,...p.map(S=>(0,Wt.readKey)(S.column)),...m?["_transactioncurrencyid_value"]:[]])],y,b=[],E=new Map(((i=s.rows)!==null&&i!==void 0?i:[]).map(S=>[S.id,S]));if(s.filter!==void 0)y=await ONe(u,l,g,s.filter,s.maxRows,h);else{let S=await DNe(u,l,g,[...E.keys()],h);y=[];for(let R of E.keys()){let x=S.get(R);x?y.push(x):b.push(R)}}let w=m?[...new Set(y.map(S=>S._transactioncurrencyid_value).filter(Wt.isGuid).map(S=>S.toLowerCase()))]:[],_=w.length>0?await PNe(u,w):new Map,I=[],T=[],O=[],v=[],N=new Set;for(let S of y){let R=ZI(S,l.primaryIdAttribute),x=S["@odata.etag"];if(!(0,Bo.isVersionToken)(x)||/[\u0000-\u001F\u007F]/.test(x)){O.push({id:R,column:"@odata.etag",reason:"unsafeValue"});continue}let G=E.get(R);if(G?.etag!==void 0&&G.etag!==x){v.push(R);continue}let U=(o=s.set)!==null&&o!==void 0?o:G?.set,M=(0,Wt.isGuid)(S._transactioncurrencyid_value)?S._transactioncurrencyid_value.toLowerCase():void 0,q={},X={},ye={},Ve;for(let[wt,Fn]of Object.entries(U)){let xe=c.get(wt),Et=(0,Wt.isNumericKind)(xe.column.kind),zt=Et?(a=xe.precision)!==null&&a!==void 0?a:M?_.get(M):void 0:void 0;if(Et&&zt===void 0){Ve={id:R,column:wt,reason:"precisionUnknown"};break}let Ht=(0,Wt.decodeValue)(xe.column,S,zt);if(!Ht.ok){Ve={id:R,column:wt,reason:Ht.reason};break}if(xe.perRowCurrency&&(0,Wt.validateRequested)(xe.column,xe.facts,Fn,zt)!==void 0){Ve={id:R,column:wt,reason:"invalidValue"};break}(0,Wt.sameValue)(xe.column,Ht.value,Fn,zt)||(q[wt]=Ht.value,X[wt]=kNe(xe.column,Fn),Et&&(ye[wt]=zt))}if(Ve){O.push(Ve);continue}if(Object.keys(X).length===0){T.push(R);continue}Object.keys(X).forEach(wt=>N.add(wt));let _e=S[l.primaryNameAttribute];I.push({id:R,etag:x,name:typeof _e=="string"?_e:null,...Object.keys(ye).length>0?{numericPrecision:ye}:{},before:q,after:X})}return{kind:"dataFixPlan",version:1,planId:(0,f8.newId)(),createdAt:(0,Bo.nowIso)(),instanceUrl:h8(e),table:{logicalName:l.logicalName,entitySetName:l.entitySetName,primaryIdAttribute:l.primaryIdAttribute,primaryNameAttribute:l.primaryNameAttribute},selection:s.filter!==void 0?{by:"filter",filter:s.filter,maxRows:s.maxRows,matched:y.length}:{by:"rows",requested:E.size},columns:p.filter(S=>N.has(S.column.logicalName)).map(S=>S.column),rows:I,unchanged:T,excluded:O,missing:b,staleSinceRead:v}}ku.planDataFix=RNe;function kNe(e,t){if(e.kind==="lookup"&&t!==null&&typeof t=="object"&&!Array.isArray(t)){let n=t;return{table:n.table,id:n.id.toLowerCase()}}return Array.isArray(t)?[...t]:t}var l8=(e,t,n)=>Number.isInteger(e)&&e>=t&&e<=n;function $Ne(e){var t,n;if(e!==void 0&&!Qn(e))throw new Qe.InvalidArgumentError("applyDataFix options must be an object");let r=(t=e?.batchSize)!==null&&t!==void 0?t:hNe;if(!l8(r,1,o8))throw new Qe.InvalidArgumentError(`applyDataFix \`batchSize\` must be an integer 1..${o8}`);let i=(n=e?.maxThrottleWaitMs)!==null&&n!==void 0?n:bNe;if(!l8(i,0,a8))throw new Qe.InvalidArgumentError(`applyDataFix \`maxThrottleWaitMs\` must be an integer 0..${a8}`);return{batchSize:r,maxThrottleWaitMs:i}}function rn(e,t){return new Qe.DataFixError("DATA_FIX_PLAN_INVALID",`The data fix plan is invalid at ${e}: ${t}.`,void 0,e)}function JI(e,t){if(e===null||typeof e=="string"||typeof e=="boolean")return e;if(typeof e=="number"){if(!Number.isFinite(e))throw rn(t,"a number that is not finite");return e}if(Array.isArray(e))return e.map((n,r)=>JI(n,`${t}[${r}]`));if(Qn(e)){let n={};for(let r of Object.keys(e))Object.defineProperty(n,r,{value:JI(e[r],t===""?r:`${t}.${r}`),enumerable:!0,writable:!0,configurable:!0});return n}throw rn(t===""?"plan":t,"not a JSON value")}var LNe=new Set(["string","memo","integer","decimal","double","money","boolean","choice","state","status","multiSelect","dateTime","lookup"]);function MNe(e,t){let n=JI(e,"");if(!Qn(n)||n.kind!=="dataFixPlan")throw rn("kind","not 'dataFixPlan'");if(n.version!==1)throw rn("version","not 1");if(typeof n.planId!="string")throw rn("planId","not a string");if(n.instanceUrl!==t)throw new Qe.DataFixError("DATA_FIX_PLAN_OTHER_ORG","The data fix plan was read from another org; plan again on this one.");let r=n.table;for(let a of["logicalName","entitySetName","primaryIdAttribute","primaryNameAttribute"])if(!Qn(r)||!Kl(r[a]))throw rn(`table.${a}`,"not an OData name");if(!Qn(n.selection)||!["filter","rows","revert"].includes(String(n.selection.by)))throw rn("selection","not a selection");if(!Array.isArray(n.columns))throw rn("columns","not an array");let i=new Map;if(n.columns.forEach((a,s)=>{let u=a;if(!Qn(u)||!Kl(u.logicalName)||i.has(u.logicalName))throw rn(`columns[${s}].logicalName`,"not a distinct OData name");if(!LNe.has(String(u.kind)))throw rn(`columns[${s}].kind`,"not a kind a data fix writes");if(u.kind==="dateTime"&&!["UserLocal","DateOnly","TimeZoneIndependent"].includes(String(u.dateTimeBehavior)))throw rn(`columns[${s}].dateTimeBehavior`,"not a measured behaviour");if(u.kind==="lookup"){let l=u.lookupTarget;if(!Qn(l)||!Kl(l.table)||!Kl(l.entitySetName)||!Kl(l.navigationProperty))throw rn(`columns[${s}].lookupTarget`,"not a lookup target of OData names")}i.set(u.logicalName,u)}),!Array.isArray(n.rows)||n.rows.length>Ru)throw rn("rows",`not an array of at most ${Ru} rows`);let o=new Set;return n.rows.forEach((a,s)=>{let u=a,l=`rows[${s}]`;if(!Qn(u)||!(0,Wt.isGuid)(u.id))throw rn(`${l}.id`,"not a GUID");if(o.has(u.id.toLowerCase()))throw rn(`${l}.id`,"repeats an earlier row");if(o.add(u.id.toLowerCase()),!(0,Bo.isVersionToken)(u.etag)||/[\u0000-\u001F\u007F]/.test(u.etag))throw rn(`${l}.etag`,"not a row version token");if(u.name!==null&&typeof u.name!="string")throw rn(`${l}.name`,"not a string or null");let c=u.after;if(!Qn(c)||Object.keys(c).length===0||!Object.keys(c).every(m=>i.has(m)))throw rn(`${l}.after`,"not an object of planned columns");let d=u.before,f=Object.keys(c).sort().join(",");if(!Qn(d)||Object.keys(d).sort().join(",")!==f)throw rn(`${l}.before`,"not the same columns as after");let p=u.numericPrecision;for(let m of Object.keys(c)){let h=i.get(m),g;if((0,Wt.isNumericKind)(h.kind)&&(g=Qn(p)?p[m]:void 0,!oh(g)))throw rn(`${l}.numericPrecision.${m}`,"not an integer 0..10");if(!(0,Wt.hasPlanShape)(h,c[m],g))throw rn(`${l}.after.${m}`,`not a ${h.kind} value`);if(!(0,Wt.hasPlanShape)(h,d[m],g))throw rn(`${l}.before.${m}`,`not a ${h.kind} value`)}}),n}function xNe(e){var t;let n=(t=e.body)===null||t===void 0?void 0:t.error;return{...typeof n?.code=="string"?{code:n.code}:{},...typeof n?.message=="string"?{message:n.message}:{}}}function FNe(e,t,n,r){var i;let o=p=>({id:e.id,status:"applied",verification:"unverified",revertible:!1,diagnostic:p}),a=t.body;if(!Qn(a))return o("echoMissing");let s=a[r];if(!(0,Wt.isGuid)(s)||s.toLowerCase()!==e.id.toLowerCase())return o("echoIdentityMismatch");let u={};for(let p of Object.keys(e.after)){let m=(0,Wt.decodeValue)(n.get(p),a,(i=e.numericPrecision)===null||i===void 0?void 0:i[p]);if(!m.ok)return o(m.reason==="incompleteRead"?"echoFieldMissing":"echoValueUnsafe");u[p]=m.value}let l=a["@odata.etag"],c=m8(t.headers,"etag");if(!(0,Bo.isVersionToken)(l)||/[\u0000-\u001F\u007F]/.test(l)||c!==void 0&&c!==l)return o("echoTokenMissing");let d=Object.keys(e.after),f=(p,m)=>{var h;return(0,Wt.sameValue)(n.get(p),u[p],m[p],(h=e.numericPrecision)===null||h===void 0?void 0:h[p])};return{id:e.id,status:"applied",verification:d.every(p=>f(p,e.after))?"asPlanned":"notAsPlanned",revertible:d.some(p=>!f(p,e.before)),etag:l,stored:u}}function UNe(e,t,n,r){var i;if(t===void 0)return{kind:"outcome",outcome:{id:e.id,status:"unknown"}};let o=t.status,a={id:e.id,httpStatus:o,...xNe(t)};if(o>=200&&o<300)return{kind:"outcome",outcome:FNe(e,t,n,r)};if(o===412)return{kind:"outcome",outcome:{...a,status:"conflict"}};let s=(i=a.code)===null||i===void 0?void 0:i.toLowerCase();return o===400&&s===wNe||o===404&&s===ENe?{kind:"gone?",outcome:{...a,status:"failed"}}:(0,Bo.isServiceProtectionRefusal)(t)?{kind:"throttled",delayMs:(0,Bo.throttleDelayMs)(t)}:o>=400&&o<500?{kind:"outcome",outcome:{...a,status:"failed"}}:{kind:"outcome",outcome:{...a,status:"unknown"}}}function qNe(e,t,n){let i=Object.keys(e.after).map(u=>t.get(u)),o=[n.primaryIdAttribute,...i.map(Wt.readKey)].join(","),a=Object.assign({},...i.map(u=>(0,Wt.encodeValue)(u,e.after[u.logicalName]))),s=i.some(u=>u.kind==="lookup")?`return=representation,odata.include-annotations="${p8}"`:"return=representation";return{method:"PATCH",path:`/${n.entitySetName}(${e.id.toLowerCase()})?$select=${o}`,body:a,etag:e.etag,headers:{Prefer:s}}}function c8(e){let t=0;for(let n=0;n<e.length;n+=1){let r=e.charCodeAt(n);r<128?t+=1:r<2048?t+=2:r>=55296&&r<=56319?(t+=4,n+=1):t+=3}return t}function BNe(e){return c8(JSON.stringify(e.body))+c8(e.path)+yNe}function VNe(e){var t;let n=(t=m8(e.headers,"content-type"))!==null&&t!==void 0?t:"";return/^multipart\//i.test(n)||typeof e.body=="string"&&e.body.trimStart().startsWith("--")}function GNe(e){return new Promise(t=>setTimeout(t,e))}async function jNe(e,t){let{body:n,batchId:r,contentIds:i}=(0,zI.renderChangeSets)(e,t),o;try{o=await e.postBatch(n,r,{headers:{Prefer:"odata.continue-on-error"}})}catch{return{kind:"unknown",status:0}}let a=(0,zI.parseChangeSetsParts)(o.body,i);if(a){let s=new Map(a.map(u=>[u.contentId,(0,zI.partResponse)(u)]));return{kind:"rows",responses:i.map(u=>s.get(u))}}return(0,Bo.isServiceProtectionRefusal)(o)?{kind:"throttled",delayMs:(0,Bo.throttleDelayMs)(o)}:(o.status===401||o.status===403)&&!VNe(o)?{kind:"access",status:o.status}:{kind:"unknown",status:o.status}}async function WNe(e,t){var n;try{return{kind:"rows",responses:[await e.patch(t.path,t.body,{headers:{"If-Match":t.etag,...(n=t.headers)!==null&&n!==void 0?n:{}}})]}}catch{return{kind:"unknown",status:0}}}async function zNe(e,t,n){let r=[];for(let i=0;i<n.length;i+=Wb){let o=n.slice(i,i+Wb),a=new Set(o.map(u=>u.id.toLowerCase())),s;try{let u=`/${t.entitySetName}${(0,Si.odataQuery)([["$select",t.primaryIdAttribute],["$filter",b8(t.primaryIdAttribute,[...a])]])}`,l=await e.get(u),c=l.body,d=c?.value;l.status===200&&Array.isArray(d)&&(0,YI.pageEnd)(c).kind==="end"&&d.every(f=>Qn(f)&&(0,Wt.isGuid)(f[t.primaryIdAttribute])&&a.has(f[t.primaryIdAttribute].toLowerCase()))&&(s=new Set(d.map(f=>f[t.primaryIdAttribute].toLowerCase())))}catch{s=void 0}for(let u of o)s===void 0?r.push({...u,status:"failed",diagnostic:"absenceNotConfirmed"}):r.push({...u,status:s.has(u.id.toLowerCase())?"failed":"gone"})}return r}var HNe={DATA_FIX_REQUEST_UNKNOWN_OUTCOME:"A request ended without a readable answer, so whether its rows were written is unknown; the rest was not sent. Plan again: rows that did apply read back at their target values.",DATA_FIX_ACCESS_REFUSED:"The service refused the request before running it (authentication or authorization); the rest was not sent. Restore access and apply `remaining`.",DATA_FIX_THROTTLE_BUDGET_EXHAUSTED:"Service protection kept refusing the requests and the next wait would exceed the throttle budget; the rest was not sent. Apply `remaining` later.",DATA_FIX_REQUEST_NOT_SENT:"A request could not be built, so it and the rest were not sent."};async function KNe(e,t,n){let r=$Ne(n),i=MNe(t,h8(e)),o=QI(e);await g8(o,i.table.logicalName);let a=new Map(i.columns.map(b=>[b.logicalName,b])),s=i.table.primaryIdAttribute,u=new Map,l=[],c=[...i.rows],d=!e.supportsAtomicBatch,f=0,p=0,m=0,h,g=(b,E)=>{h={code:b,...E?{httpStatus:E}:{},message:HNe[b]}},y=b=>u.set(b.id,{id:b.id,status:"notAttempted"});for(;c.length>0&&h===void 0;){let b=[],E=[],w=0;for(;c.length>0&&b.length<(d?1:r.batchSize);){let O=qNe(c[0],a,i.table),v=BNe(O);if(b.length>0&&w+v>gNe)break;b.push(c.shift()),E.push(O),w+=v}let _;try{_=d?await WNe(e,E[0]):await jNe(e,E)}catch{b.forEach(y),g("DATA_FIX_REQUEST_NOT_SENT");break}let I=[],T=0;if(_.kind==="rows")b.forEach((O,v)=>{let N=UNe(O,_.kind==="rows"?_.responses[v]:void 0,a,s);N.kind==="throttled"?(I.push(O),T=Math.max(T,N.delayMs)):N.kind==="gone?"?l.push(N.outcome):u.set(O.id,N.outcome)});else if(_.kind==="throttled")I=b,T=_.delayMs;else if(_.kind==="access")b.forEach(y),g("DATA_FIX_ACCESS_REFUSED",_.status);else{let O=_.status;b.forEach(v=>u.set(v.id,{id:v.id,status:"unknown",...O?{httpStatus:O}:{}})),g("DATA_FIX_REQUEST_UNKNOWN_OUTCOME",O)}I.length>0&&(m>=vNe||p+T>r.maxThrottleWaitMs?(I.forEach(y),g("DATA_FIX_THROTTLE_BUDGET_EXHAUSTED")):(await GNe(T),p+=T,f+=1,m+=1,c.unshift(...I)))}c.forEach(y);for(let b of await zNe(o,i.table,l))u.set(b.id,b);return JNe(i,a,u,{waits:f,waitedMs:p},h)}ku.applyDataFix=KNe;function d8(e,t,n){let r=new Set(t.flatMap(i=>Object.keys(i.after)));return{...e,planId:(0,f8.newId)(),columns:e.columns.filter(i=>r.has(i.logicalName)),rows:t,unchanged:[],excluded:[],missing:[],staleSinceRead:[],...n}}function HI(e,t){return Object.fromEntries(t.map(n=>[n,e[n]]))}function JNe(e,t,n,r,i){let o=e.rows.map(c=>{var d;return(d=n.get(c.id))!==null&&d!==void 0?d:{id:c.id,status:"unknown"}}),a={applied:0,conflict:0,gone:0,failed:0,unknown:0,notAttempted:0},s={asPlanned:0,notAsPlanned:0,unverified:0};o.forEach(c=>{a[c.status]+=1,c.verification&&(s[c.verification]+=1)});let u=e.rows.filter(c=>{var d;return((d=n.get(c.id))===null||d===void 0?void 0:d.status)==="notAttempted"}),l=[];for(let c of e.rows){let d=n.get(c.id);if(d?.status!=="applied"||!d.revertible||!d.stored||!d.etag)continue;let f=d.stored,p=Object.keys(c.after).filter(h=>{var g;return!(0,Wt.sameValue)(t.get(h),f[h],c.before[h],(g=c.numericPrecision)===null||g===void 0?void 0:g[h])}),m=c.numericPrecision?HI(c.numericPrecision,p.filter(h=>{var g;return h in((g=c.numericPrecision)!==null&&g!==void 0?g:{})})):{};l.push({id:c.id,etag:d.etag,name:c.name,...Object.keys(m).length>0?{numericPrecision:m}:{},before:HI(f,p),after:HI(c.before,p)})}return{planId:e.planId,complete:a.notAttempted===0&&a.unknown===0,counts:a,verification:s,outcomes:o,remaining:u.length>0?d8(e,u,{}):null,revert:l.length>0?d8(e,l,{createdAt:(0,Bo.nowIso)(),selection:{by:"revert",ofPlanId:e.planId}}):null,throttle:r,...i?{stoppedBy:i}:{}}}});var D8=C(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 N8=Ke(),Vo=pe(),Xn=ae(),Jr=Y(),zb={read:"Read",create:"Create",write:"Write",delete:"Delete",append:"Append",appendTo:"AppendTo",assign:"Assign",share:"Share"},tT={user:"Basic",businessUnit:"Local",parentChild:"Deep",organization:"Global"},w8={user:1,businessUnit:2,parentChild:3,organization:4},eT={user:"CanBeBasic",businessUnit:"CanBeLocal",parentChild:"CanBeDeep",organization:"CanBeGlobal"};Or.SDK_ROLE_MARKER="Authored by @maker-studio/cds-maker-sdk (persona/security role).";function YNe(e){return Object.prototype.hasOwnProperty.call(zb,e)?zb[e]:void 0}function QNe(e){return Object.prototype.hasOwnProperty.call(tT,e)}var E8=new WeakMap,A8=new WeakMap;async function _8(e,t){var n,r;(0,Xn.assertODataName)(t,"entity logical name");let i=E8.get(e);i||(i=new Map,E8.set(e,i));let o=i.get(t);if(o)return o;let a=`/EntityDefinitions(LogicalName='${(0,Xn.odataPathLiteral)(t)}')${(0,Xn.odataQuery)([["$select","LogicalName,Privileges"]])}`,u=(r=(n=(0,Vo.ensureSuccess)(await e.get(a),e.apiUrl(a)).body)===null||n===void 0?void 0:n.Privileges)!==null&&r!==void 0?r:[];if(u.length===0)throw new Jr.InvalidArgumentError(`Entity '${t}' exposes no privileges (unknown or non-securable entity).`);return i.set(t,u),u}async function XNe(e){var t,n,r;let i=A8.get(e);if(i)return i;let o=`/businessunits${(0,Xn.odataQuery)([["$select","businessunitid"],["$filter","_parentbusinessunitid_value eq null"],["$top",1]])}`,u=(r=((n=(t=(0,Vo.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||t===void 0?void 0:t.value)!==null&&n!==void 0?n:[])[0])===null||r===void 0?void 0:r.businessunitid;if(!u)throw new Jr.InvalidArgumentError("Could not resolve the root business unit.");let l=(0,Xn.normalizeGuid)(u,"businessUnitId");return A8.set(e,l),l}async function I8(e,t){var n;let r=new Map;for(let i of t){if(!i.access||i.access.length===0)throw new Jr.InvalidArgumentError(`Entity '${i.entity}' privilege request has no access levels.`);let o=(n=i.scope)!==null&&n!==void 0?n:"user";if(!QNe(o))throw new Jr.InvalidArgumentError(`Unknown privilege scope '${o}' for entity '${i.entity}'.`);let a=await _8(e,i.entity);for(let s of i.access){let u=YNe(s);if(!u)throw new Jr.InvalidArgumentError(`Unknown access level '${s}' for entity '${i.entity}'.`);let l=a.find(m=>m.PrivilegeType===u);if(!l)throw new Jr.InvalidArgumentError(`Entity '${i.entity}' does not support '${s}' access.`);let c=eT[o];if(l[c]===!1)throw new Jr.InvalidArgumentError(`Privilege '${l.Name}' on '${i.entity}' does not support the '${o}' scope.`);let d=(0,Xn.normalizeGuid)(l.PrivilegeId,"PrivilegeId"),f=r.get(d);if(!f){r.set(d,{privilegeName:l.Name,privilegeType:u,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 Jr.InvalidArgumentError(`Entities '${m}' and '${i.entity}' share the Dataverse privilege '${l.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=w8[o]>w8[f.scope]?o:f.scope}}return[...r.entries()].map(([i,o])=>({entity:[...o.entities].sort().join(", "),privilegeId:i,privilegeName:o.privilegeName,privilegeType:o.privilegeType,scope:o.scope}))}async function ZNe(e,t,n,r){if(n.length===0&&!r)return;let i={Privileges:n.map(a=>({Depth:tT[a.scope],PrivilegeId:a.privilegeId}))},o=`/roles(${t})/Microsoft.Dynamics.CRM.ReplacePrivilegesRole`;(0,Vo.ensureSuccess)(await e.post(o,i),e.apiUrl(o))}async function C8(e,t,n,r,i){var o,a;let s=`/${t}(${n})/${r}${(0,Xn.odataQuery)([["$select","roleid"],["$filter",`roleid eq ${i}`]])}`,u=(0,Vo.ensureSuccess)(await e.get(s),e.apiUrl(s)),l=(a=(o=u.body)===null||o===void 0?void 0:o.value)!==null&&a!==void 0?a:[];if(!(0,N8.boundedPageComplete)(u.body,l.length))throw new Jr.ConnectionError(e.apiUrl(s),u.status,"the role membership read answered no row but says more rows exist, so whether the role is held is unknown");return l.length>0}async function e_e(e,t,n){var r,i;let o=[],a=[],s={"@odata.id":e.apiUrl(`/roles(${t})`)};for(let u of(r=n?.teams)!==null&&r!==void 0?r:[]){let l=(0,Xn.normalizeGuid)(u,"teamId");if(!await C8(e,"teams",l,"teamroles_association",t)){let c=`/teams(${l})/teamroles_association/$ref`;(0,Vo.ensureSuccess)(await e.post(c,s),e.apiUrl(c))}o.push(l)}for(let u of(i=n?.users)!==null&&i!==void 0?i:[]){let l=(0,Xn.normalizeGuid)(u,"userId");if(!await C8(e,"systemusers",l,"systemuserroles_association",t)){let c=`/systemusers(${l})/systemuserroles_association/$ref`;(0,Vo.ensureSuccess)(await e.post(c,s),e.apiUrl(c))}a.push(l)}return{teams:o,users:a}}async function S8(e,t,n){var r,i;let o=`/roles${(0,Xn.odataQuery)([["$select","roleid,description,ismanaged"],["$filter",`name eq '${(0,Xn.odataLiteral)(t)}' and _businessunitid_value eq ${n}`]])}`,a=(0,Vo.ensureSuccess)(await e.get(o),e.apiUrl(o)),s=(i=(r=a.body)===null||r===void 0?void 0:r.value)!==null&&i!==void 0?i:[];if((0,N8.pageEnd)(a.body).kind!=="end")throw new Jr.ConnectionError(e.apiUrl(o),a.status,`the read of the roles named '${t}' says more rows exist, so whether a role the SDK does not own shares the name is unknown`);let u=s.filter(d=>!!d.roleid);if(u.length===0)return;let l=d=>{var f;return d.ismanaged!==!0&&((f=d.description)!==null&&f!==void 0?f:"")===Or.SDK_ROLE_MARKER};if(u.some(d=>!l(d)))throw new Jr.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(u.length>1)throw new Jr.InvalidArgumentError(`Multiple (${u.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=u[0].roleid;return c?(0,Xn.normalizeGuid)(c,"roleId"):void 0}function t_e(e){var t,n;return{teams:((t=e?.teams)!==null&&t!==void 0?t:[]).map(r=>(0,Xn.normalizeGuid)(r,"teamId")),users:((n=e?.users)!==null&&n!==void 0?n:[]).map(r=>(0,Xn.normalizeGuid)(r,"userId"))}}function T8(e){return e.map(t=>({entity:t.entity,privilegeName:t.privilegeName,privilegeType:t.privilegeType,scope:t.scope}))}async function O8(e,t){var n,r;let i=(n=t.name)===null||n===void 0?void 0:n.trim();if(!i)throw new Jr.InvalidArgumentError("createSecurityRole: a non-empty role name is required.");let o=t.businessUnitId?(0,Xn.normalizeGuid)(t.businessUnitId,"businessUnitId"):await XNe(e),a=await I8(e,(r=t.privileges)!==null&&r!==void 0?r:[]),s=t_e(t.assignTo),u=await S8(e,i,o),l=u!==void 0;if(!u){let d="/roles",f={name:i,description:Or.SDK_ROLE_MARKER,"[email protected]":`/businessunits(${o})`};try{let p=(0,Vo.ensureSuccess)(await e.post(d,f),e.apiUrl(d));u=(0,Xn.normalizeGuid)((0,Vo.requireCreatedId)(p,"roleid","role"),"roleId")}catch(p){let m;try{m=await S8(e,i,o)}catch{m=void 0}if(!m)throw p;u=m}}await ZNe(e,u,a,l);let c=await e_e(e,u,s);return{roleId:u,name:i,reused:l,appliedPrivileges:T8(a),assignedTeams:c.teams,assignedUsers:c.users}}Or.createSecurityRole=O8;async function n_e(e,t){var n,r;let i=(n=t.persona)===null||n===void 0?void 0:n.trim();if(!i)throw new Jr.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:[]}),...(r=t.additionalPrivileges)!==null&&r!==void 0?r:[]];return O8(e,{name:i,businessUnitId:t.businessUnitId,privileges:o,assignTo:t.assignTo})}Or.createPersonaRole=n_e;async function r_e(e,t){let r=`/roles(${(0,Xn.normalizeGuid)(t,"roleId")})`;(0,Vo.ensureSuccess)(await e.delete(r),e.apiUrl(r))}Or.deleteSecurityRole=r_e;async function i_e(e,t,n){let r=(0,Xn.normalizeGuid)(t,"roleId");if(n.length===0)throw new Jr.InvalidArgumentError("addEntityPrivilegesToRole requires at least one entity privilege (an empty grant would be a silent no-op).");let i=await I8(e,n),o={Privileges:i.map(s=>({Depth:tT[s.scope],PrivilegeId:s.privilegeId}))},a=`/roles(${r})/Microsoft.Dynamics.CRM.AddPrivilegesRole`;return(0,Vo.ensureSuccess)(await e.post(a,o),e.apiUrl(a)),T8(i)}Or.addEntityPrivilegesToRole=i_e;var o_e=new Map(Object.keys(zb).map(e=>[zb[e],e]));async function a_e(e,t){return(await _8(e,t)).map(r=>{let i=Object.keys(eT).filter(a=>r[eT[a]]!==!1),o=o_e.get(r.PrivilegeType);return{name:r.Name,privilegeId:r.PrivilegeId,privilegeType:r.PrivilegeType,...o?{access:o}:{},scopes:i}})}Or.getEntityPrivileges=a_e});var J8=C(Pr=>{"use strict";Object.defineProperty(Pr,"__esModule",{value:!0});Pr.createMakerSdk=Pr.MakerSdk=Pr.PUSH_NOT_ATTEMPTED_CODE=Pr.ALREADY_EXISTS_CODE=void 0;var P8=Mv(),R8=mo(),le=Y(),co=ec(),s_e=eD(),W8=sD(),mf=pD(),u_e=Fv(),k8=$D(),l_e=aw(),nT=hk(),hf=wk(),c_e=$k(),d_e=vE(),$8=g$(),L8=AA(),f_e=sM(),p_e=Ya(),M8=mM(),Zn=u0(),m_e=VM(),rT=mg(),iT=KM(),Hb=Sc(),Ns=p0(),Kb=ZE(),gf=Ff(),h_e=h0(),x8=hA(),Mn=il(),g_e=Jc(),y_e=C0(),b_e=S0(),F8=gC(),v_e=Nw(),U8=_w(),w_e=j9(),Jb=ft(),E_e=fl(),Go=Eu(),fo=Rs(),oT=tI(),A_e=3e5,Dr=pe(),Yl=ae(),yf=QE(),q8=X9(),C_e=e8(),B8=v8(),S_e=IN(),ah=D8(),z8=Symbol("cds-maker-sdk.committedWrite");function N_e(e){return typeof e=="object"&&e!==null&&(e[z8]=!0),e}function __e(e){return typeof e=="object"&&e!==null&&e[z8]===!0}var I_e={fileConcurrency:1},aT="SOLUTION_COMPONENT_UNCLASSIFIED",T_e=2,O_e=4,D_e="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 sT(e){return{componentId:e.objectId,componentType:e.componentType,workflowCategory:e.workflowCategory,reason:"unsupported",...e.includesAllSubcomponents?{detail:D_e}:{}}}function sh(e,t){return{componentId:e.objectId,componentType:e.componentType,workflowCategory:e.workflowCategory,reason:"failed",error:$u(t)}}function V8(e,t,n){let r=n;return{type:e,id:t.objectId,name:typeof r.name=="string"?r.name:t.objectId,entityLogicalName:typeof r.entityLogicalName=="string"?r.entityLogicalName:void 0,lastFetched:(0,Dr.nowIso)(),isDirty:!1}}var P_e=new Set(["entity","appmodule","dashboard","uxagentproject"]);function R_e(e){var t;let n={entity:[],appmodule:[],dashboard:[],uxagentproject:[]},r=new Set,i=(s,u)=>{let l=`${s}\0${u.toLowerCase()}`;r.has(l)||(r.add(l),n[s].push(u))};for(let{scope:s}of e)if(s?.envelope==="entity")s.entityLogicalName&&i("entity",s.entityLogicalName);else if(s&&s.envelope!=="webresource")for(let u of(t=s.targetIds)!==null&&t!==void 0?t:[])i(s.envelope,u);let o=(s,u,l)=>l.length>0?`<${s}>${l.map(c=>`<${u}>${(0,Yl.xmlText)(c)}</${u}>`).join("")}</${s}>`:"",a=o("entities","entity",n.entity)+o("appmodules","appmodule",n.appmodule)+o("dashboards","dashboard",n.dashboard)+o("uxagentprojects","uxagentproject",n.uxagentproject);return a?`<importexportxml>${a}</importexportxml>`:void 0}function k_e(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 W8.WorkspaceManager(L_e,e.instanceUrl,(0,u_e.assertStorageContract)(t))}Pr.ALREADY_EXISTS_CODE="ARTIFACT_ALREADY_EXISTS";var $_e="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";Pr.PUSH_NOT_ATTEMPTED_CODE="PUSH_NOT_ATTEMPTED";var L_e="<injected workspaceStorage>",Qb=class e{constructor(t){var n,r;if(this.promotionIssued=new L8.IssuedPlans,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 le.InvalidArgumentError(`createRecovery must be 'adoptExact' or omitted (got '${String(t.createRecovery)}').`);this.createRecovery=t.createRecovery,this.readConcurrency=(0,oT.resolveReadConcurrency)(t.readConcurrency),this.genPageIteration=(0,F8.resolveGenPageIteration)(t.genPageIteration),this.languageCode=(n=t.languageCode)!==null&&n!==void 0?n:E_e.DEFAULT_LCID,this.cacheStalenessMs=(r=t.cacheStalenessMs)!==null&&r!==void 0?r:A_e,this.compiler={load:(0,F8.createGenPageTypeScriptLoader)(t.typescript)},this.workspace=k_e(t),this.versions=new mf.VersionManager(this.workspace),this.dataverse=new k8.DataverseClient(t.instanceUrl,t.httpClient,t.solutionUniqueName,this.readConcurrency),this.connectivity=new $8.ConnectivityRouter(this.dataverse,t.instanceUrl,{powerAppsServiceClient:t.powerAppsServiceClient,powerPlatformApiClient:t.powerPlatformApiClient,connectorRuntimeClient:t.connectorRuntimeClient}),this.registrations=(0,w_e.buildRegistrations)(this.languageCode),this.promotionConnectivity={instanceUrl:t.instanceUrl,clients:{powerAppsServiceClient:t.powerAppsServiceClient,powerPlatformApiClient:t.powerPlatformApiClient}}}async initWorkspace(){await this.workspace.init()}async getManifest(){return this.workspace.getManifest()}async cleanWorkspace(){await this.workspace.clean()}withArtifactLock(t,n,r){var i;let o=this.artifactKey(t,n),s=((i=this.artifactLocks.get(o))!==null&&i!==void 0?i:Promise.resolve()).then(r,r),u=s.then(()=>{},()=>{});return this.artifactLocks.set(o,u),u.then(()=>{this.artifactLocks.get(o)===u&&this.artifactLocks.delete(o)}),s}async fetchArtifact(t,n,r){return this.withArtifactLock(t,n,async()=>{let i=await this.fetchArtifactUnlocked(t,n,r);return await this.acknowledgeRefresh(t,n),i})}async fetchArtifactUnlocked(t,n,r){let i=this.requireRegistration(t,"fetchArtifact"),o=await i.api.get(this.dataverse,n);return this.applyFetchedArtifactUnlocked(t,n,i,o,r)}async applyFetchedArtifactUnlocked(t,n,r,i,o){var a,s,u;let{raw:l,etag:c,memberEtags:d,siblingEtags:f}=i,p=r.adapter.fromApiResponse(l);if(!o?.overwrite&&await this.versions.isDirty(t,n)){let h=(s=(a=await this.versions.getMeta(t,n))===null||a===void 0?void 0:a.etag)!==null&&s!==void 0?s:null;if(h&&c&&h!==c)throw new le.LocalEditsWouldBeLostError(t,n,h,c);let g=await this.workspace.readArtifact(t,n);if(g){let y=await this.versions.getMeta(t,n);if(y&&!y.etag&&c){if(!(0,fo.deepEqual)(y.snapshot,p))throw new le.LocalEditsWouldBeLostError(t,n,h,c);await this.versions.storeMeta(t,n,{...y,etag:c,fetchedAt:(0,Dr.nowIso)()},y)}return(0,Go.cloneJson)(g)}}await this.workspace.writeArtifact(t,n,p);let m=await this.versions.getMeta(t,n);return await this.versions.storeMeta(t,n,{etag:c,languageCode:this.languageCode,projectionVersion:mf.PROJECTION_VERSION,fetchedAt:(0,Dr.nowIso)(),snapshot:(0,Go.cloneJson)(p),...d?{memberEtags:d}:{},...f?{siblingEtags:f}:{},...m?.refreshGeneration?{refreshGeneration:m.refreshGeneration,observedGeneration:(u=m.observedGeneration)!==null&&u!==void 0?u:0}:{}},m),(0,Go.cloneJson)(p)}async fetchArtifactList(t,n){return this.requireRegistration(t,"fetchArtifactList").api.list(this.dataverse,n)}async fetchSolution(t){await this.workspace.ensureReady();let n=await(0,Mn.fetchSolutionComponents)(this.dataverse,t),r=[],i=[],o=await(0,g_e.foldVariableValueComponents)(this.dataverse,n);for(let{component:l,error:c}of o.failed)i.push(sh(l,c));let a=await(0,y_e.foldCustomApiChildComponents)(this.dataverse,o.components);for(let{component:l,error:c}of a.failed)i.push(sh(l,c));let s=await(0,b_e.foldDuplicateRuleConditionComponents)(this.dataverse,a.components);for(let{component:l,error:c}of s.failed)i.push(sh(l,c));for(let{component:l,detail:c}of s.orphaned)i.push({...sT(l),detail:c});let u=s.components;if(this.readConcurrency>1)await this.fetchComponentsOverlapped(u,r,i);else for(let l of u)try{let c=await this.resolveComponentType(l);if(!c){i.push(sT(l));continue}let d=await this.fetchArtifact(c,l.objectId);r.push(V8(c,l,d))}catch(c){i.push(sh(l,c))}return await this.workspace.updateManifest({lastSyncAt:(0,Dr.nowIso)()}),{summaries:r,skipped:i}}async fetchComponentsOverlapped(t,n,r){await(0,oT.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"){r.push(sT(o));return}let s=await this.applyFetchedArtifactUnlocked(a.type,o.objectId,a.reg,a.fetched);await this.acknowledgeRefresh(a.type,o.objectId),n.push(V8(a.type,o,s))}catch(a){r.push(sh(o,a))}})}async beginComponentRead(t){let n=await this.resolveComponentType(t);return n?this.lockedRead(n,t.objectId,async()=>{let r=this.requireRegistration(n,"fetchArtifact"),i=await r.api.get(this.dataverse,t.objectId,I_e);return{kind:"artifact",type:n,reg:r,fetched:i}}):(0,oT.plainRead)(async()=>({kind:"unsupported"}))}lockedRead(t,n,r){let i,o=new Promise(l=>{i=l}),a,s=new Promise(l=>{a=l}),u=this.withArtifactLock(t,n,async()=>{try{i({ok:!0,value:await r()})}catch(c){i({ok:!1,error:c})}let l=await s;await l?.()});return{outcome:o,finish:l=>(a(l),u),discard:async()=>{a(void 0),await u}}}async fetchEntityMetadata(t){return this.fetchEntityMetadataVia(t,this.dataverse)}async fetchEntityMetadataVia(t,n){let r=t.toLowerCase(),i=this.schemaEpoch(r),o=await(0,hf.fetchEntityMetadataFromApi)(n,t);if(this.schemaEpoch(r)!==i)return o;let a=this.workspace.writeEntityMetadata(t,o),s={key:r,settled:a.then(()=>{},()=>{})};this.metadataPublications.add(s);try{await a}finally{this.metadataPublications.delete(s)}return this.schemaEpoch(r)===i&&this.undroppedMetadata.delete(r),o}schemaEpoch(t){var n,r;return`${(n=this.schemaWrites.get("*"))!==null&&n!==void 0?n:0}:${(r=this.schemaWrites.get(t.toLowerCase()))!==null&&r!==void 0?r:0}`}async schemaWrite(t,n){try{return await n()}finally{await this.forgetEntityMetadata(t)}}async forgetEntityMetadata(t){let n=i=>{var o;this.schemaWrites.set(i,((o=this.schemaWrites.get(i))!==null&&o!==void 0?o:0)+1)};if(t===void 0){n("*"),await this.publicationsSettled(void 0),await this.dropCachedMetadata(void 0);return}let r=[...new Set(t.filter(i=>typeof i=="string"&&i!=="").map(i=>i.toLowerCase()))];r.forEach(n),await this.publicationsSettled(r);for(let i of r)await this.dropCachedMetadata(i)}async publicationsSettled(t){let n=t===void 0?void 0:new Set(t);await Promise.all([...this.metadataPublications].filter(r=>n===void 0||n.has(r.key)).map(r=>r.settled))}async dropCachedMetadata(t){try{await this.workspace.dropEntityMetadata(t)}catch(n){n instanceof le.WorkspaceNotInitializedError||n instanceof le.WorkspaceOrgMismatchError||this.undroppedMetadata.add(t??"*");return}t===void 0?this.undroppedMetadata.clear():this.undroppedMetadata.delete(t)}async readCachedEntityMetadata(t){let n=t.toLowerCase();return this.undroppedMetadata.has("*")&&await this.dropCachedMetadata(void 0),this.undroppedMetadata.has(n)&&await this.dropCachedMetadata(n),this.undroppedMetadata.has("*")||this.undroppedMetadata.has(n)?null:this.workspace.readEntityMetadata(t)}loadMissedEntityMetadata(t,n=this.dataverse){let r=this.schemaEpoch(t),i=this.entityMetadataLoads.get(t);if(i&&this.entityMetadataLoadEpochs.get(i)===r)return i;let o=this.fetchEntityMetadataVia(t,n).then(()=>{});this.entityMetadataLoads.set(t,o),this.entityMetadataLoadEpochs.set(o,r);let a=()=>{this.entityMetadataLoads.get(t)===o&&this.entityMetadataLoads.delete(t)};return o.then(a,a),o}generateGenPageRuntimeTypes(t,n){return(0,c_e.generateGenPageRuntimeTypes)(r=>this.fetchEntityMetadata(r),t,n)}findTables(t,n){return(0,hf.findTables)(this.dataverse,t,n)}getEnvironmentLanguages(){return(0,d_e.getEnvironmentLanguages)(this.dataverse)}listConnections(){return this.connectivity.listConnections()}listConnectorOperations(t){return this.connectivity.listConnectorOperations(t)}getConnectorOperationSchema(t,n){return this.connectivity.getConnectorOperationSchema(t,n)}listConnectorTables(t,n,r){return this.connectivity.listConnectorTables(t,n,r)}getConnectorTableSchema(t,n,r,i){return this.connectivity.getConnectorTableSchema(t,n,r,i)}findColumns(t,n,r){return(0,hf.findColumns)(this.dataverse,t,n,r)}createTable(t){return this.schemaWrite([t.schemaName],()=>(0,Zn.createTable)(this.dataverse,t))}createColumn(t,n){return this.schemaWrite([t],()=>(0,Zn.createColumn)(this.dataverse,t,n))}createColumns(t,n){return this.schemaWrite([t],()=>(0,Zn.createColumns)(this.dataverse,t,n))}updateColumn(t,n,r){return this.schemaWrite([t],()=>(0,Zn.updateColumn)(this.dataverse,t,n,r))}deleteColumn(t,n){return this.schemaWrite([t],()=>(0,Zn.deleteColumn)(this.dataverse,t,n))}setFormSecurityRoles(t,n){return(0,rT.setFormSecurityRoles)(this.dataverse,t,n)}getFormSecurityRoles(t){return(0,rT.getFormSecurityRoles)(this.dataverse,t)}setColumnVisualization(t,n,r){return(0,Zn.setColumnVisualization)(this.dataverse,t,n,r)}getColumnVisualization(t,n){return(0,Zn.getColumnVisualization)(this.dataverse,t,n)}createCustomerColumn(t,n){return this.schemaWrite([t,"account","contact"],()=>(0,Zn.createCustomerColumn)(this.dataverse,t,n))}insertStatusValue(t,n){return this.schemaWrite([t],()=>(0,Zn.insertStatusValue)(this.dataverse,t,n))}updateTable(t,n){return this.schemaWrite([t],()=>(0,Zn.updateTable)(this.dataverse,t,n))}async setEntityIcon(t,n){if(await this.schemaWrite([t],()=>(0,Zn.updateTable)(this.dataverse,t,{iconVectorName:n.vector,iconSmallName:n.small,iconMediumName:n.medium,iconLargeName:n.large})),n.publish!==!1){let r=`<importexportxml><entities><entity>${(0,Yl.xmlText)(t)}</entity></entities></importexportxml>`;(0,Dr.ensureSuccess)(await this.dataverse.post("/PublishXml",{ParameterXml:r}),this.dataverse.apiUrl("/PublishXml"))}}createAlternateKey(t,n){return(0,Zn.createAlternateKey)(this.dataverse,t,n)}deleteAlternateKey(t,n){return(0,Zn.deleteAlternateKey)(this.dataverse,t,n)}createRelationship(t){let n=t.type==="ManyToMany"?[t.entity1,t.entity2]:[t.referencedEntity,t.referencingEntity];return this.schemaWrite(n,()=>(0,Zn.createRelationship)(this.dataverse,t))}deleteRelationship(t){return this.schemaWrite(void 0,()=>(0,Zn.deleteRelationship)(this.dataverse,t))}createGlobalOptionSet(t){return(0,Zn.createGlobalOptionSet)(this.dataverse,t)}deleteGlobalOptionSet(t){return(0,Zn.deleteGlobalOptionSet)(this.dataverse,t)}deleteTable(t){return this.schemaWrite(void 0,()=>(0,Zn.deleteTable)(this.dataverse,t))}createSecurityRole(t){return(0,ah.createSecurityRole)(this.dataverse,t)}createPersonaRole(t){return(0,ah.createPersonaRole)(this.dataverse,t)}deleteSecurityRole(t){return(0,ah.deleteSecurityRole)(this.dataverse,t)}addEntityPrivilegesToRole(t,n){return(0,ah.addEntityPrivilegesToRole)(this.dataverse,t,n)}getEntityPrivileges(t){return(0,ah.getEntityPrivileges)(this.dataverse,t)}createRecord(t,n){return(0,Ns.createRecord)(this.dataverse,t,n)}createRecordsBulk(t,n){return(0,Ns.createRecordsBulk)(this.dataverse,t,n)}updateRecord(t,n,r){return(0,Ns.updateRecord)(this.dataverse,t,n,r)}upsertRecord(t,n,r,i){return(0,Ns.upsertRecord)(this.dataverse,t,n,r,i)}deleteRecord(t,n){return(0,Ns.deleteRecord)(this.dataverse,t,n)}getRecord(t,n,r){return(0,Ns.getRecord)(this.dataverse,t,n,r)}queryRecords(t,n){return(0,Ns.queryRecords)(this.dataverse,t,n)}seedRecordGraph(t,n){return(0,C_e.seedRecordGraph)(this.dataverse,t,n)}resolveArtifact(t,n){return(0,q8.resolveArtifact)(this.dataverse,t,n)}findArtifact(t,n){return(0,q8.findArtifact)(this.dataverse,t,n)}async deleteAppCascade(t,n){await this.workspace.ensureReady();let r=await(0,v_e.deleteAppCascade)(this.dataverse,t,n),i=(0,Yl.normalizeGuid)(t,"appModuleId");return await this.workspace.readArtifact("app",i)&&await this.workspace.deleteArtifact("app",i),r}associateRecords(t,n,r){return(0,Ns.associateRecords)(this.dataverse,t,n,r)}disassociateRecords(t,n,r,i){return(0,Ns.disassociateRecords)(this.dataverse,t,n,r,i)}createWebResource(t){return(0,Kb.createWebResource)(this.dataverse,t)}updateWebResource(t,n){return(0,Kb.updateWebResource)(this.dataverse,t,n)}getWebResource(t){return(0,Kb.getWebResource)(this.dataverse,t)}deleteWebResource(t){return(0,Kb.deleteWebResource)(this.dataverse,t)}getAppSettings(t){return(0,gf.readAppSettings)(this.dataverse,t)}setAppSetting(t,n,r){return(0,gf.setAppSetting)(this.dataverse,t,n,r)}setHeaderAndNavigationRefresh(t,n){if(typeof n!="boolean")throw new le.ValidationError("app",t,[{pointer:"/headerAndNavigationRefresh",rule:h_e.HEADER_NAV_BOOLEAN_RULE,message:`enabled must be a boolean, got ${typeof n}`}]);return(0,gf.setAppSetting)(this.dataverse,t,gf.HEADER_AND_NAVIGATION_REFRESH,n?gf.APP_SETTING_ON:gf.APP_SETTING_OFF)}getAppTheme(t){return(0,x8.getAppTheme)(this.dataverse,t)}setAppTheme(t,n,r){return this.withArtifactLock("app",String(t),()=>(0,x8.setAppTheme)(this.dataverse,t,n,r??{}))}getSolution(t){return(0,Mn.getSolution)(this.dataverse,t)}createPublisher(t){return(0,Mn.createPublisher)(this.dataverse,t)}createSolution(t){return(0,Mn.createSolution)(this.dataverse,t)}setSolutionVersion(t,n){return(0,Mn.setSolutionVersion)(this.dataverse,t,n)}addSolutionComponent(t){return(0,Mn.addSolutionComponent)(this.dataverse,t)}removeSolutionComponent(t,n,r){return(0,Mn.removeSolutionComponent)(this.dataverse,t,n,r)}exportSolution(t){return(0,Mn.exportSolution)(this.dataverse,t)}importSolution(t){return this.schemaWrite(void 0,()=>(0,Mn.importSolution)(this.dataverse,t))}getDeploymentSettingsTemplate(t){return(0,Mn.getDeploymentSettingsTemplate)(this.dataverse,t)}deleteSolution(t){return this.schemaWrite(void 0,()=>(0,Mn.deleteSolution)(this.dataverse,t))}async inspectArtifact(t,n,r){var i;if(t!=="command"&&t!=="dashboard")throw new le.SdkError(le.INSPECTION_NOT_SUPPORTED_CODE,`inspectArtifact inspects 'command' and 'dashboard' only, not '${String(t)}'. Read another type with fetchArtifact.`);let o=(i=this.registrations.get(t))===null||i===void 0?void 0:i.inspect;if(!o)throw new le.SdkError(le.INSPECTION_NOT_SUPPORTED_CODE,`No inspection is registered for '${t}'.`);let a=(0,k8.readOnlyDataverse)(this.dataverse),s={languageCode:this.languageCode};if(t==="dashboard")return o(a,n,r,s);try{return await o(a,n,r,s)}catch(u){let l=u?.code;throw u instanceof le.InvalidArgumentError||l===le.INSPECTION_UNREADABLE_CODE?u:(0,l_e.inspectionUnreadable)(n,u)}}async getArtifact(t,n){return this.withArtifactLock(t,n,async()=>{let{artifact:r,meta:i}=await this.readWhole(t,n);return await this.acknowledgeRefresh(t,n,i),r})}async getArtifactUnlocked(t,n){return this.readRaw(t,n)}async readWhole(t,n){let{meta:r}=await this.revalidate(t,n);return{artifact:await this.readLocal(t,n),meta:r}}async acknowledgeRefresh(t,n,r){var i,o,a;let s=this.artifactKey(t,n),u=r===void 0?await this.versions.getMeta(t,n):r;this.baselineObserved.has(s)||this.baselineObserved.set(s,(i=u?.observedGeneration)!==null&&i!==void 0?i:0);let l=(o=u?.refreshGeneration)!==null&&o!==void 0?o:0;this.raiseGenerationHighWater(s,l),u&&l!==((a=u.observedGeneration)!==null&&a!==void 0?a:0)&&await this.versions.storeMeta(t,n,{...u,observedGeneration:l},u),this.observedGenerations.set(s,l)}raiseGenerationHighWater(t,n){var r;n>((r=this.generationHighWater.get(t))!==null&&r!==void 0?r:0)&&this.generationHighWater.set(t,n)}async observedAtInvocation(t,n,r){var i,o;if(r!==void 0)return r;let a=this.baselineObserved.get(this.artifactKey(t,n));return a!==void 0?a:(o=(i=await this.versions.getMeta(t,n))===null||i===void 0?void 0:i.observedGeneration)!==null&&o!==void 0?o:0}artifactKey(t,n){return`${t}\0${(0,W8.canonicalArtifactId)(n)}`}nextRefreshGeneration(t,n,r){var i,o,a;let s=this.artifactKey(t,n),u=Math.max((i=r?.refreshGeneration)!==null&&i!==void 0?i:0,(o=r?.observedGeneration)!==null&&o!==void 0?o:0,(a=this.generationHighWater.get(s))!==null&&a!==void 0?a:0)+1;return this.raiseGenerationHighWater(s,u),u}async readRaw(t,n){return await this.revalidateIfStale(t,n),this.readLocal(t,n)}async readForMutation(t,n,r,i){var o,a;let s=await this.observedAtInvocation(t,n,i);if(((a=(o=await this.versions.getMeta(t,n))===null||o===void 0?void 0:o.refreshGeneration)!==null&&a!==void 0?a:0)>s)throw new le.StaleArtifactError(t,n,r,"pushed");if(await this.revalidateIfStale(t,n)==="refreshed-changed")throw new le.StaleArtifactError(t,n,r);return this.readLocal(t,n)}async readLocal(t,n){let r=await this.workspace.readArtifact(t,n);if(!r)throw new le.ArtifactNotFoundError(t,n);return r}async revalidateIfStale(t,n){return(await this.revalidate(t,n)).outcome}async revalidate(t,n){let r=await this.versions.getMeta(t,n);if(!r)return{outcome:"skipped",meta:null};let i=r.fetchedAt?Date.parse(r.fetchedAt):NaN,o=Date.now()-i;if(!Number.isNaN(i)&&this.cacheStalenessMs>0&&o<=this.cacheStalenessMs)return{outcome:"fresh",meta:r};if(await this.versions.isDirty(t,n,r))return{outcome:"skipped",meta:r};let a=await this.workspace.readArtifact(t,n);await this.fetchArtifactUnlocked(t,n);let s=await this.workspace.readArtifact(t,n);return{outcome:(0,fo.deepEqual)(a,s)?"refreshed-unchanged":"refreshed-changed"}}async queryTree(t,n,r){return this.withArtifactLock(t,n,async()=>{let{artifact:i,meta:o}=await this.readWhole(t,n),a=co.JsonPointer.resolve(i,r);if(a===void 0)throw new le.PathNotFoundError(t,n,r);return r===""&&await this.acknowledgeRefresh(t,n,o),a})}async findElements(t,n,r){return this.withArtifactLock(t,n,async()=>(0,s_e.findElements)(await this.getArtifactUnlocked(t,n),r))}async withDirtyFlags(t){let n=[];for(let r of t)n.push({...r,isDirty:await this.versions.isDirty(r.type,r.id)});return n}async listArtifacts(t,n){return this.withDirtyFlags(await this.workspace.listArtifacts(t,n))}async getEntityMetadata(t){let n=await this.readCachedEntityMetadata(t);if(!n)throw new le.ArtifactNotFoundError("entityMetadata",t);return n}async getFieldMetadata(t,n){let i=(await this.getEntityMetadata(t)).attributes.find(o=>o.logicalName===n);if(!i)throw new le.PathNotFoundError("entityMetadata",t,n);return i}async updateElement(t,n,r,i){let o=this.observedGenerations.get(this.artifactKey(t,n));return this.withArtifactLock(t,n,async()=>{let a=await this.readForMutation(t,n,r,o),s=co.JsonPointer.resolve(a,r);if(s===void 0)throw new le.PathNotFoundError(t,n,r);let u=_s(s)&&_s(i)?{...s,...i}:i;return co.JsonPointer.set(a,r,(0,Go.cloneJson)(u)),this.assertStructurallyValid(t,n,a,r),await this.workspace.writeArtifact(t,n,a),this.getArtifactUnlocked(t,n)})}async addElement(t,n,r,i,o){let a=this.observedGenerations.get(this.artifactKey(t,n));return this.withArtifactLock(t,n,async()=>{let s=await this.readForMutation(t,n,r,a),u=co.JsonPointer.resolve(s,r);if(u===void 0)throw new le.PathNotFoundError(t,n,r);if(!Array.isArray(u)){if(!_s(u)||!_s(i))throw new le.ValidationError(t,n,r,"parent must be an array, or an object with an object of properties to add");if(o?.position!==void 0)throw new le.ValidationError(t,n,r,"position is not supported for an object parent");let d={};for(let f of Object.keys(i)){if(f==="id")throw new le.ValidationError(t,n,r,"refusing to write 'id' \u2014 that re-keys the node rather than adding a property");let p=(0,Go.cloneJson)(i[f]),m=(0,Jb.isValueMapKey)(f)||(0,Jb.pointerTouchesValueMap)(r);d[f]=m?p:Array.isArray(p)?p.map(h=>_s(h)?this.assignMissingIds(t,h):h):_s(p)?this.assignMissingIds(t,p):p}for(let f of Object.keys(d))co.JsonPointer.set(s,co.JsonPointer.append(r,f),d[f]);return this.assertStructurallyValid(t,n,s,r),await this.workspace.writeArtifact(t,n,s),this.getArtifactUnlocked(t,n)}let l=(0,Jb.pointerTouchesValueMap)(r)?(0,Go.cloneJson)(i):this.assignMissingIds(t,(0,Go.cloneJson)(i)),c=U_e(u,o?.position);return u.splice(c,0,l),this.assertStructurallyValid(t,n,s,r),await this.workspace.writeArtifact(t,n,s),this.getArtifactUnlocked(t,n)})}async moveElement(t,n,r,i,o){let a=this.observedGenerations.get(this.artifactKey(t,n));return this.withArtifactLock(t,n,async()=>{var s;let u=await this.readForMutation(t,n,r,a),l=co.JsonPointer.resolve(u,r);if(l===void 0)throw new le.PathNotFoundError(t,n,r);let c=co.JsonPointer.resolve(u,i);if(c===void 0)throw new le.PathNotFoundError(t,n,i);if(!Array.isArray(c))throw new le.ValidationError(t,n,i,"move target must be an array");if(i===r||i.startsWith(`${r}/`))throw new le.ValidationError(t,n,i,"cannot move an element into its own subtree");co.JsonPointer.remove(u,r);let d=(s=o?.index)!==null&&s!==void 0?s:c.length;c.splice(Math.max(0,Math.min(d,c.length)),0,l),j8(c);let f=co.JsonPointer.resolve(u,G8(r));return Array.isArray(f)&&f!==c&&j8(f),this.assertStructurallyValid(t,n,u,i),await this.workspace.writeArtifact(t,n,u),this.getArtifactUnlocked(t,n)})}async removeElement(t,n,r){let i=this.observedGenerations.get(this.artifactKey(t,n));return this.withArtifactLock(t,n,async()=>{let o=await this.readForMutation(t,n,r,i);if(co.JsonPointer.resolve(o,r)===void 0)throw new le.PathNotFoundError(t,n,r);return co.JsonPointer.remove(o,r),this.assertStructurallyValid(t,n,o,G8(r)),await this.workspace.writeArtifact(t,n,o),this.getArtifactUnlocked(t,n)})}assertStructurallyValid(t,n,r,i){var o,a,s;let u=this.registrations.get(t),l=(s=(a=u==null?void 0:(o=u.adapter).validate)===null||a===void 0?void 0:a.call(o,r,i))!==null&&s!==void 0?s:[];if(l.length>0)throw new le.ValidationError(t,n,l)}retrieveSetting(t,n){return(0,yf.retrieveSetting)(this.dataverse,t,n)}saveSettingValue(t,n,r){return(0,yf.saveSettingValue)(this.dataverse,t,n,r)}getAiReadiness(t){return(0,yf.getAiReadiness)(this.dataverse,t)}setAppAiFeatures(t,n,r){return(0,yf.setAppAiFeatures)(this.dataverse,t,n,r)}configureRowSummary(t,n){return(0,yf.configureRowSummary)(this.dataverse,t,n)}removeRowSummary(t){return(0,yf.removeRowSummary)(this.dataverse,t)}async enrichDefaultViews(t,n,r={}){let i=await(0,S_e.findDefaultViews)(this.dataverse,t,{excludeViewIds:r.excludeViewIds}),o=r.publish===!1,a=[],s=[],u=()=>({updated:[...a],results:[...s],pendingPublish:a.length>0?[{scope:(0,R8.boundEntityPublishScope)({entityLogicalName:t}),artifacts:a.map(c=>({type:"view",id:c}))}]:[]}),l;try{for(let c of i){await this.fetchArtifact("view",c.id),await this.updateElement("view",c.id,"/columns",n),l=c.id;let d=await this.pushArtifact("view",c.id);l=void 0,s.push(d),d.saved&&a.push(c.id)}}catch(c){throw l&&__e(c)&&a.push(l),o?(0,le.withPartialEnrichment)(c,u()):c}if(o)return u();if(a.length){let c=await this.publishArtifact("view",a[0]);if(c.publish.kind==="failed")throw new le.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,n){let r=this.requireRegistration(t,"createArtifact"),i=r.adapter.assignMissingIds(r.adapter.createDefault(n)),o=i.id;if(!o)throw new le.ValidationError(t,"(new)","/id","created artifact must have an id");return this.withArtifactLock(t,o,async()=>(await this.workspace.writeArtifact(t,o,i),(0,Go.cloneJson)(i)))}async deleteArtifact(t,n){return this.withArtifactLock(t,n,async()=>{await this.workspace.deleteArtifact(t,n)})}async deleteRemoteArtifact(t,n){return this.withArtifactLock(t,n,async()=>{var r;let i=this.requireRegistration(t,"deleteRemoteArtifact");if(await this.workspace.ensureReady(),i.guardedDelete){let o=await this.versions.getMeta(t,n);await i.api.delete(this.dataverse,n,{token:(r=o?.etag)!==null&&r!==void 0?r:null,snapshot:o?.snapshot})}else await i.api.delete(this.dataverse,n);await this.workspace.readArtifact(t,n)&&await this.workspace.deleteArtifact(t,n)})}async publishArtifact(t,n,r){let{result:i,siblings:o}=await this.withArtifactLock(t,n,()=>this.publishArtifactUnlocked(t,n,r));for(let a of o)await this.withArtifactLock(a.type,a.id,()=>this.adoptBracket(a));return i}async publishArtifacts(t,n){var r,i;let o=new Map;for(let g of t){let y=this.artifactKey(g.type,g.id);o.has(y)||o.set(y,{type:g.type,id:g.id})}let a=[];for(let[g,y]of o)a.push(await this.withArtifactLock(y.type,y.id,()=>this.preparePublish(g,y.type,y.id)));let s=new Set(o.keys()),u=[],l=new Set;for(let g of a){let y=((r=g.scope)===null||r===void 0?void 0:r.envelope)==="entity"?(i=g.scope.entityLogicalName)===null||i===void 0?void 0:i.toLowerCase():void 0;g.scope&&y&&!l.has(y)&&(l.add(y),u.push(g.scope))}let c=await this.captureSiblings(u,s),d=R_e(a),f=a.filter(g=>{var y;return(y=g.reg)===null||y===void 0?void 0:y.assertCombinablePublish}).sort((g,y)=>g.key<y.key?-1:g.key>y.key?1:0),p=async()=>{var g,y;for(let b of f)(y=(g=b.reg)===null||g===void 0?void 0:g.assertCombinablePublish)===null||y===void 0||y.call(g,this.dataverse,b.id);if(d)try{await(0,R8.publishXml)(this.dataverse,d);return}catch(b){return $u(b)}},m=await f.reduceRight((g,y)=>()=>this.withArtifactLock(y.type,y.id,g),p)(),h=new Map;for(let g of a)h.set(g.key,await this.withArtifactLock(g.type,g.id,()=>this.settlePublish(g,m,n)));for(let g of c)await this.withArtifactLock(g.type,g.id,()=>this.adoptBracket(g));return t.map(g=>({...h.get(this.artifactKey(g.type,g.id))}))}async preparePublish(t,n,r){var i,o;let a=await this.readRaw(n,r),s=this.registrations.get(n);if(!s?.publish)return{key:t,type:n,id:r,artifact:a,notApplicable:!0};let u=(i=s.publishScope)===null||i===void 0?void 0:i.call(s,r,a);if(!u||!P_e.has(u.envelope))throw new le.InvalidArgumentError(`publishArtifacts: ${n} '${r}' publishes through ${u?`a '${u.envelope}'`:"no declared"} scope, which one PublishXml envelope cannot carry. Publish it with publishArtifact.`);(o=s.assertCombinablePublish)===null||o===void 0||o.call(s,this.dataverse,r);let l=s.rebaselineAfterPublish==="bracket"?await this.captureBracket(s,n,r):void 0;return{key:t,type:n,id:r,artifact:a,reg:s,scope:u,...l?{own:l}:{}}}async settlePublish(t,n,r){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),n)return{type:i,id:o,shipped:!1,publish:{kind:"failed",error:n},...a};if(!r?.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,fo.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 u=await this.verifyPublished(i,o,t.artifact);return{type:i,id:o,shipped:u.kind==="verified",publish:u,...a}}async publishArtifactUnlocked(t,n,r){var i;let o=await this.readRaw(t,n),a=this.registrations.get(t);if(!a?.publish)return{result:{type:t,id:n,shipped:!1,publish:{kind:"notApplicable"}},siblings:[]};let s=(i=a.publishScope)===null||i===void 0?void 0:i.call(a,n,o),u=a.rebaselineAfterPublish==="bracket"?await this.captureBracket(a,t,n):void 0,l=s?await this.captureSiblings([s],new Set([this.artifactKey(t,n)])):[];try{await a.publish(this.dataverse,n,o)}catch(d){return{result:{type:t,id:n,shipped:!1,publish:{kind:"failed",error:$u(d)},...s?{publishScope:s}:{}},siblings:[]}}if(a.rebaselineAfterPublish==="snapshot"&&await this.rebaselineAfterPublish(a,t,n),u&&await this.adoptBracket(u),!r?.verify)return{result:{type:t,id:n,shipped:!1,publish:{kind:"submitted"},...s?{publishScope:s}:{}},siblings:l};let c=await this.verifyPublished(t,n,o);return{result:{type:t,id:n,shipped:c.kind==="verified",publish:c,...s?{publishScope:s}:{}},siblings:l}}async captureBracket(t,n,r){try{let i=await this.versions.getMeta(n,r),o=i?.etag;if(!(0,Dr.isVersionToken)(o)||!t.api.readContentThenToken)return;let{raw:a,etag:s,siblingEtags:u}=await t.api.readContentThenToken(this.dataverse,r),l=i?.siblingEtags;return s!==o||!x_e(l,u)?void 0:{type:n,id:r,reg:t,heldEtag:o,...l?{heldSiblings:l}:{},content:this.bracketContent(t,a)}}catch{return}}async captureSiblings(t,n){var r,i,o;let a=new Map;for(let l of t){let c=l.envelope==="entity"?(r=l.entityLogicalName)===null||r===void 0?void 0:r.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 l of s){let c=this.registrations.get(l.type);if(!(n.has(this.artifactKey(l.type,l.id))||c?.rebaselineAfterPublish!=="bracket"||!c.publishScope))try{let d=await this.workspace.readArtifact(l.type,l.id),f=d?c.publishScope(l.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(l))}catch{continue}}let u=[];for(let l of a.values())for(let c of l){let d=this.registrations.get(c.type),f=d?await this.captureBracket(d,c.type,c.id):void 0;f&&u.push(f)}return u}async adoptBracket(t){var n;try{let r=await this.versions.getMeta(t.type,t.id);if(!r||r.etag!==t.heldEtag||!(0,fo.deepEqual)((n=r.siblingEtags)!==null&&n!==void 0?n:void 0,t.heldSiblings))return;let{raw:i,etag:o,siblingEtags:a}=await t.reg.api.get(this.dataverse,t.id);if(!(0,Dr.isVersionToken)(o)||!H8(a,t.heldSiblings)||!K8(a)||!(o!==t.heldEtag||!(0,fo.deepEqual)(a??void 0,t.heldSiblings))||!(0,fo.deepEqual)(this.bracketContent(t.reg,i),t.content))return;await this.versions.storeMeta(t.type,t.id,{...r,etag:o,...t.heldSiblings?{siblingEtags:{...a}}:{},fetchedAt:(0,Dr.nowIso)()},r)}catch{}}bracketContent(t,n){var r,i,o;let a=t.adapter.fromApiResponse(n);return(o=(i=(r=t.adapter).baselineContent)===null||i===void 0?void 0:i.call(r,a))!==null&&o!==void 0?o:a}adoptReadBack(t,n){try{return{artifact:t.adapter.fromApiResponse(n)}}catch(r){return{warning:`The write was saved, but the record read back after it could not be read into the local copy (${$u(r).message}). The SDK holds no version for it now, so the next push is refused: re-fetch before editing again.`}}}adoptedAsSent(t,n,r,i){try{let o={...r,...i},a=t.adapter.fromApiResponse(t.adapter.completeAsStored?t.adapter.completeAsStored(o,r):o);return(0,fo.deepEqual)(n,a)}catch{return!1}}async rebaselineAfterPublish(t,n,r){try{let i=await this.versions.getMeta(n,r);if(!i)return;let{raw:o,etag:a,memberEtags:s,siblingEtags:u}=t.api.getForRebaseline?await t.api.getForRebaseline(this.dataverse,r):await t.api.get(this.dataverse,r),l=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,fo.deepEqual)(c(i.snapshot),c(l)))return;await this.versions.storeMeta(n,r,{...i,etag:a,fetchedAt:(0,Dr.nowIso)(),...s?{memberEtags:s}:{},...u?{siblingEtags:u}:{}},i)}catch{}}async verifyPublished(t,n,r){var i;if(t!=="app"){let o=this.registrations.get(t);return o?.api.getPublished?this.verifyPublishedContent(o,t,n,r):{kind:"unverifiable",reason:`published-projection verification is not characterised for '${t}'; the publish was submitted`}}try{let o=`/appmodules(${(0,Yl.normalizeGuid)(n,"id")})${(0,Yl.odataQuery)([["$select","appmoduleid,name,description"]])}`,a=await this.dataverse.get(o);if(a.status>=200&&a.status<300){let s=(i=a.body)!==null&&i!==void 0?i:{},u=r;if(!u)return{kind:"unverifiable",reason:"there is no local copy of the app to compare the published projection with"};let l=["name","description"].filter(d=>u[d]!==void 0);if(l.length===0)return{kind:"unverifiable",reason:"the local copy of the app holds neither a name nor a description to compare the published projection with, and its presence alone proves nothing for a re-publish"};let c=l.filter(d=>{var f,p;return((f=u[d])!==null&&f!==void 0?f:"")!==((p=s[d])!==null&&p!==void 0?p:"")});return c.length>0?{kind:"unverifiable",reason:`the published projection does not yet match the saved app (${c.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 ${a.status}`}}catch(o){return{kind:"unverifiable",reason:$u(o).message}}}async verifyPublishedContent(t,n,r,i){var o,a,s;try{let u=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},l=u(i),c=(o=await this.versions.getMeta(n,r))===null||o===void 0?void 0:o.snapshot;if(c===void 0||!(0,fo.deepEqual)(l,u(c)))return{kind:"unverifiable",reason:`the local ${n} 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,r));return d?(0,fo.deepEqual)(l,u(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 ${n} is not in the published projection yet. PublishXml is asynchronous \u2014 re-read shortly, or re-publish if it persists`}}catch(u){return{kind:"unverifiable",reason:$u(u).message}}}async pushArtifact(t,n){return this.withArtifactLock(t,n,()=>this.pushArtifactUnlocked(t,n))}async prepareArtifactUnlocked(t,n,r,i={client:this.dataverse,persistNormalized:!0}){var o,a;let s=this.requireRegistration(t,"pushArtifact"),u=await this.workspace.readArtifactWithText(t,n);if(!u)throw new le.ArtifactNotFoundError(t,n);let l=u.artifact,c=u.text,d=await this.versions.getMeta(t,n),f=(a=(o=s.adapter).normalize)===null||a===void 0?void 0:a.call(o,l,d?.snapshot);f&&f!==l&&(i.persistNormalized&&await this.workspace.writeArtifact(t,n,f),l=f,c=void 0),this.assertLanguageMatches(t,n,d,s),this.assertProjectionMatches(t,n,d);let p=await this.buildMetadataContext(s.adapter,l,d?.snapshot,i.client),m=await s.adapter.toApiPayload(l,d?.snapshot,p);return await this.assertSemanticallyComplete(s,t,n,l,d===null,d?.everActivated,r,i.client),{type:t,id:n,reg:s,json:l,...c!==void 0?{storedText:c}:{},meta:d,payload:m}}async assertSemanticallyComplete(t,n,r,i,o,a,s,u=this.dataverse){let l=t.adapter.issuesBlockingPush;if(!l)return;let c=i.entityLogicalName,f=(c?await this.columnsForCheck(t,c,i,s,u):[]).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(h=>({value:h.value,label:h.label}))}:{},...m.targets?{targets:m.targets}:{}})),p=l.call(t.adapter,i,f,{isCreate:o,everActivated:a});if(p.length>0)throw new le.ValidationError(n,r,p)}columnsForCheck(t,n,r,i,o=this.dataverse){var a,s,u;let l=(u=(s=(a=t.adapter).columnsCheckedAtPush)===null||s===void 0?void 0:s.call(a,r))!==null&&u!==void 0?u:[],c=async()=>{let p=await this.readCachedEntityMetadata(n);if(p)return p.attributes;try{return await(0,hf.readCheckColumns)(o,n,l)}catch{return[]}};if(!i)return c();let d=[n,...[...new Set(l)].sort()].join("\0"),f=i.get(d);return f||(f=c(),i.set(d,f)),f}async pushArtifactUnlocked(t,n,r){return this.executePrepared(await this.prepareArtifactUnlocked(t,n,r))}async executePrepared(t){var n,r,i,o,a,s,u,l,c,d,f;let{type:p,id:m,reg:h,json:g,meta:y,payload:b}=t,E=!1;try{let w;if(y)w=await h.api.update(this.dataverse,m,b,y.etag,y.memberEtags,y.siblingEtags);else{let S=await this.createWithMintedId(h,p,m,b,g);if("adopted"in S)return await this.persistAdoption(p,m,g,S.adopted);w=S.written}E=!0;let _=m;y||(w.serverIdentity&&h.adapter.applyServerIdentity&&h.adapter.applyServerIdentity(g,w.serverIdentity),w.id&&w.id!==m&&(g.id=w.id,await this.workspace.deleteArtifact(p,m),_=w.id));let I=y&&w.readBack!==void 0?this.adoptReadBack(h,w.readBack):void 0,T=I?.artifact?{artifact:I.artifact,baseline:I.artifact}:h.adapter.committed?h.adapter.committed(g,b,{intentPending:w.intentPending===!0,...w.serverState!==void 0?{serverState:w.serverState}:{}}):{artifact:g,baseline:g};await this.workspace.writeArtifact(p,_,T.artifact,y&&_===m?t.storedText:void 0);let O=I?.artifact!==void 0&&!(0,fo.deepEqual)(I.artifact,g),v=O?this.nextRefreshGeneration(p,_,y):(n=y?.refreshGeneration)!==null&&n!==void 0?n:0,N=[...(r=w.warnings)!==null&&r!==void 0?r:[],...I?.warning?[I.warning]:[],...I?.artifact!==void 0&&!this.adoptedAsSent(h,I.artifact,w.readBack,b)?[`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 ${p} 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(p,_,{etag:I&&!I.artifact?null:w.etag,...v>0?{refreshGeneration:v,observedGeneration:(i=y?.observedGeneration)!==null&&i!==void 0?i:0}:{},languageCode:this.languageCode,projectionVersion:mf.PROJECTION_VERSION,fetchedAt:(0,Dr.nowIso)(),snapshot:(0,Go.cloneJson)(T.baseline),...w.memberEtags?{memberEtags:w.memberEtags}:{},...w.siblingEtags?{siblingEtags:w.siblingEtags}:{}},_===m?y:void 0),{type:p,id:_,saved:!0,shipped:((o=w.publish)===null||o===void 0?void 0:o.kind)==="verified",publish:(a=w.publish)!==null&&a!==void 0?a:{kind:"notRequested"},...w.publish&&w.publish.kind!=="notRequested"?(()=>{var S;let R=(S=h.publishScope)===null||S===void 0?void 0:S.call(h,_,g);return R?{publishScope:R}:{}})():{},...O?{refreshed:!0}:{},...N.length>0?{warnings:N}:{},...w.appMainForms?{appMainForms:w.appMainForms}:{}}}catch(w){let _=(0,le.readPartialTokens)(w);if(_&&y){let I={...(s=y.memberEtags)!==null&&s!==void 0?s:{},...(u=_.memberEtags)!==null&&u!==void 0?u:{}},T={...(l=y.siblingEtags)!==null&&l!==void 0?l:{},...(c=_.siblingEtags)!==null&&c!==void 0?c:{}},O=h.adapter.partiallyCommitted&&y.snapshot!==void 0?h.adapter.partiallyCommitted(y.snapshot,b,Object.keys((d=_.memberEtags)!==null&&d!==void 0?d:{})):void 0;await this.versions.storeMeta(p,m,{...y,...O!==void 0&&O!==y.snapshot?{snapshot:(0,Go.cloneJson)(O)}:{},...Object.keys(I).length>0?{memberEtags:I}:{},...Object.keys(T).length>0?{siblingEtags:T}:{}},y)}if(w instanceof le.SdkError&&w.code===Pr.ALREADY_EXISTS_CODE)return{type:p,id:m,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:w};if(w instanceof le.SdkError&&w.code===P8.WFOM_API_UNAVAILABLE_CODE)return{type:p,id:m,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:w};if(w instanceof le.SdkError&&w.code===P8.BUSINESS_RULE_LEFT_DEACTIVATED_CODE)return{type:p,id:m,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:w};if(w instanceof le.SdkError&&w.code===Dr.VERSION_CONFLICT_CODE)return{type:p,id:m,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:(0,U8.isFailureAfterPrimaryWrite)(w)?w:new le.VersionConflictError(p,m,(f=y?.etag)!==null&&f!==void 0?f:null,null,w.message)};throw E?N_e(w):w}}assertLanguageMatches(t,n,r,i){if(i?.languageSensitive&&!(r?.languageCode===void 0||r.languageCode===this.languageCode))throw new le.SdkError("ARTIFACT_LANGUAGE_MISMATCH",`Refusing to push ${t} '${n}': it was fetched with languageCode ${r.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 ${r.languageCode}.`)}assertProjectionMatches(t,n,r){var i;if(r&&r.projectionVersion!==mf.PROJECTION_VERSION)throw new le.SdkError("ARTIFACT_PROJECTION_STALE",`Refusing to push ${t} '${n}': its workspace copy was produced by projection version ${(i=r.projectionVersion)!==null&&i!==void 0?i:"unknown (pre-versioning)"}, but this SDK produces version ${mf.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}', '${n}') and re-apply any local edits. A copy WITH local edits keeps them, and this version, through that fetch: read the edits first (getArtifact or diffArtifact), re-fetch with fetchArtifact('${t}', '${n}', { overwrite: true }) \u2014 which discards them \u2014 and re-apply them.`)}async createWithMintedId(t,n,r,i,o){try{return{written:await t.api.create(this.dataverse,i,r)}}catch(a){let s=n==="form"?(0,rT.readPrimaryCreateRefusal)(a):void 0;if(s?.status===404&&await(0,iT.formExistsAtId)(()=>t.api.get(this.dataverse,r),s.sent.formid)){let l=`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,le.attachCause)(new le.SdkError(Pr.ALREADY_EXISTS_CODE,Yb(n,r,l)+(this.createRecovery==="adoptExact"?` ${uT($_e)}`:"")),a)}if(!(a instanceof le.SdkError)||a.code!==Dr.VERSION_CONFLICT_CODE||(0,U8.isFailureAfterPrimaryWrite)(a))throw a;if(this.createRecovery==="adoptExact"&&s?.status===412){let u=await(0,iT.recoverFormCreate)({client:this.dataverse,read:()=>t.api.get(this.dataverse,r),sent:s.sent,authoredFormType:o.formType,project:l=>t.adapter.fromApiResponse(l)});if("adopted"in u)return{adopted:u.adopted};throw new le.SdkError(Pr.ALREADY_EXISTS_CODE,`${Yb(n,r)} ${uT(u.refused)}`)}throw new le.SdkError(Pr.ALREADY_EXISTS_CODE,Yb(n,r))}}async persistAdoption(t,n,r,i){let{artifact:o,etag:a}=i,s=!(0,fo.deepEqual)(o,r);return await this.versions.storeMeta(t,n,{etag:a,...s?{refreshGeneration:this.nextRefreshGeneration(t,n,null),observedGeneration:0}:{},languageCode:this.languageCode,projectionVersion:mf.PROJECTION_VERSION,fetchedAt:(0,Dr.nowIso)(),snapshot:(0,Go.cloneJson)(o)},null),s&&await this.workspace.writeArtifact(t,n,o),{type:t,id:n,saved:!1,adoptedExisting:!0,shipped:!1,publish:{kind:"notRequested"},...s?{refreshed:!0}:{}}}async buildMetadataContext(t,n,r,i=this.dataverse){var o,a,s,u;let l=(a=(o=t.metadataNeeds)===null||o===void 0?void 0:o.call(t,n,r))!==null&&a!==void 0?a:[],c=new Set(l.map(T=>T.entityLogicalName).filter(T=>!!T)),d=new Set(l.filter(T=>T.needsColumnDetail).map(T=>T.entityLogicalName)),f=new Set(l.filter(T=>T.needsColumnDetail||!T.fieldName).map(T=>T.entityLogicalName)),p=T=>l.filter(O=>O.entityLogicalName===T).every(O=>O.fetchRequired===!1),m=new Map,h=new Map;for(let T of c){let O=await this.readCachedEntityMetadata(T);if(O&&d.has(T)&&(O.columnDetailComplete!==!0||!(typeof O.columnDetailVersion=="number"&&O.columnDetailVersion>=hf.COLUMN_DETAIL_VERSION)||O.attributes.some(v=>typeof v.attributeTypeName!="string"))&&(O=null),!O&&!f.has(T)){if(!p(T)){let v=l.filter(N=>N.entityLogicalName===T).map(N=>N.fieldName);try{let N=await(0,hf.readColumnHints)(i,T,v);h.set(T,new Map(N.map(S=>[S.logicalName,S])))}catch{}}continue}if(!O&&!p(T))try{await this.loadMissedEntityMetadata(T,i),O=await this.readCachedEntityMetadata(T)}catch{}O&&m.set(T,O)}let g=(T,O)=>{var v,N,S;return(N=(v=m.get(T))===null||v===void 0?void 0:v.attributes.find(R=>R.logicalName===O))!==null&&N!==void 0?N:(S=h.get(T))===null||S===void 0?void 0:S.get(O)},y=this.languageCode,E=l.some(T=>{if(!T.needsLabel||!T.fieldName)return!1;let O=g(T.entityLogicalName,T.fieldName);return O?.localizedDisplayName!==void 0&&!O.localizedDisplayName[y]})?await this.readBaseLanguage(i):void 0,w=!((s=t.needsBaseLanguage)===null||s===void 0)&&s.call(t,n)?await this.readBaseLanguage(i):void 0,_=(u=t.customControlNeeds)===null||u===void 0?void 0:u.call(t,n,r),I=_&&(_.controls.length>0||_.columns.length>0)?await this.readPcfNeeds(_,i):void 0;return{resolveField:(T,O)=>{let v=g(T,O);return v?{displayName:F_e(v,y,E),attributeType:v.attributeType}:void 0},resolveEntity:T=>m.get(T),loadTypeScript:()=>this.compiler.load(),genPageIteration:this.genPageIteration,...w!==void 0?{baseLanguageCode:w}:{},...I?{pcf:I}:{}}}async readPcfNeeds(t,n=this.dataverse){let r=new Map;for(let o of t.controls)r.set(o,await(0,M8.readControlManifest)(n,o));let i=new Map;for(let o of t.columns)i.set(o,await(0,M8.readPcfColumn)(n,t.entityLogicalName,o,t.requireCreateEligibility?{requireCreateEligibility:!0}:void 0));return{control:o=>r.get(o),column:(o,a)=>o===t.entityLogicalName?i.get(a):void 0}}readBaseLanguage(t=this.dataverse){if(!this.baseLanguage){let n=(async()=>{var r,i,o;try{let a=await t.get("/organizations?$select=languagecode");if(a.status<200||a.status>=300)return;let s=Number((o=(i=(r=a.body)===null||r===void 0?void 0:r.value)===null||i===void 0?void 0:i[0])===null||o===void 0?void 0:o.languagecode);return Number.isInteger(s)&&s>0?s:void 0}catch{return}})();this.baseLanguage=n,n.then(r=>{r===void 0&&this.baseLanguage===n&&(this.baseLanguage=void 0)})}return this.baseLanguage}async pushAll(){let t=await this.getDirtyArtifacts();await this.warmBatchMetadata(t);let n=new Map,r=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,n))}catch(s){r.set(o,{type:a.type,id:a.id,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:$u(s)})}}if(r.size>0)return t.map((o,a)=>{var s;return(s=r.get(a))!==null&&s!==void 0?s:{type:o.type,id:o.id,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:new le.SdkError(Pr.PUSH_NOT_ATTEMPTED_CODE,`Not attempted: ${r.size} artifact(s) in this batch could not be prepared, so no writes were issued. Fix the reported failures and push again.`)}});let i=[];for(let o of t)try{i.push(await this.withArtifactLock(o.type,o.id,()=>this.pushArtifactUnlocked(o.type,o.id,n)))}catch(a){i.push({type:o.type,id:o.id,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:$u(a)})}return i}async warmBatchMetadata(t,n=this.dataverse){var r,i,o;let a=new Set;for(let s of t){let u=this.registrations.get(s.type);if(!u)continue;let l;try{l=await this.readLocal(s.type,s.id)}catch{continue}let c=l.entityLogicalName;c&&a.add(c);for(let d of(o=(i=(r=u.adapter).metadataNeeds)===null||i===void 0?void 0:i.call(r,l))!==null&&o!==void 0?o:[])d.entityLogicalName&&a.add(d.entityLogicalName)}for(let s of a)if(!await this.readCachedEntityMetadata(s))try{await this.loadMissedEntityMetadata(s,n)}catch{}}async getDirtyArtifacts(){return(await this.withDirtyFlags(await this.workspace.listArtifacts())).filter(n=>n.isDirty)}async diffArtifact(t,n){return this.versions.diff(t,n)}async previewPush(t,n,r){let{client:i,guard:o}=this.dataverse.readOnly(),a=this.targetSolutionReader(i);return this.withArtifactLock(t,n,()=>this.latched(o,async()=>(await this.previewUnlocked(t,n,i,o,a,r)).preview))}async previewPushAll(t){let{client:n,guard:r}=this.dataverse.readOnly();return this.latched(r,async()=>{let i=await this.getDirtyArtifacts(),o=r.gets;await this.warmBatchMetadata(i,n);let a=this.targetSolutionReader(n);await a();let s=r.gets-o,u=new Map,l=[];for(let d of i)l.push(await this.withArtifactLock(d.type,d.id,()=>this.previewUnlocked(d.type,d.id,n,r,a,t,u)));(0,nT.judgeBatchDependencies)(l.map(d=>d.preview));let c=l.filter(d=>!d.prepared).length;if(c>0)for(let d of l.filter(f=>f.prepared))d.preview.refusals.push({code:Pr.PUSH_NOT_ATTEMPTED_CODE,message:`Not attempted: ${c} artifact(s) in this batch could not be prepared, so pushAll would issue no writes. Fix the reported failures first.`}),d.preview.outcome="refused";return{wouldAttempt:i.length>0&&c===0,previews:l.map(d=>d.preview),sharedRequests:s}})}async latched(t,n){let r=()=>{if(t.refusedWrites.length>0)throw new le.SdkError("PREVIEW_WRITE_REFUSED",`A pre-push check attempted ${t.refusedWrites.length} write(s) (${t.refusedWrites[0]}); it may only read. Nothing was written. This is a defect in the SDK.`)},i;try{i=await n()}catch(o){throw r(),o}return r(),i}targetSolutionReader(t){let n=this.dataverse.solutionName,r;return()=>n?(r||(r=(0,nT.readTargetSolution)(t,n)),r):Promise.resolve(void 0)}async previewUnlocked(t,n,r,i,o,a,s){let u=this.requireRegistration(t,"previewPush"),l=await this.workspace.readArtifact(t,n);if(!l)throw new le.ArtifactNotFoundError(t,n);let c=await this.versions.getMeta(t,n),d=(await this.versions.diff(t,n)).changes,f=!1;return{preview:await(0,nT.previewArtifact)({type:t,id:n,reg:u,client:r,guard:i,options:a,meta:c,json:l,localChanges:d,prepare:async()=>{let m=await this.prepareArtifactUnlocked(t,n,s,{client:r,persistNormalized:!1});return f=!0,{payload:m.payload,json:m.json}},solution:o,alreadyExists:m=>Yb(t,n)+(m!==void 0?` ${uT(m)}`:""),...t==="form"&&this.createRecovery==="adoptExact"?{judgeAdoption:async(m,h)=>{let g=await(0,iT.recoverFormCreate)({client:r,read:()=>u.api.get(r,n),sent:Object.freeze({...(0,Dr.withClientMintedId)(m,"formid",n)}),authoredFormType:h.formType,project:y=>u.adapter.fromApiResponse(y)});return"adopted"in g?{eligible:!0}:{refused:g.refused}}}:{}}),prepared:f}}planDataFix(t){return(0,B8.planDataFix)(this.dataverse,t)}applyDataFix(t,n){return(0,B8.applyDataFix)(this.dataverse,t,n)}planPromotion(t,n){return t instanceof e?(0,L8.planPromotion)(this.promotionContext(),t.dataverse,n):Promise.reject((0,p_e.promotionError)("INVALID_ARGUMENT","preflight",{reason:"source must be an SDK created by createMakerSdk"}))}promote(t,n,r){return this.schemaWrite(void 0,()=>(0,f_e.promote)(this.promotionContext(),t,n,r))}promotionContext(){let{instanceUrl:t,clients:n}=this.promotionConnectivity;return{client:this.dataverse,issuedPlans:this.promotionIssued,listConnections:(r,i)=>{let o=()=>Promise.reject(new le.SdkError("PREVIEW_WRITE_REFUSED","A promotion plan attempted a write; it may only read.")),a=s=>s&&{get:(u,l)=>(i.spendGet(),s.get(u,l)),post:o,patch:o,delete:o};return new $8.ConnectivityRouter(r,t,{powerAppsServiceClient:a(n.powerAppsServiceClient),powerPlatformApiClient:a(n.powerPlatformApiClient)}).listConnections()}}}assignMissingIds(t,n){let r=this.registrations.get(t);return r?r.adapter.assignMissingIds(n):(0,Jb.assignMissingIds)(n)}async resolveComponentType(t){if(t.genPage)return"genPage";if(t.connectionReference)return"connectionReference";if(t.customApi==="api")return"customApi";switch(t.componentType){case Mn.SolutionComponentType.SavedQuery:return"view";case Mn.SolutionComponentType.SavedQueryVisualization:return"chart";case Mn.SolutionComponentType.AppModule:return"app";case Mn.SolutionComponentType.EnvironmentVariableDefinition:return"environmentVariable";case Mn.SolutionComponentType.FieldSecurityProfile:return"fieldSecurityProfile";case Mn.SolutionComponentType.DuplicateRule:return"duplicateRule";case Mn.SolutionComponentType.Workflow:return this.workflowArtifactType(t);case Mn.SolutionComponentType.SystemForm:return this.systemFormArtifactType(t.objectId);default:return}}async systemFormArtifactType(t){let n=await(0,Hb.readSystemFormType)(this.dataverse,t);if(Number.isNaN(n))throw new le.SdkError(aT,`System form '${t}' answered without a readable type, so whether it is a form or a dashboard cannot be told.`);return(0,Hb.systemFormKindOf)(n)}async workflowArtifactType(t){let n=(0,Yl.normalizeGuid)(t.objectId,"workflowId"),r=`/workflows(${n})${(0,Yl.odataQuery)([["$select","category,businessprocesstype"]])}`,o=(0,Dr.ensureSuccess)(await this.dataverse.get(r),this.dataverse.apiUrl(r)).body,a=(0,Hb.decodeCode)(o?.category);if(Number.isNaN(a))throw new le.SdkError(aT,`Workflow '${n}' answered without a readable category, so its kind cannot be told.`);if(t.workflowCategory=a,a===T_e)return"businessRule";if(a===O_e){let s=(0,Hb.decodeCode)(o?.businessprocesstype);if(Number.isNaN(s))throw new le.SdkError(aT,`Workflow '${n}' (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,n){let r=this.registrations.get(t);if(!r)throw new le.NotImplementedError(n,`no adapter registered for artifact type '${t}'`);return r}getSearchSettings(t){return(0,m_e.getSearchSettings)(this.dataverse,t)}};Pr.MakerSdk=Qb;function M_e(e){return new Qb(e)}Pr.createMakerSdk=M_e;function $u(e){return e instanceof Error?e:new Error(String(e))}function H8(e,t){let n=Object.keys(e??{}),r=Object.keys(t??{});return n.length===r.length&&n.every(i=>Object.prototype.hasOwnProperty.call(t??{},i))}function K8(e){return Object.values(e??{}).every(Dr.isVersionToken)}function x_e(e,t){return H8(e,t)&&K8(e)&&Object.keys(e??{}).every(n=>t?.[n]===e?.[n])}function uT(e){return`createRecovery 'adoptExact' did not adopt it: ${e}.`}function Yb(e,t,n){return`Cannot create ${e} '${t}': a record already exists at that id${n?` (${n})`:""}, 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 F_e(e,t,n){let r=e.localizedDisplayName;return r?.[t]||(n===void 0?void 0:r?.[n])||e.displayName}function _s(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function G8(e){let t=e.lastIndexOf("/");return t<=0?"":e.slice(0,t)}function j8(e){e.length===0||!e.every(t=>_s(t)&&typeof t.order=="number")||e.forEach((t,n)=>{t.order=n})}function U_e(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 r=e.findIndex(i=>_s(i)&&i.id===t.before);return r<0?e.length:r}let n=e.findIndex(r=>_s(r)&&r.id===t.after);return n<0?e.length:n+1}});var Y8=C(Xb=>{"use strict";Object.defineProperty(Xb,"__esModule",{value:!0});Xb.ARTIFACT_TYPES=void 0;Xb.ARTIFACT_TYPES=["form","view","businessRule","app","command","chart","dashboard","genPage","bpf","environmentVariable","connectionReference","fieldSecurityProfile","customApi","duplicateRule"]});var X8=C(Q8=>{"use strict";Object.defineProperty(Q8,"__esModule",{value:!0})});var e5=C(Z8=>{"use strict";Object.defineProperty(Z8,"__esModule",{value:!0})});var n5=C(t5=>{"use strict";Object.defineProperty(t5,"__esModule",{value:!0})});var i5=C(r5=>{"use strict";Object.defineProperty(r5,"__esModule",{value:!0})});var a5=C(o5=>{"use strict";Object.defineProperty(o5,"__esModule",{value:!0})});var u5=C(s5=>{"use strict";Object.defineProperty(s5,"__esModule",{value:!0})});var c5=C(l5=>{"use strict";Object.defineProperty(l5,"__esModule",{value:!0})});var f5=C(d5=>{"use strict";Object.defineProperty(d5,"__esModule",{value:!0})});var m5=C(p5=>{"use strict";Object.defineProperty(p5,"__esModule",{value:!0})});var g5=C(h5=>{"use strict";Object.defineProperty(h5,"__esModule",{value:!0})});var b5=C(y5=>{"use strict";Object.defineProperty(y5,"__esModule",{value:!0})});var w5=C(v5=>{"use strict";Object.defineProperty(v5,"__esModule",{value:!0})});var A5=C(E5=>{"use strict";Object.defineProperty(E5,"__esModule",{value:!0})});var S5=C(C5=>{"use strict";Object.defineProperty(C5,"__esModule",{value:!0})});var _5=C(N5=>{"use strict";Object.defineProperty(N5,"__esModule",{value:!0})});var T5=C(I5=>{"use strict";Object.defineProperty(I5,"__esModule",{value:!0})});var D5=C(O5=>{"use strict";Object.defineProperty(O5,"__esModule",{value:!0})});var R5=C(P5=>{"use strict";Object.defineProperty(P5,"__esModule",{value:!0})});var $5=C(k5=>{"use strict";Object.defineProperty(k5,"__esModule",{value:!0})});var M5=C(L5=>{"use strict";Object.defineProperty(L5,"__esModule",{value:!0})});var F5=C(x5=>{"use strict";Object.defineProperty(x5,"__esModule",{value:!0})});var q5=C(U5=>{"use strict";Object.defineProperty(U5,"__esModule",{value:!0})});var V5=C(B5=>{"use strict";Object.defineProperty(B5,"__esModule",{value:!0})});var j5=C(G5=>{"use strict";Object.defineProperty(G5,"__esModule",{value:!0})});var z5=C(W5=>{"use strict";Object.defineProperty(W5,"__esModule",{value:!0})});var K5=C(H5=>{"use strict";Object.defineProperty(H5,"__esModule",{value:!0})});var Y5=C(J5=>{"use strict";Object.defineProperty(J5,"__esModule",{value:!0})});var X5=C(Q5=>{"use strict";Object.defineProperty(Q5,"__esModule",{value:!0})});var e6=C(Z5=>{"use strict";Object.defineProperty(Z5,"__esModule",{value:!0})});var n6=C(t6=>{"use strict";Object.defineProperty(t6,"__esModule",{value:!0})});var i6=C(r6=>{"use strict";Object.defineProperty(r6,"__esModule",{value:!0})});var a6=C(ge=>{"use strict";var q_e=ge&&ge.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),Be=ge&&ge.__exportStar||function(e,t){for(var n in e)n!=="default"&&!Object.prototype.hasOwnProperty.call(t,n)&&q_e(t,e,n)};Object.defineProperty(ge,"__esModule",{value:!0});ge.projectConnectorOperationSchema=ge.projectConnectorOperations=ge.PromotionError=ge.createMakerSdk=void 0;var B_e=J8();Object.defineProperty(ge,"createMakerSdk",{enumerable:!0,get:function(){return B_e.createMakerSdk}});Be(Y8(),ge);Be(X8(),ge);Be(e5(),ge);Be(n5(),ge);Be(i5(),ge);Be(a5(),ge);Be(u5(),ge);Be(c5(),ge);Be(f5(),ge);Be(m5(),ge);Be(g5(),ge);Be(b5(),ge);Be(w5(),ge);Be(A5(),ge);Be(S5(),ge);Be(h0(),ge);Be(_5(),ge);Be(T5(),ge);Be(D5(),ge);Be(R5(),ge);Be($5(),ge);Be(M5(),ge);Be(F5(),ge);Be(q5(),ge);Be(V5(),ge);Be(j5(),ge);Be(z5(),ge);Be(K5(),ge);Be(Y5(),ge);Be(X5(),ge);Be(e6(),ge);Be(eA(),ge);Be(n6(),ge);Be(i6(),ge);Be(Y(),ge);var V_e=Y();Object.defineProperty(ge,"PromotionError",{enumerable:!0,get:function(){return V_e.PromotionError}});var o6=Zf();Object.defineProperty(ge,"projectConnectorOperations",{enumerable:!0,get:function(){return o6.projectConnectorOperations}});Object.defineProperty(ge,"projectConnectorOperationSchema",{enumerable:!0,get:function(){return o6.projectConnectorOperationSchema}})});var cT=C(Ra=>{"use strict";var G_e=Ra&&Ra.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),j_e=Ra&&Ra.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),l6=Ra&&Ra.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var n in e)n!=="default"&&Object.prototype.hasOwnProperty.call(e,n)&&G_e(t,e,n);return j_e(t,e),t};Object.defineProperty(Ra,"__esModule",{value:!0});Ra.NodeFileSystemStorage=void 0;var xn=l6(require("fs")),Rr=l6(require("path")),s6=Y(),u6=Uv();async function c6(e){let t;try{t=await xn.promises.lstat(e)}catch{return}if(t.isSymbolicLink()){try{await xn.promises.unlink(e)}catch{await xn.promises.rmdir(e)}return}if(!t.isDirectory()){await xn.promises.unlink(e);return}for(let n of await xn.promises.readdir(e))await c6(Rr.join(e,n));await xn.promises.rmdir(e)}var lT=class{constructor(t){this.root=t}getRoot(){return this.root}pathFor(t,n=!0){return this.assertWithinRoot(Rr.join(this.root,...t),n)}realPathThroughNearestAncestor(t){let n=t,r=[];for(;!xn.existsSync(n);){r.unshift(Rr.basename(n));let i=Rr.dirname(n);if(i===n)return Rr.resolve(t);n=i}return Rr.resolve(xn.realpathSync(n),...r)}assertWithinRoot(t,n){let r=Rr.resolve(this.root),i=Rr.resolve(t);if(i!==r&&!i.startsWith(r+Rr.sep))throw new s6.PathTraversalError(t,this.root);let o=this.realPathThroughNearestAncestor(r),a=n?this.realPathThroughNearestAncestor(i):Rr.resolve(this.realPathThroughNearestAncestor(Rr.dirname(i)),Rr.basename(i));if(a!==o&&!a.startsWith(o+Rr.sep))throw new s6.PathTraversalError(t,this.root);return i}async readText(t){let n=this.pathFor(t);if(!xn.existsSync(n))return null;try{return await(0,u6.retryTransientIoAsync)(()=>xn.promises.readFile(n,"utf8"))}catch(r){if(r.code==="ENOENT")return null;throw r}}async writeTextAtomic(t,n){let r=this.pathFor(t),i=Rr.dirname(r);await xn.promises.mkdir(i,{recursive:!0});let o=Rr.join(i,`.${Rr.basename(r)}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`);try{await xn.promises.writeFile(o,n,"utf8"),await(0,u6.retryTransientIoAsync)(()=>xn.promises.rename(o,r))}catch(a){try{xn.existsSync(o)&&await xn.promises.unlink(o)}catch{}throw a}}async deleteFile(t){let n=this.pathFor(t);xn.existsSync(n)&&await xn.promises.unlink(n)}async deleteByPrefix(t){await c6(this.pathFor(t,!1))}async ensureContainer(t){await xn.promises.mkdir(this.pathFor(t),{recursive:!0})}async exists(t){return xn.existsSync(this.pathFor(t))}};Ra.NodeFileSystemStorage=lT});var d6=C(Ni=>{"use strict";var W_e=Ni&&Ni.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),z_e=Ni&&Ni.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),H_e=Ni&&Ni.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var n in e)n!=="default"&&Object.prototype.hasOwnProperty.call(e,n)&&W_e(t,e,n);return z_e(t,e),t};Object.defineProperty(Ni,"__esModule",{value:!0});Ni.loadNodeTypeScript=Ni.createNodeWorkspaceStorage=Ni.NodeFileSystemStorage=void 0;var K_e=cT(),J_e=cT();Object.defineProperty(Ni,"NodeFileSystemStorage",{enumerable:!0,get:function(){return J_e.NodeFileSystemStorage}});function Y_e(e){return new K_e.NodeFileSystemStorage(e)}Ni.createNodeWorkspaceStorage=Y_e;async function Q_e(){return await Promise.resolve().then(()=>H_e(require("typescript")))}Ni.loadNodeTypeScript=Q_e});var Is={};module.exports=_i(Is);Os(Is,Xe(a6()),module.exports);Os(Is,Xe(d6()),module.exports);diff --git a/plugins/model-apps/skills/app-builder/SKILL.md b/plugins/model-apps/skills/app-builder/SKILL.mdindex 0d245dc3e..666bd78fd 100644--- a/plugins/model-apps/skills/app-builder/SKILL.md+++ b/plugins/model-apps/skills/app-builder/SKILL.md@@ -367,19 +367,21 @@ After plan-mode approval (before the full build):that starts with `--`, `&`, `:` or `@` is read); Fluent's `...shorthands.*(…)` and`...typographyStyles.*` may be spread as they are.- Review every generated page for iteration that compiles to nothing as well:-- The page compiler targets ES5 without iterator downleveling or full type checking. Spreading,- looping over, or array-destructuring a Map, Set or iterator reads length and indices instead of- the iterator: values can disappear, defaults can replace them, or rest destructuring can throw.- This includes `[...new Set(xs)]`, `[...m.values()]`, `[...seen.values()]`,- `for (const [k, v] of m)`, `new Set([...prev, id])`, `[...selected]` and- `[...text.matchAll(re)]`. Convert with `Array.from(...)` before spreading, looping or- destructuring; copy a Set with `new Set(prev)` then `.add(id)`. Ordinary array spreads and loops- remain valid. `Object.keys`, `Object.values` and `Object.entries` return arrays. Spreads of- `arguments` and ordinary indexed array-likes work; rest destructuring of an array-like without- `slice` does not. String spread throws, and an ES5 string loop visits UTF-16 code units rather- than Unicode code points. See **Common Errors > 5. Iteration that compiles to nothing** in+ Review every generated page for iteration that another page compiler can lose as well:++ Pages this plugin uploads are compiled with iterator support (ES5 with `downlevelIteration`), so a+ spread, a `for...of` loop or an array destructure of a Map, Set, iterator, generator or string+ reads it as modern JavaScript does. A tool that compiles the page again without that support — an+ older maker portal, or `pac` — reads length and indices instead: values disappear, defaults replace+ them, and rest destructuring or a string spread throws, all with a clean compile. Keep the page+ correct under every compiler: convert with `Array.from(...)` before spreading, looping or+ destructuring, for example `[...new Set(xs)]`, `[...m.values()]`, `[...seen.values()]`, `for (const+ [k, v] of m)`, `new Set([...prev, id])`, `[...selected]` and `[...text.matchAll(re)]`; copy a Set+ with `new Set(prev)` then `.add(id)`. Ordinary array spreads and loops remain valid. `Object.keys`,+ `Object.values` and `Object.entries` return arrays. Rest destructuring of a non-iterable array-like without+ `slice` throws under every compiler. A destructuring default must not write to the array being+ destructured: `const [a = (values[1] = 3), b] = values` leaves `b` at its old value here, unlike+ modern JavaScript. See **Common Errors > 5. Iteration that another page compiler can lose** in`references/rules.md` for the pairs.Then validate and commit the transition — never flip `source` by hand, and never@@ -799,9 +801,10 @@ Then:key it already has only draws a warning — and so does a page you changed in a workspace that holds no record of it (a new or moved one, oranother environment), where the build cannot tell what was sent: run the checker on that page yourself.A page you edit by hand also follows the iteration rule of Phase 1.5, step 5 (**Common Errors > 5.- Iteration that compiles to nothing** in `references/rules.md`): convert a Map, Set or iterator with- `Array.from` before spreading, looping over or destructuring it. Converting a form the page already- had can make previously absent values appear, so do it only when the requested change needs it.+ Iteration that another page compiler can lose** in `references/rules.md`): convert a Map, Set or+ iterator with `Array.from` before spreading, looping over or destructuring it. An upload compiles the+ changed page again with iterator support, so a form it already had now reads its values where an+ earlier release lost them, converted or not; convert such a form only when the requested change needs it.3. **If the edit ADDS a page** (or resets a page's `source` back to `intent` to regenerate it),**re-run Phase 1.5 before Phase 2** — a downloaded spec contains only `kind: "tsx"` pages, so anadded `intent` page has no code and Phase 2's `deploy` profile rejects it. Phase 1.5 is safe to@@ -829,7 +832,7 @@ laid out, explicit `tabs` honored; sub-grids, quick-views, and form JS (`events[canonical control cells / the `/bag/c` events region via the SDK's generic `addElement` surface)→ **business rules** (`businessRules[]` — authored as the workflow object model through the bound`CreateProcessWithWfomJson` member and activated; **skipped with a warning** on an environment that-does not declare that member) →+does not declare that member or has it switched off — HTTP 400 `0x80040216`, common on production environments) →**business process flows** (`businessProcessFlows[]`; a category-4 process compiled from theauthored stages and activated — this goes through the SDK's generic artifact surface, a plain`workflows` row, so it is NOT subject to the bound-member gate above) →@@ -913,8 +916,10 @@ child view id. Each step emits `[n/total]`.upstream because it covered 4 of the 7 action types and a single clause, so it silently narroweda rule into something that did not say what the author wrote. Environments that do not declarethe member therefore **cannot host business rules at all** — and that is the common case, not an- edge case. The build **skips** the rules, warns once naming the- member, and builds everything else normally, so an app is never left half-created. If rules are+ edge case. **Production environments are the other common case**: they declare the member but+ answer the first rule with HTTP 400 `0x80040216` ("An unexpected error occurred."), a platform+ limit, and nothing is created. The build **skips** the rules in both cases, warns once naming the+ member or the code, and builds everything else normally, so an app is never left half-created. If rules areessential, verify the environment first.**Business process flows are NOT affected by this gate** — a BPF is written as an ordinary`workflows` row through the SDK's generic artifact surface, with no bound member involved.diff --git a/plugins/model-apps/skills/genpage/SKILL.md b/plugins/model-apps/skills/genpage/SKILL.mdindex 2fb2473d9..9025602d8 100644--- a/plugins/model-apps/skills/genpage/SKILL.md+++ b/plugins/model-apps/skills/genpage/SKILL.md@@ -545,7 +545,8 @@ It returns a single JSON object:{"ok": true | false,"blocker": null | "usage" | "az_missing" | "az_not_logged_in" | "az_timeout" | "pac_not_logged_in"- | "pac_timeout" | "no_env_url" | "whoami_403" | "whoami_401" | "whoami_error",+ | "pac_timeout" | "no_env_url" | "whoami_403" | "whoami_401" | "whoami_error"+ | "no_customization_role","message": "human-readable next step","warnings": ["..."],"azUser": "...", "pacUser": "...", "envUrl": "...",@@ -567,6 +568,10 @@ It returns a single JSON object:- **`blocker: "az_timeout"`** means the Azure CLI was too slow to answer, not that it is missing orsigned out. Retry once; if it recurs on a busy machine, set `POWER_PLATFORM_SKILLS_AZ_TIMEOUT_MS`(milliseconds, default 60000) for the Azure CLI budget.+- **`blocker: "no_customization_role"`** means WhoAmI passed but the identity holds no security role, so+ every customization read would fail (HTTP 403 `0x80042f09`). Show the `message` and stop: the maker+ needs an administrator to assign a role such as System Customizer (or to sign in as the PAC user when+ `message` offers it). Any other failure of that one extra read is only a `warnings` entry.- **`blocker: "pac_timeout"`** means `pac org who` did not answer within its fixed 60 s, so the PAClogin is unknown, not missing. Retry once. The Azure CLI setting above does not change this budget.@@ -914,21 +919,24 @@ subagent. Inline the page-builder workflow directly in the orchestrator:cannot see (a template that starts with `--`, `&`, `:` or `@` is read); Fluent's`...shorthands.*(…)` and `...typographyStyles.*` may be spread as they are.- Then review the page for iteration that compiles to nothing:+ Then review the page for iteration that another page compiler can lose:- The page compiler targets ES5 without iterator downleveling or full type checking.- Spreading, looping over, or array-destructuring a Map, Set or iterator reads length- and indices instead of the iterator: values can disappear, defaults can replace them,- or rest destructuring can throw. This includes `[...new Set(xs)]`, `[...m.values()]`,+ Pages this plugin uploads are compiled with iterator support (ES5 with+ `downlevelIteration`), so a spread, a `for...of` loop or an array destructure of a Map,+ Set, iterator, generator or string reads it as modern JavaScript does. A tool that+ compiles the page again without that support — an older maker portal, or `pac` — reads+ length and indices instead: values disappear, defaults replace them, and rest+ destructuring or a string spread throws, all with a clean compile. Keep the page+ correct under every compiler: convert with `Array.from(...)` before spreading, looping+ or destructuring, for example `[...new Set(xs)]`, `[...m.values()]`,`[...seen.values()]`, `for (const [k, v] of m)`, `new Set([...prev, id])`,- `[...selected]` and `[...text.matchAll(re)]`. Convert with `Array.from(...)` before- spreading, looping or destructuring; copy a Set with `new Set(prev)` then `.add(id)`.- Ordinary array spreads and loops remain valid. `Object.keys`, `Object.values` and- `Object.entries` return arrays. Spreads of `arguments` and ordinary indexed- array-likes work; rest destructuring of an array-like without `slice` does not.- String spread throws, and an ES5 string loop visits UTF-16 code units rather than- Unicode code points. See **Common Errors > 5. Iteration that compiles to nothing**- in `references/rules.md` for the pairs.+ `[...selected]` and `[...text.matchAll(re)]`; copy a Set with `new Set(prev)` then+ `.add(id)`. Ordinary array spreads and loops remain valid. `Object.keys`,+ `Object.values` and `Object.entries` return arrays. Rest destructuring of a non-iterable array-like+ without `slice` throws under every compiler. A destructuring default must not write to+ the array being destructured: `const [a = (values[1] = 3), b] = values` leaves `b` at+ its old value here, unlike modern JavaScript. See **Common Errors > 5. Iteration that+ another page compiler can lose** in `references/rules.md` for the pairs.10. Run the completeness gate on the page you wrote — the same one 5c runs on aworker's page, and this is also the page a 5c fallback produces:@@ -1032,9 +1040,9 @@ node "${PLUGIN_ROOT}/scripts/check-griffel-styles.js" --file '<working-dir>/<fil```and fix what it reports in the page yourself before Phase 6. A page that has not-exited 0 is not deployed. Review every generated page for iteration that compiles to-nothing as well, and fix it yourself: the workers follow the same rule-(`references/rules.md`, **Common Errors > 5. Iteration that compiles to nothing**).+exited 0 is not deployed. Review every generated page for iteration that another page+compiler can lose as well, and fix it yourself: the workers follow the same rule+(`references/rules.md`, **Common Errors > 5. Iteration that another page compiler can lose**).### Phase 6: Deploydiff --git a/plugins/model-apps/skills/genpage/edit-flow.md b/plugins/model-apps/skills/genpage/edit-flow.mdindex b709a3a12..046a779d7 100644--- a/plugins/model-apps/skills/genpage/edit-flow.md+++ b/plugins/model-apps/skills/genpage/edit-flow.md@@ -560,25 +560,33 @@ the same, go ahead with a`warnings` entry, but the page then goes on rendering without it — do not rely on that toskip this step.)-Review the edited page for iteration that compiles to nothing as well:--The page compiler targets ES5 without iterator downleveling or full type checking.-Spreading, looping over, or array-destructuring a Map, Set or iterator reads length-and indices instead of the iterator: values can disappear, defaults can replace them,-or rest destructuring can throw. This includes `[...new Set(xs)]`, `[...m.values()]`,-`[...seen.values()]`, `for (const [k, v] of m)`, `new Set([...prev, id])`,-`[...selected]` and `[...text.matchAll(re)]`. Convert with `Array.from(...)` before-spreading, looping or destructuring; copy a Set with `new Set(prev)` then `.add(id)`.-Ordinary array spreads and loops remain valid. `Object.keys`, `Object.values` and-`Object.entries` return arrays. Spreads of `arguments` and ordinary indexed array-likes-work; rest destructuring of an array-like without `slice` does not. String spread-throws, and an ES5 string loop visits UTF-16 code units rather than Unicode code-points. See **Common Errors > 5. Iteration that compiles to nothing** in-`references/rules.md` for the pairs.--Write every form your edit adds with that conversion. A form the page already had-before your edit loses its values today, and converting it with `Array.from` can make-previously absent values appear or stop a throw — a change users see. Do not silently+Review the edited page for iteration that another page compiler can lose as well:++Pages this plugin uploads are compiled with iterator support (ES5 with+`downlevelIteration`), so a spread, a `for...of` loop or an array destructure of a Map,+Set, iterator, generator or string reads it as modern JavaScript does. A tool that+compiles the page again without that support — an older maker portal, or `pac` — reads+length and indices instead: values disappear, defaults replace them, and rest+destructuring or a string spread throws, all with a clean compile. Keep the page correct+under every compiler: convert with `Array.from(...)` before spreading, looping or+destructuring, for example `[...new Set(xs)]`, `[...m.values()]`, `[...seen.values()]`,+`for (const [k, v] of m)`, `new Set([...prev, id])`, `[...selected]` and+`[...text.matchAll(re)]`; copy a Set with `new Set(prev)` then `.add(id)`. Ordinary+array spreads and loops remain valid. `Object.keys`, `Object.values` and+`Object.entries` return arrays. Rest destructuring of a non-iterable array-like without `slice`+throws under every compiler. A destructuring default must not write to the array being+destructured: `const [a = (values[1] = 3), b] = values` leaves `b` at its old value+here, unlike modern JavaScript. See **Common Errors > 5. Iteration that another page+compiler can lose** in `references/rules.md` for the pairs.++Write every form your edit adds with that conversion. The upload compiles the whole page+again with iterator support, so a form the page already had now reads its values or stops+throwing where an earlier release's upload lost them — a change users see, converted or+not: say so in the summary when the page has such a form. Converting it keeps the page+correct under an older compiler, but `Array.from` reads the whole iterable at once: where a+loop stops early or a destructure reads only the first values of a generator or another+iterator, the conversion reads the rest too — check that doing so changes nothing the page+shows or does before converting such a form. Do not silentlyexpand an unrelated edit: convert an existing form only when the requested change needsit or the user asks for it, and state any resulting behavior change in the summary.diff --git a/plugins/model-apps/skills/genpage/verify-flow.md b/plugins/model-apps/skills/genpage/verify-flow.mdindex ebac4252a..4d4f2b1f6 100644--- a/plugins/model-apps/skills/genpage/verify-flow.md+++ b/plugins/model-apps/skills/genpage/verify-flow.md@@ -113,7 +113,7 @@ delete it to keep the page looking as it does, or write the longhands to make thrender (a visible change, so only when it is wanted).A fix is held to the iteration rule too: convert a Map, Set or iterator with `Array.from` beforespreading, looping over or destructuring it (`references/rules.md`, **Common Errors > 5. Iteration-that compiles to nothing**).+that another page compiler can lose**).Per the "Prompt semantics" rule, the prompt for thisre-deploy describes the fix delta only — e.g.`"Fix sort handler on Name column; correct accidental DataGrid type prop"` —diff --git a/plugins/pcf/CHANGELOG.md b/plugins/pcf/CHANGELOG.mdindex 67afde87b..9b41087d9 100644--- a/plugins/pcf/CHANGELOG.md+++ b/plugins/pcf/CHANGELOG.md@@ -13,12 +13,13 @@ First preview release: ships the `/pcf:pcf` skill, matrix-pinned templates and r### Changed-- The bundled SDK is the one model-apps 2.18.0 ships (power-platform-ux a3443479), beside model-apps 2.18.0's HTTP client; the SDK no longer carries its PCF control registration, which this plugin never called. What changed in them — a web resource's published content read back, an app's sitemap found by its component, a publish sent once — is in requests this plugin does not make: it only reads through them and publishes through PAC, so what it does is unchanged.+- The bundled SDK is the one model-apps 2.20.6 ships (commit 59ae2d72e2a8), beside model-apps 2.20.6's HTTP client; the SDK no longer carries its PCF control registration, which this plugin never called. This plugin only reads through them and publishes through PAC; its reads pass its real-bundle tests unchanged.- The PCF guide explains why calls after an early-return guard or in an `else` branch are reported, and shows the positive guard block to use instead.- An optional call with type arguments that is handed a context member, such as `factory?.<T>(context.device).captureImage()`, is now reported as a Pages call even when the factory returns its own object; call it without `?.` or keep the result in a local first.### Fixed+- `check-auth.js` no longer reports success for an identity that cannot read customizations (no security role in the environment); it fails with `no_customization_role` and names a role to ask for.- The push receipt (`pcf-receipt.json`) no longer carries an access token that a refused confirmation read quoted, and every file the SDK writes into a push's workspace goes through the same output guard as model-apps' scripts.- A large result is no longer cut short on Linux and macOS: `emitResult`, the printer of an uncaught error, `check-auth.js`, the result printers of `pcf-inventory.js`, `verify-pcf.js` and `lint-pcf.js`, every script's usage error and the write-safety hook's message make their writes blocking before the process exits. What is printed and every exit status are unchanged; Windows was never affected.- The output guard (the same module model-apps 2.19.0 ships) also keeps an access token out of bytes written to stdout or stderr, masked with `*` byte for byte so framed output keeps its length, out of the token's base64 — and the base64 of each of its parts of 24 characters or more — and its percent-encoded and HTML spellings, and out of a token that `util.inspect` or an ellipsis cut short or that was split between two writes (each piece of 24 characters or more), keeping an escape split between two writes whole, also after a nested write and the write around it were both refused. Still left: a piece shorter than 24 characters, the middle piece of a token written in three or more writes, a short piece on the far side of a split escape, base64 of a piece of the token that is not a whole part, and bytes written to a file.diff --git a/plugins/pcf/scripts/check-auth.js b/plugins/pcf/scripts/check-auth.jsindex 47675bbcb..e40f68680 100644--- a/plugins/pcf/scripts/check-auth.js+++ b/plugins/pcf/scripts/check-auth.js@@ -20,7 +20,7 @@// {// "ok": true|false,// "blocker": null | "az_missing" | "az_not_logged_in" | "az_timeout" | "pac_not_logged_in" | "pac_timeout"-// | "no_env_url" | "whoami_403" | "whoami_401" | "whoami_error",+// | "no_env_url" | "whoami_403" | "whoami_401" | "whoami_error" | "no_customization_role",// "message": "human-readable next step",// "warnings": ["..."],// "azUser": "...",@@ -37,6 +37,10 @@// read the environment; a missing/for-different-identity pac login is surfaced as a WARNING, not a hard// blocker.//+// After a passing WhoAmI one more GET (`solutions?$select=solutionid&$top=1`, the first read a build makes)+// checks the identity can read customizations: an HTTP 403 `0x80042f09` ("has not been assigned any roles")+// is `ok: false` with blocker `no_customization_role`. Any other outcome of that read is a warning only.+//// Exit code 0 always (so callers can parse stdout). Use `ok` field to gate.const { execFileAsync } = require('./lib/process-runner.js');@@ -54,6 +58,9 @@ const PAC_PROBE_TIMEOUT_MS = 60000;// print model-apps' flows.const PAC_OPTIONAL_NOTE = 'That does not block a step that signs in with the az token alone: only a step that runs `pac` needs the login, and so does reading the environment when --env is omitted.';+// The Dataverse error code of a read refused to a user who holds no security role (see the capability probe in main()).+const NO_ROLE_CODE = '0x80042f09';+// Read the env URL from either `--env <url>` (the flag the build/verify/teardown scripts use) or// the first positional arg, so a caller can copy the `--env` form here without silently passing// the literal string "--env" as the URL (the prior positional-only parse did exactly that).@@ -371,6 +378,46 @@ async function main() {);}+ // 4) Capability probe. WhoAmI answers for ANY user the environment knows, role or not, so it said "ready" for an identity+ // that holds no security role: every customization read then fails, and the first build step is where the maker found out.+ // One read the build itself starts with (its solution) tells. Measured on an identity with no role:+ // GET solutions?$select=solutionid&$top=1 -> HTTP 403+ // {"error":{"code":"0x80042f09","message":"The user with id <id> has not been assigned any roles. They need a role with the prvReadCustomization privilege."}}+ // (`sitemaps`, `roles` and `publishers` answered the same.) A COUNT of the user's roles would be wrong: privileges also come+ // through teams, so a user with no role of their own can read customizations. The code decides, never the words — the platform+ // answers in the caller's language. Any other outcome of the probe (another 403 code, a 5xx, a transport failure) proves nothing+ // about roles, so it is a warning and never a verdict: a false "no role" would send a working maker to an administrator.+ // https://learn.microsoft.com/power-platform/admin/security-roles-privileges+ let probe = null;+ try {+ probe = await dataverseRequest(envUrl, 'GET', 'solutions?$select=solutionid&$top=1', null, { timeout: 30000 });+ } catch (e) {+ warnings.push(`Could not confirm the identity can read customizations (${e.message}). WhoAmI passed, so this is not taken as a missing role.`);+ }+ if (probe) {+ const probeCode = probe.data && probe.data.error && probe.data.error.code;+ if (probe.status === 403 && String(probeCode || '').toLowerCase() === NO_ROLE_CODE) {+ const otherIdentity = pacUser && !identitiesMatch+ ? ` Or sign in as the PAC user if that identity holds a role: \`az login --username ${pacUser}\`.`+ : '';+ return emit(+ buildResult({+ azUser,+ pacUser,+ envUrl,+ identitiesMatch,+ warnings,+ whoAmI: { ok: true, userId: whoRes.data?.UserId, organizationId: whoRes.data?.OrganizationId },+ blocker: 'no_customization_role',+ message: `WhoAmI passed, but "${azUser}" has no security role in ${envUrl}, so it cannot read customizations (HTTP 403 ${NO_ROLE_CODE}: the prvReadCustomization privilege is missing). Ask an environment administrator to assign a role such as System Customizer.${otherIdentity}`,+ })+ );+ }+ if (probe.status < 200 || probe.status >= 300) {+ warnings.push(`Could not confirm the identity can read customizations (HTTP ${probe.status}${probeCode ? ` ${probeCode}` : ''}). WhoAmI passed, so this is not taken as a missing role.`);+ }+ }+// A pac probe that ran out of time says THAT here too — its warning already does, and "not logged in" beside// it contradicted it: a slow PAC CLI's login is unknown, not missing.const readyMessage = !pacUserdiff --git a/plugins/pcf/scripts/lib/sdk-http-client.js b/plugins/pcf/scripts/lib/sdk-http-client.jsindex 2d14267f5..fdd66f494 100644--- a/plugins/pcf/scripts/lib/sdk-http-client.js+++ b/plugins/pcf/scripts/lib/sdk-http-client.js@@ -16,6 +16,10 @@const { dataverseOrigin, getAuthToken, makeRequest, tokenFailureMessage } = require('./dataverse-auth.js');const { needlesOf, noteToken, TOKEN_MARKER } = require('./output-redaction.js');+// The key under which a failure's body carries the history of the sends that led to it (`{ sends, earlierAmbiguous }`, see `ambiguousSends` in createAzHttpClient).+// Symbol.for, so a module that reads it need not load this client, and the copy of this file in another plugin agrees with it.+const HTTP_SEND_HISTORY = Symbol.for('power-platform-skills.http-send-history');+// How Dataverse reports that SQL Server chose a request's transaction as a deadlock VICTIM and rolled// it back. Two live captures, both HTTP 500 (a process-flow delete during a teardown, and PublishXml):// HTTP 500 from …/api/data/v9.0/workflows(<id>): Sql error: Generic SQL error. CRM ErrorCode: -2147204784 Sql ErrorCode: -2146232060 Sql Number: 1205@@ -709,6 +713,14 @@ function createAzHttpClient(orgUrl, deps = {}) {// Every access token this client has sent — the one a 401 refresh replaced as well as the one that replaced it, because a service may repeat either — for taking it out of an answer that is not a success// and out of a transport failure's text (the scrubber above). A success is never given to these.const tokensSent = new Set();++ // The sends of a write that may have run, whatever answered them: `POST <url>` -> true once a send of it got no answer, was cut off, or was answered by the+ // service being down or throttling (5xx; a 429 that is not the service protection limits). Such a send can have been applied; an answer to a LATER send of the+ // same request — a re-send of this client's loop, or the SDK's own re-call — says nothing about it. A failure delivered afterwards says so (HTTP_SEND_HISTORY),+ // so a caller that reads the later answer as a definitive refusal (the business-rule gate in lib/sdk-build.js) can tell it is not. Kept for the client's life and+ // never cleared: it only ever turns a caller's skip into the halt it always was.+ const ambiguousSends = new Set();+ const isAmbiguousAnswer = (res) => Boolean(res.error) || res.statusCode >= 500 || (res.statusCode === 429 && !isServiceProtectionRefusal(res));const scrubText = (text) => [...tokensSent].reduce((out, sent) => scrub(out, sent), String(text));const scrubValue = (value) => [...tokensSent].reduce((out, sent) => scrubAnswer(out, sent), value);// A Buffer is returned as it is unless it holds the token as text: bytes that are not text, or hold no token, are never decoded into something else.@@ -808,14 +820,20 @@ function createAzHttpClient(orgUrl, deps = {}) {// What the caller is given for an answer that is not sent again — the last the loop got, or a throttled one a budgeted client did not wait for. An answer that is not a success is what an SDK makes an error message of (it quotes the body, and the// scripts print that message), so the token is taken out of it first — the body in whatever mode it is read in, and the headers. A success is the caller's data and is returned exactly as it came.- const deliver = (res) => {+ const deliver = (res, history) => {if (!(res.statusCode >= 200 && res.statusCode < 300)) {const text = (value) => (typeof value === 'string' ? scrubText(value) : value);- return {+ const answer = {status: res.statusCode,headers: scrubValue(res.headers || {}),body: ctl.bytes ? scrubBytes(res.body) : ctl.rawBody ? text(res.body) : scrubValue(parseBody(text(res.body))),};+ // The SDK keeps a failure's body as the `cause` of the error it raises, the same object, so this reaches the caller of the SDK. A body that is not an+ // object (text, bytes) carries nothing, and a caller that needs the history then has none to read.+ if (history && answer.body && typeof answer.body === 'object' && !Buffer.isBuffer(answer.body)) {+ Object.defineProperty(answer.body, HTTP_SEND_HISTORY, { value: history, enumerable: false });+ }+ return answer;}return {status: res.statusCode,@@ -853,6 +871,10 @@ function createAzHttpClient(orgUrl, deps = {}) {}const res = await request({ url, method, headers, body: bodyOut, includeHeaders: true, timeout: isWrite ? WRITE_TIMEOUT_MS : READ_TIMEOUT_MS, ...(ctl.bytes ? { binary: true } : {}) });+ // Read before this answer is recorded: what matters to a caller is whether an EARLIER send was ambiguous.+ const sendKey = `${method_} ${url}`;+ const history = { sends: attempt + 1, earlierAmbiguous: ambiguousSends.has(sendKey) };+ if (isWrite && isAmbiguousAnswer(res)) ambiguousSends.add(sendKey);if (res.error) {if (conditional) {throw transportError(res, `Request failed: ${scrubText(res.error)} — this conditional ${method_} was not re-sent, because it may still commit and a re-send could only be refused as a false version conflict`);@@ -883,7 +905,7 @@ function createAzHttpClient(orgUrl, deps = {}) {// victim (500), a gateway (502, 503, 504) — is not throttling, and keeps its own schedule.if (throttle && res.statusCode === 429) {if (await waitOutThrottle({ res, attempt, method: method_, url })) continue;- return deliver(res);+ return deliver(res, history);}await sleep(retryWaitMs(res, attempt));continue;@@ -915,7 +937,7 @@ function createAzHttpClient(orgUrl, deps = {}) {if (throttled && !last) {if (throttle) {if (await waitOutThrottle({ res, attempt, method: method_, url, batch: isBatch })) continue;- return deliver(res);+ return deliver(res, history);}// A batch refused operation by operation may carry the wait in that operation's own headers.await sleep(Math.max(retryWaitMs(res, attempt), isBatch ? batchRetryAfterMs(res, now()) : 0));@@ -927,7 +949,7 @@ function createAzHttpClient(orgUrl, deps = {}) {await sleep(1000 * 2 ** attempt);continue;}- return deliver(res);+ return deliver(res, history);}/* istanbul ignore next */throw new Error('Unreachable retry loop');@@ -964,4 +986,4 @@ function createAzHttpClient(orgUrl, deps = {}) {};}-module.exports = { createAzHttpClient, SQL_DEADLOCK_VICTIM, DEADLOCK_RESENDS, isSqlDeadlockVictim, isBatchDeadlockVictim, isBatchThrottled, completeBatchStatus, batchRetryAfterMs, isConditionalDeleteBatch, isColumnCreateBatch, isTransientTransportFailure, TRANSIENT_TRANSPORT_CODES, SERVICE_PROTECTION_CODES, isServiceProtectionRefusal, retryAfterMs, throttleBackoffMs, RETRY_AFTER_CAP_MS, scrub, scrubAnswer, scrubBearer, MIN_SCRUBBED_TOKEN_LENGTH };+module.exports = { createAzHttpClient, HTTP_SEND_HISTORY, SQL_DEADLOCK_VICTIM, DEADLOCK_RESENDS, isSqlDeadlockVictim, isBatchDeadlockVictim, isBatchThrottled, completeBatchStatus, batchRetryAfterMs, isConditionalDeleteBatch, isColumnCreateBatch, isTransientTransportFailure, TRANSIENT_TRANSPORT_CODES, SERVICE_PROTECTION_CODES, isServiceProtectionRefusal, retryAfterMs, throttleBackoffMs, RETRY_AFTER_CAP_MS, scrub, scrubAnswer, scrubBearer, MIN_SCRUBBED_TOKEN_LENGTH };diff --git a/plugins/pcf/scripts/tests/pcf-pages-guard.test.js b/plugins/pcf/scripts/tests/pcf-pages-guard.test.jsindex 120c2bdb2..9487c6137 100644--- a/plugins/pcf/scripts/tests/pcf-pages-guard.test.js+++ b/plugins/pcf/scripts/tests/pcf-pages-guard.test.js@@ -835,11 +835,62 @@ test('Pages proof keeps lexical this in arrows but not rebinding functions or classert.match(findingsFor(THIS_CALL).find((finding) => finding.code === 'PCF_PAGES_API').message, /this\._ctx\?\.device\?\.captureImage/);});-// These generous CI bounds distinguish indexed lookup from repeatedly scanning a guard's-// deeply nested body. The smaller realistic fixture also catches per-call scope rescans.-const NESTED_SCAN_LIMIT_MS = 1500;-const CONTROL_SCAN_LIMIT_MS = 500;+// Complexity guards. They exist to catch a rescan that turns linear work into quadratic (or+// exponential) work, not to measure how fast a machine is, so none of them bounds a wall-clock time+// that load alone can exceed (the old fixed 500-1500 ms bounds failed on a busy machine):+// - Where the gate exposes its work (lexer passes, the line-start table) the test counts that work.+// A count does not depend on load.+// - Otherwise the test times one fixture at a quarter of its size and at full size and bounds the+// growth. Linear work grows about 4x (2-6x measured); quadratic work grows 16x. A slow or busy+// machine slows both runs alike, so the ratio holds. Each side is the fastest of several runs, so+// a pause that hits one run is ignored, and a ratio over the limit is measured again (a real+// regression exceeds it every time).+// - Every timed test keeps an absolute ceiling, at least 10x the old bound, as a catastrophe guard.+const GROWTH_RUNS = 5;+const GROWTH_ATTEMPTS = 3;+const GROWTH_LIMIT = 10;+const CATASTROPHE_LIMIT_MS = 15000;++function fastest(runs, fn) {+ let best = Infinity;+ for (let i = 0; i < runs; i += 1) {+ const started = performance.now();+ fn();+ best = Math.min(best, performance.now() - started);+ // Already past the catastrophe ceiling: more runs only make a failing test slower.+ if (best > CATASTROPHE_LIMIT_MS) break;+ }+ return best;+}+// `build(scale)` returns the fixture at `scale` of its full size; `run(text)` returns the findings.+// Returns the findings for the full-size fixture so the caller can keep asserting on them.+function assertLinearGrowth(t, label, build, run) {+ const small = build(0.25);+ const full = build(1);+ // The first runs pay for JIT compilation, which is not growth with size.+ run(small);+ run(small);+ let growth = Infinity;+ let fullMs = Infinity;+ for (let attempt = 1; attempt <= GROWTH_ATTEMPTS && growth >= GROWTH_LIMIT; attempt += 1) {+ const smallMs = fastest(GROWTH_RUNS, () => run(small));+ fullMs = fastest(GROWTH_RUNS, () => run(full));+ // Timer noise dominates below a millisecond, so do not divide by less.+ growth = fullMs / Math.max(smallMs, 1);+ t.diagnostic(`${label}: ${smallMs.toFixed(3)} ms at 1/4 size, ${fullMs.toFixed(3)} ms at full size, growth ${growth.toFixed(2)}x (attempt ${attempt})`);+ }+ assert.ok(growth < GROWTH_LIMIT, `${label}: work grew ${growth.toFixed(2)}x for 4x the input; linear work grows about 4x and quadratic work 16x`);+ assert.ok(fullMs < CATASTROPHE_LIMIT_MS, `${label}: ${fullMs.toFixed(3)} ms exceeds ${CATASTROPHE_LIMIT_MS} ms`);+ return run(full);+}++function scanBoth(text, feature, hosts) {+ return [...scanSource(FILE, text), ...findingsFor(text, feature, hosts)];+}++// Wall-clock timing, kept only by the line-location test (see its comment): a bound on elapsed+// time is sensitive to machine load, unlike the work counts and growth ratios used elsewhere.// A wall-clock limit on ONE cold run is noise-bound, not a test of the scanner: the first run pays the JIT's warm-up, and a// shared CI runner adds GC and scheduler pauses on top (observed: 501 ms against the 500 ms limit on a Windows runner, while// local single runs vary 125–253 ms for the same input). So the scan runs once untimed to warm up, then three times, and the@@ -856,34 +907,83 @@ function timedScan(text) {return { elapsed, findings };}+// A second copy of the gate whose lexer calls are counted. The gate reads its lexer through a+// destructured import, so the counting wrapper must be in place when the module loads; the shared+// exports and the first copy (the one every other test uses) are restored straight after.+// Lexer passes are the unit of work for .ts angle-bracket types: the file must be lexed a bounded+// number of times however many types it holds, because each pass reads the whole file.+function loadCountingGate() {+ const literalsPath = require.resolve('../lib/source-literals.js');+ const gatePath = require.resolve('../lib/pcf-code-gate.js');+ const literals = require(literalsPath);+ const original = literals.blankNonCodePreservingTemplateExpressions;+ const stats = { calls: 0, chars: 0 };+ const loaded = require.cache[gatePath];+ literals.blankNonCodePreservingTemplateExpressions = function counting(text, options) {+ stats.calls += 1;+ stats.chars += text.length;+ return original.call(this, text, options);+ };+ delete require.cache[gatePath];+ try {+ return { gate: require(gatePath), stats };+ } finally {+ literals.blankNonCodePreservingTemplateExpressions = original;+ if (loaded) require.cache[gatePath] = loaded;+ else delete require.cache[gatePath];+ }+}++const counting = loadCountingGate();++function lexWork(fn) {+ counting.stats.calls = 0;+ counting.stats.chars = 0;+ const result = fn();+ return { calls: counting.stats.calls, chars: counting.stats.chars, result };+}++// Measured: 2-4 lexer passes and 2-4 characters lexed per source character, however many casts the+// file holds. Lexing once per type (the sequential loop) reads the whole file 31 to 601 times, so+// 8 leaves room for another pass without letting that regression through.+const MAX_LEX_PASSES = 8;+function assertBoundedLexing(label, text, work) {+ assert.ok(work.calls <= MAX_LEX_PASSES, `${label}: ${work.calls} lexer passes (limit ${MAX_LEX_PASSES})`);+ assert.ok(work.chars <= MAX_LEX_PASSES * text.length,+ `${label}: lexed ${work.chars} characters of a ${text.length}-character file (limit ${MAX_LEX_PASSES}x)`);+}+test('Pages proof indexes the 5000-line nested fixture without quadratic rescans', (t) => {- const text = [- `if (${PROOF}) {`,- ...Array(8).fill(`${CALL};`),- ...Array(2495).fill('run(() => {'),- ...Array(2495).fill('});'),- '}',- ].join('\n');- assert.equal(text.split('\n').length, 5000);- const { elapsed, findings } = timedScan(text);- t.diagnostic(`nested timing: ${elapsed.toFixed(3)} ms; ${Buffer.byteLength(text)} bytes`);- assert.ok(elapsed < NESTED_SCAN_LIMIT_MS, `${elapsed.toFixed(3)} ms exceeds ${NESTED_SCAN_LIMIT_MS} ms`);- assert.deepEqual(findings, []);+ // The guard's body nests 2495 callbacks deep; a lookup that rebalances the body for each scope or+ // call, instead of reading the index, makes this fixture quadratic.+ const build = (scale) => {+ const depth = Math.round(2495 * scale);+ return [+ `if (${PROOF}) {`,+ ...Array(8).fill(`${CALL};`),+ ...Array(depth).fill('run(() => {'),+ ...Array(depth).fill('});'),+ '}',+ ].join('\n');+ };+ assert.equal(build(1).split('\n').length, 5000);+ assert.deepEqual(assertLinearGrowth(t, 'nested', build, scanBoth), []);});test('Pages proof indexes a 3000-line realistic control with 40 guarded calls', (t) => {- const lines = ['class Control {', 'init(context: Context) {', `if (${PROOF}) {`];- for (let i = 0; i < 40; i += 1) {- lines.push('this.handlers.push((item: Item) => {', ...Array(70).fill('consume(item);'), `${CALL};`, '});');- }- while (lines.length < 2997) lines.push('consume(null);');- lines.push('}', '}', '}');- const text = lines.join('\n');- assert.equal(lines.length, 3000);- const { elapsed, findings } = timedScan(text);- t.diagnostic(`control timing: ${elapsed.toFixed(3)} ms; 40 guarded calls`);- assert.ok(elapsed < CONTROL_SCAN_LIMIT_MS, `${elapsed.toFixed(3)} ms exceeds ${CONTROL_SCAN_LIMIT_MS} ms`);- assert.deepEqual(findings, []);+ // Calls and lines scale together, so a per-call rescan of the control grows with both.+ const build = (scale) => {+ const total = Math.round(3000 * scale);+ const lines = ['class Control {', 'init(context: Context) {', `if (${PROOF}) {`];+ for (let i = 0; i < Math.round(40 * scale); i += 1) {+ lines.push('this.handlers.push((item: Item) => {', ...Array(70).fill('consume(item);'), `${CALL};`, '});');+ }+ while (lines.length < total - 3) lines.push('consume(null);');+ lines.push('}', '}', '}');+ return lines.join('\n');+ };+ assert.equal(build(1).split('\n').length, 3000);+ assert.deepEqual(assertLinearGrowth(t, 'control', build, scanBoth), []);});const DEFAULT_CALLBACK = 'function render(cb = () => { if (true) { return 1; } }) { return cb(); }';@@ -1329,18 +1429,19 @@ test('Pages diagnostics index line locations instead of rescanning per call', (tassert.ok(findings.every((finding, i) => finding.code === 'PCF_PAGES_API' && finding.line === i + 1));});-for (const [name, text, feature] of [- ['10000 unmatched angles', 'const value = ' + 'a<'.repeat(10000), null],- ['8000 guard parentheses', `if (${'('.repeat(8000)}${PROOF}${')'.repeat(8000)}) { ${CALL}; }`, 'Device.captureImage'],- ['8000 nested for statements', FOR_CHAIN, null],+// The tests below scale their fixture and bound the growth (see assertLinearGrowth), so a slow+// or busy machine cannot fail them.++for (const [name, build, feature] of [+ ['10000 unmatched angles', (scale) => 'const value = ' + 'a<'.repeat(Math.round(10000 * scale)), null],+ ['8000 guard parentheses', (scale) => {+ const depth = Math.round(8000 * scale);+ return `if (${'('.repeat(depth)}${PROOF}${')'.repeat(depth)}) { ${CALL}; }`;+ }, 'Device.captureImage'],+ ['8000 nested for statements', (scale) => 'for(;;)'.repeat(Math.round(8000 * scale)) + 'consume(1);', null],]) {test(`Source analysis bounds ${name}`, (t) => {- const started = performance.now();- const findings = [...scanSource(FILE, text), ...findingsFor(text, feature)];- const elapsed = performance.now() - started;- t.diagnostic(`${name} timing: ${elapsed.toFixed(3)} ms`);- assert.ok(elapsed < PATHOLOGICAL_SCAN_LIMIT_MS, `${elapsed.toFixed(3)} ms exceeds ${PATHOLOGICAL_SCAN_LIMIT_MS} ms`);- assert.deepEqual(findings, []);+ assert.deepEqual(assertLinearGrowth(t, name, build, (text) => scanBoth(text, feature)), []);});}@@ -1460,14 +1561,9 @@ test('Pages unknown write targets expire only tracked roots inside the target',for (const [name, receiver] of [['distinct receiver names', (i) => `p${i}`], ['one shared receiver name', () => 'p']]) {test(`Source binding analysis bounds 2000 functions with ${name}`, (t) => {- const text = Array.from({ length: 2000 }, (_, i) =>+ const build = (scale) => Array.from({ length: Math.round(2000 * scale) }, (_, i) =>`function f${i}(${receiver(i)}) { ${receiver(i)}.context.webAPI.retrieveRecord(); }`).join('\n');- const started = performance.now();- const findings = [...scanSource(FILE, text), ...findingsFor(text, 'WebAPI', ['model'])];- const elapsed = performance.now() - started;- t.diagnostic(`${name} timing: ${elapsed.toFixed(3)} ms; ${Buffer.byteLength(text)} bytes`);- assert.ok(elapsed < PATHOLOGICAL_SCAN_LIMIT_MS, `${elapsed.toFixed(3)} ms exceeds ${PATHOLOGICAL_SCAN_LIMIT_MS} ms`);- assert.deepEqual(findings, []);+ assert.deepEqual(assertLinearGrowth(t, name, build, (text) => scanBoth(text, 'WebAPI', ['model'])), []);});}@@ -1584,8 +1680,8 @@ test('.ts angle-bracket types the gate cannot blank fall back fail closed', () =});test('Source analysis bounds a .ts control with many angle-bracket types', (t) => {- // Each blanked type costs one more lex of the whole file; a large control with 30 assertions- // must still finish well within the bound and keep its findings.+ // Each blanked type used to cost one more lex of the whole file; a large control with 30 assertions+ // must be lexed a bounded number of times and keep its findings.const lines = ['export class C {', ' public init(context: ComponentFramework.Context<IInputs>): void {'];for (let i = 0; i < 900; i += 1) {lines.push(i % 30 === 0@@ -1595,11 +1691,13 @@ test('Source analysis bounds a .ts control with many angle-bracket types', (t) =lines.push(` ${CALL};`, ' }', '}');const text = lines.join('\n');const started = performance.now();- const findings = findingsFor(text);+ const work = lexWork(() => counting.gate.featureCoherence({ features: [{ name: 'Device.captureImage' }] },+ [{ file: FILE, text }], ['pages']));const elapsed = performance.now() - started;- t.diagnostic(`.ts angle-type timing: ${elapsed.toFixed(3)} ms; ${Buffer.byteLength(text)} bytes`);- assert.ok(elapsed < PATHOLOGICAL_SCAN_LIMIT_MS, `${elapsed.toFixed(3)} ms exceeds ${PATHOLOGICAL_SCAN_LIMIT_MS} ms`);- assert.deepEqual(findings.map((finding) => [finding.code, finding.line]), [['PCF_PAGES_API', lines.length - 2]]);+ t.diagnostic(`.ts angle-type work: ${work.calls} lexer passes, ${work.chars} characters lexed of ${text.length}; ${elapsed.toFixed(3)} ms`);+ assertBoundedLexing('30 casts', text, work);+ assert.ok(elapsed < CATASTROPHE_LIMIT_MS, `${elapsed.toFixed(3)} ms exceeds ${CATASTROPHE_LIMIT_MS} ms`);+ assert.deepEqual(work.result.map((finding) => [finding.code, finding.line]), [['PCF_PAGES_API', lines.length - 2]]);});test('.ts files with hundreds of angle-bracket types stay analyzable', (t) => {@@ -1622,11 +1720,13 @@ test('.ts files with hundreds of angle-bracket types stay analyzable', (t) => {['a type longer than 4096 characters', `const shape = <${longType}>raw;\n${guarded}`],]) {const started = performance.now();- const gated = gateSources({ manifestModel: { features: [{ name: 'Device.captureImage' }] }, sources: [{ file: FILE, text }], hosts: ['pages'] });+ const work = lexWork(() => counting.gate.gateSources({ manifestModel: { features: [{ name: 'Device.captureImage' }] }, sources: [{ file: FILE, text }], hosts: ['pages'] }));const elapsed = performance.now() - started;- t.diagnostic(`${name}: ${elapsed.toFixed(3)} ms; ${Buffer.byteLength(text)} bytes`);+ const gated = work.result;+ t.diagnostic(`${name}: ${work.calls} lexer passes, ${work.chars} characters lexed of ${text.length}; ${elapsed.toFixed(3)} ms`);assert.deepEqual(gated, { ok: true, errors: [], warnings: [] }, name);- assert.ok(elapsed < PATHOLOGICAL_SCAN_LIMIT_MS, `${name}: ${elapsed.toFixed(3)} ms exceeds ${PATHOLOGICAL_SCAN_LIMIT_MS} ms`);+ assertBoundedLexing(name, text, work);+ assert.ok(elapsed < CATASTROPHE_LIMIT_MS, `${name}: ${elapsed.toFixed(3)} ms exceeds ${CATASTROPHE_LIMIT_MS} ms`);const unguarded = text.replace(guarded, `${CALL};`);const callLine = unguarded.split('\n').findIndex((line) => line.includes(CALL)) + 1;assert.deepEqual(findingsFor(unguarded).map((finding) => [finding.code, finding.line]), [['PCF_PAGES_API', callLine]], name);diff --git a/plugins/pcf/scripts/vendor/PROVENANCE.json b/plugins/pcf/scripts/vendor/PROVENANCE.jsonindex 8e3124815..a8c449117 100644--- a/plugins/pcf/scripts/vendor/PROVENANCE.json+++ b/plugins/pcf/scripts/vendor/PROVENANCE.json@@ -1,13 +1,13 @@{- "commit": "a3443479b88ec538be2e74293fa92230c4ef1aab",+ "commit": "59ae2d72e2a88da53f34430608d7afe3ee05503a","dirtySdkPackage": 0,- "libBuiltAt": "2026-10-20T20:18:04.982Z",- "newestSrcAt": "2026-10-20T19:21:12.668Z",+ "libBuiltAt": "2026-10-28T21:30:20.191Z",+ "newestSrcAt": "2026-10-28T21:07:03.627Z","libIsStale": false,"nostub": false,"esbuildVersion": "0.28.1","nodeVersion": "v24.21.0",- "builtAt": "2026-10-20T20:20:30.581Z",- "bundleSha256": "eebd70a2a7f6e12e45d18744640fd803479a738bc936b8e0dce1a9f97a0a4f8c",- "bundleBytes": 1029451+ "builtAt": "2026-10-28T21:31:21.536Z",+ "bundleSha256": "a7f59f9683114f30ed8252c1e84824bc81e282dc3b7fa2653153be2398125f3f",+ "bundleBytes": 1471508}diff --git a/plugins/pcf/scripts/vendor/cds-maker-sdk.cjs b/plugins/pcf/scripts/vendor/cds-maker-sdk.cjsindex 6f798fd8d..4669c311a 100644--- a/plugins/pcf/scripts/vendor/cds-maker-sdk.cjs+++ b/plugins/pcf/scripts/vendor/cds-maker-sdk.cjs@@ -25,61 +25,78 @@}globalThis.document=globalThis.document||globalThis.window.document;})();-var kU=Object.create;var Nc=Object.defineProperty;var LU=Object.getOwnPropertyDescriptor;var $U=Object.getOwnPropertyNames;var xU=Object.getPrototypeOf,FU=Object.prototype.hasOwnProperty;var L=(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)Nc(e,r,{get:t[r],enumerable:!0})},Sc=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of $U(t))!FU.call(e,i)&&i!==r&&Nc(e,i,{get:()=>t[i],enumerable:!(n=LU(t,i))||n.enumerable});return e},Yi=(e,t,r)=>(Sc(e,t,"default"),r&&Sc(r,t,"default")),Ae=(e,t,r)=>(r=e!=null?kU(xU(e)):{},Sc(t||!e||!e.__esModule?Nc(r,"default",{value:e,enumerable:!0}):r,e)),Br=e=>Sc(Nc({},"__esModule",{value:!0}),e);var Qi=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 ow;(function(e){e.None="None",e.UserOwned="UserOwned",e.TeamOwned="TeamOwned",e.BusinessOwned="BusinessOwned",e.OrganizationOwned="OrganizationOwned",e.BusinessParented="BusinessParented",e.Filtered="Filtered"})(ow||(T.OwnershipTypes=ow={}));var aw;(function(e){e.User="Microsoft.Dynamics.CRM.systemuser",e.Team="Microsoft.Dynamics.CRM.team"})(aw||(T.PrincipalType=aw={}));var sw;(function(e){e[e.DoNotDisplayInActivityMenus=0]="DoNotDisplayInActivityMenus",e[e.DisplayInActivityMenus=1]="DisplayInActivityMenus"})(sw||(T.ActivityTypeMask=sw={}));var lw;(function(e){e.Activity="Activity",e.Virtual="Virtual",e.Standard="Standard",e.Elastic="Elastic"})(lw||(T.TableTypes=lw={}));var uw;(function(e){e.Standard="Standard",e.Virtual="Virtual",e.Elastic="Elastic"})(uw||(T.TableTypeCode=uw={}));var cw;(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"})(cw||(T.FormType=cw={}));var dw;(function(e){e[e.ClassicForm=0]="ClassicForm",e[e.AirForm=1]="AirForm",e[e.ConvertedICForm=2]="ConvertedICForm"})(dw||(T.FormPresentation=dw={}));var fw;(function(e){e[e.Inactive=0]="Inactive",e[e.Active=1]="Active"})(fw||(T.ActivationState=fw={}));var pw;(function(e){e[e.String=0]="String",e[e.Number=1]="Number",e[e.Picklist=2]="Picklist"})(pw||(T.AttributeType=pw={}));var mw;(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"})(mw||(T.ViewType=mw={}));var hw;(function(e){e[e.ASPChart=0]="ASPChart",e[e.PowerBI=1]="PowerBI"})(hw||(T.ChartsType=hw={}));var gw;(function(e){e[e.DataAndInteractionCentric=0]="DataAndInteractionCentric",e[e.InteractionCentric=1]="InteractionCentric"})(gw||(T.ChartType=gw={}));var yw;(function(e){e[e.Published=0]="Published",e[e.Unpublished=1]="Unpublished",e[e.Deleted=2]="Deleted",e[e.DeletedUnpublished=3]="DeletedUnpublished"})(yw||(T.ComponentState=yw={}));var bw;(function(e){e[e.None=1]="None",e[e.Sandbox=2]="Sandbox",e[e.External=3]="External"})(bw||(T.PluginIsolationMode=bw={}));var vw;(function(e){e[e.BasicAuth=0]="BasicAuth"})(vw||(T.AuthType=vw={}));var ww;(function(e){e[e.Database=0]="Database",e[e.Disk=1]="Disk",e[e.Normal=2]="Normal",e[e.AzureWebApp=3]="AzureWebApp"})(ww||(T.PluginSourceType=ww={}));var Cw;(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"})(Cw||(T.AttributeTypeCode=Cw={}));var Ew;(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"})(Ew||(T.AttributeTypeName=Ew={}));var Aw;(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"})(Aw||(T.AttributeFormatCode=Aw={}));var Sw;(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"})(Sw||(T.AttributeFormatName=Sw={}));var Nw;(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"})(Nw||(T.AttributeTypeCodeNum=Nw={}));var _w;(function(e){e.Picklist="Picklist",e.State="State",e.Status="Status",e.Boolean="Boolean"})(_w||(T.OptionSetType=_w={}));var Tw;(function(e){e[e.Draft=0]="Draft",e[e.Activated=1]="Activated"})(Tw||(T.StateCode=Tw={}));var Dw;(function(e){e[e.Draft=1]="Draft",e[e.Activated=2]="Activated"})(Dw||(T.StatusCode=Dw={}));var Iw;(function(e){e[e.Enabled=0]="Enabled",e[e.Disabled=1]="Disabled"})(Iw||(T.StateCodeEnabledDisabled=Iw={}));var Ow;(function(e){e[e.Enabled=1]="Enabled",e[e.Disabled=2]="Disabled"})(Ow||(T.StatusCodeEnabledDisabled=Ow={}));var Pw;(function(e){e[e.Definition=1]="Definition",e[e.Activation=2]="Activation",e[e.Template=3]="Template"})(Pw||(T.WorkflowTypeCode=Pw={}));var Rw;(function(e){e[e.User=1]="User",e[e.BusinessUnit=2]="BusinessUnit",e[e.ParentChildBusinessUnit=3]="ParentChildBusinessUnit",e[e.Organization=4]="Organization"})(Rw||(T.WorkflowScope=Rw={}));var kw;(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"})(kw||(T.WorkflowCategory=kw={}));var Lw;(function(e){e[e.None=-1]="None",e[e.BusinessFlow=0]="BusinessFlow",e[e.TaskFlow=1]="TaskFlow"})(Lw||(T.BusinessProcessType=Lw={}));var $w;(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"})($w||(T.AppSubType=$w={}));var xw;(function(e){e.OneToManyRelationship="OneToManyRelationship",e.ManyToManyRelationship="ManyToManyRelationship"})(xw||(T.RelationshipType=xw={}));var Fw;(function(e){e.ManyToOneRelationship="ManyToOneRelationship",e.OneToManyRelationship="OneToManyRelationship",e.ManyToManyRelationship="ManyToManyRelationship"})(Fw||(T.RelationshipTypeExt=Fw={}));var Mw;(function(e){e.NoCascade="NoCascade",e.Cascade="Cascade",e.Active="Active",e.UserOwned="UserOwned",e.RemoveLink="RemoveLink",e.Restrict="Restrict"})(Mw||(T.CascadeType=Mw={}));var Uw;(function(e){e.None="None",e.Append="Append",e.ParentChild="ParentChild",e.Pointer="Pointer",e.Inheritance="Inheritance"})(Uw||(T.RelationshipSecurityTypes=Uw={}));var Bw;(function(e){e[e.Active=1]="Active",e[e.Inactive=2]="Inactive"})(Bw||(T.ViewStatusCode=Bw={}));var qw;(function(e){e[e.Active=0]="Active",e[e.Inactive=1]="Inactive"})(qw||(T.ViewStateCode=qw={}));var Vw;(function(e){e.Active="Active",e.Failed="Failed",e.InProgress="InProgress",e.Pending="Pending"})(Vw||(T.EntityKeyIndexStatus=Vw={}));var Gw;(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"})(Gw||(T.SolutionComponentTypeCode=Gw={}));var Ww;(function(e){e[e.IncludeSubcomponents=0]="IncludeSubcomponents",e[e.DoNotIncludeSubcomponents=1]="DoNotIncludeSubcomponents",e[e.IncludeAsShellOnly=2]="IncludeAsShellOnly"})(Ww||(T.RootComponentBehavior=Ww={}));var _c;(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"})(_c||(T.SolutionComponentTypeCodeExt=_c={}));var Tc;(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"})(Tc||(T.EntityTypeCode=Tc={}));var zw;(function(e){e.MultiSelectPicklist="MultiSelectPicklist",e.File="File",e.Image="Image"})(zw||(T.SolutionComponentVirtualAttributeSubtype=zw={}));function MU(e){let t=_c[e];return Tc[t]}T.SolutionComponentTypeCodeToEntityTypeCodeExt=MU;function UU(e){let t=Tc[e];return _c[t]}T.SolutionEntityTypeCodeExtToComponentTypeCode=UU;var jw;(function(e){e.Active="Active",e.Auto="Auto",e.Disabled="Disabled",e.Inactive="Inactive"})(jw||(T.ImeMode=jw={}));var Hw;(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"})(Hw||(T.SourceType=Hw={}));var Kw;(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"})(Kw||(T.StringFormatName=Kw={}));var Jw;(function(e){e[e.PrecisionProperty=0]="PrecisionProperty",e[e.Organization=1]="Organization",e[e.TransactionCurrency=2]="TransactionCurrency"})(Jw||(T.PrecisionSource=Jw={}));var Yw;(function(e){e.UserLocal="UserLocal",e.DateOnly="DateOnly",e.TimeZoneIndependent="TimeZoneIndependent"})(Yw||(T.DateTimeBehavior=Yw={}));var Qw;(function(e){e.DateOnly="DateOnly",e.DateAndTime="DateAndTime"})(Qw||(T.DateTimeFormat=Qw={}));var Xw;(function(e){e.None="None",e.Duration="Duration",e.TimeZone="TimeZone",e.Language="Language",e.Locale="Locale"})(Xw||(T.IntegerFormat=Xw={}));var Zw;(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"})(Zw||(T.WebResourceTypeCode=Zw={}));var eC;(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"})(eC||(T.SdkMessageProcessingStage=eC={}));var tC;(function(e){e[e.ServerOnly=0]="ServerOnly",e[e.OutlookClientOnly=1]="OutlookClientOnly",e[e.Both=2]="Both"})(tC||(T.SupportedDeployment=tC={}));var rC;(function(e){e[e.Synchronous=0]="Synchronous",e[e.Asynchronous=1]="Asynchronous"})(rC||(T.SdkMessageProcessingMode=rC={}));var nC;(function(e){e[e.ReportingServicesReport=1]="ReportingServicesReport",e[e.OtherReport=2]="OtherReport",e[e.LinkedReport=3]="LinkedReport"})(nC||(T.ReportTypeCode=nC={}));var iC;(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"})(iC||(T.ConnectionRoleCategory=iC={}));var oC;(function(e){e[e.Name=1]="Name",e[e.Address=2]="Address"})(oC||(T.ServiceNamespaceFormat=oC={}));var aC;(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"})(aC||(T.ServiceEndpointContract=aC={}));var sC;(function(e){e[e.Normal=1]="Normal",e[e.Federated=2]="Federated"})(sC||(T.ServiceEndpointConnectionMode=sC={}));var lC;(function(e){e.CannotDeleteInUseComponent="0x8004f01f",e.CannotDeleteInUseAttribute="0x80048418",e.CannotDeleteInUseOptionSet="0x80048417",e.CannotDeleteInUseEntity="0x80048420",e.CannotUninstallWithDependencies="0x8004F01D"})(lC||(T.DeleteDependencyErrorCode=lC={}));var uC;(function(e){e.SystemAdministrator="627090FF-40A3-4053-8790-584EDC5BE201",e.SystemCustomizer="119F245C-3CC8-4B62-B31C-D1A046CED15D"})(uC||(T.DefaultRoleTemplates=uC={}));var cC;(function(e){e[e.DefaultTeamPrivilege=0]="DefaultTeamPrivilege",e[e.DirectUserAndTeamPrivilege=1]="DirectUserAndTeamPrivilege"})(cC||(T.RoleInheritance=cC={}));var dC;(function(e){e[e.NotSpecified=0]="NotSpecified",e[e.CustomConnector=1]="CustomConnector"})(dC||(T.ConnectorTypeEnum=dC={}));var fC;(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"})(fC||(T.EnvironmentVariableDefinitionTypeEnum=fC={}));var pC;(function(e){e[e.Owner=0]="Owner",e[e.Access=1]="Access",e[e.AADSecurityGroup=2]="AADSecurityGroup",e[e.AADOfficeGroup=3]="AADOfficeGroup"})(pC||(T.TeamTypeEnum=pC={}));var mC;(function(e){e.Bots="bots"})(mC||(T.KnownCustomSolutionComponentEntitySetName=mC={}));var hC;(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"})(hC||(T.QueryType=hC={}))});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.WebResourceUnverifiedError=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 dt=class extends Error{constructor(t,r){super(r),this.code=t,Object.setPrototypeOf(this,new.target.prototype),this.name=new.target.name}};X.SdkError=dt;var gC=Symbol.for("cds-maker-sdk.partialWriteTokens");function BU(e,t){return typeof e=="object"&&e!==null&&(e[gC]=t),e}X.withPartialTokens=BU;function qU(e){return Dm(e,gC)}X.readPartialTokens=qU;function Dm(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 yC=Symbol.for("cds-maker-sdk.partialDefaultViewEnrichment");function VU(e,t){return typeof e=="object"&&e!==null&&(e[yC]=t),e}X.withPartialEnrichment=VU;function GU(e){return Dm(e,yC)}X.readPartialEnrichment=GU;var dm=Symbol.for("cds-maker-sdk.cleanupWarnings");function WU(e,t){if(typeof e=="object"&&e!==null&&t.length>0){let r=e,n=r[dm];r[dm]=[...Array.isArray(n)?n:[],...t]}return e}X.withCleanupWarnings=WU;function zU(e){let t=Dm(e,dm);return t?[...t]:void 0}X.readCleanupWarnings=zU;var fm=class extends dt{constructor(t,r){super("ARTIFACT_NOT_FOUND",`Artifact ${t}/${r} not found in workspace`),this.type=t,this.id=r}};X.ArtifactNotFoundError=fm;var pm=class extends dt{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=pm;var mm=class extends dt{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=mm;var hm=class extends dt{constructor(t){super("INVALID_ARGUMENT",t)}};X.InvalidArgumentError=hm;var gm=class extends dt{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=gm;var ym=class extends dt{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=ym;var bm=class extends dt{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=bm;var vm=class extends dt{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=vm;var wm=class extends dt{constructor(t,r,n){super("WEB_RESOURCE_UNVERIFIED",n),this.id=t,this.webResourceName=r}};X.WebResourceUnverifiedError=wm;function jU(e,t){return typeof e=="object"&&e!==null&&Object.defineProperty(e,"cause",{value:t,enumerable:!1,writable:!0,configurable:!0}),e}X.attachCause=jU;var Cm=class extends dt{constructor(t){super("WORKSPACE_NOT_INITIALIZED",`Workspace not initialized at ${t}. Call initWorkspace() first.`),this.workspacePath=t}};X.WorkspaceNotInitializedError=Cm;var Em=class extends dt{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=Em;var Am=class extends dt{constructor(t,r){super("NOT_IMPLEMENTED",`Operation '${t}' is not implemented yet${r?`: ${r}`:""}.`),this.operation=t}};X.NotImplementedError=Am;var Sm=class extends dt{constructor(t,r){super("INVALID_JSON_POINTER",`Invalid JSON Pointer '${t}': ${r}`),this.pointer=t}};X.JsonPointerError=Sm;var Nm=class extends dt{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=Nm;var _m=class extends dt{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=_m;var Tm=class extends dt{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=Tm});var le=v(nt=>{"use strict";Object.defineProperty(nt,"__esModule",{value:!0});nt.odataQuery=nt.normalizeGuid=nt.createSafeXmlElement=nt.assertNoControlChars=nt.assertODataName=nt.assertXmlName=nt.xmlText=nt.odataPathLiteral=nt.odataLiteral=void 0;var Dc=Q();function bC(e){return String(e??"").replace(/'/g,"''")}nt.odataLiteral=bC;function HU(e){return encodeURIComponent(bC(e))}nt.odataPathLiteral=HU;function KU(e){return String(e??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}nt.xmlText=KU;function vC(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 Dc.InvalidArgumentError(`${t} must be a valid XML element name (got '${e}')`);return e}nt.assertXmlName=vC;function JU(e,t){let r=String(e??"");if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(r))throw new Dc.InvalidArgumentError(`${t} must be a valid OData identifier (letters, digits, underscore): got '${e}'`);return e}nt.assertODataName=JU;function YU(e,t){if(/[\u0000-\u001F\u007F]/.test(String(e??"")))throw new Dc.InvalidArgumentError(`${t} must not contain control characters (including CR/LF): they would inject additional lines into the request`);return e}nt.assertNoControlChars=YU;function QU(e,t,r){return e.createElement(vC(t,r))}nt.createSafeXmlElement=QU;var XU=/^[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 ZU(e,t){let r=String(e??""),n=r.length===38&&r.startsWith("{")&&r.endsWith("}")?r.slice(1,-1):r;if(!XU.test(n))throw new Dc.InvalidArgumentError(`${t} must be a valid GUID (got '${e}')`);return n.toLowerCase()}nt.normalizeGuid=ZU;function eB(e){let t=[];for(let[r,n]of e)n!=null&&n!==""&&t.push(`${r}=${encodeURIComponent(String(n))}`);return t.length>0?`?${t.join("&")}`:""}nt.odataQuery=eB});var ye=v(z=>{"use strict";Object.defineProperty(z,"__esModule",{value:!0});z.nowIso=z.isAlreadyDeleted=z.deleteRecord=z.resendAppSearchIndexRace=z.resendDeadlockVictim=z.resendWhile=z.isAppSearchIndexRace=z.namesAppSearchIndexRace=z.isTransactionNotStarted=z.TRANSACTION_NOT_STARTED_CODE=z.LOCK_BACKOFF_MS=z.isConcurrencyLockRefusalError=z.isConcurrencyLockRefusal=z.CONCURRENCY_LOCK_CODE=z.AMBIGUOUS_WRITE_STATUSES=z.DEADLOCK_BACKOFF_MS=z.isSqlDeadlockVictim=z.ensureSuccess=z.resolveCreatedId=z.requireCreatedId=z.withClientMintedId=z.readCreatedId=z.readRowEtag=z.readEtag=z.requireEtag=z.isVersionToken=z.echoWrite=z.UPDATE_NO_ETAG_CODE=z.VERSION_CONFLICT_CODE=void 0;var ko=Q(),$a=le();z.VERSION_CONFLICT_CODE="VERSION_CONFLICT";z.UPDATE_NO_ETAG_CODE="ARTIFACT_UPDATE_NO_ETAG";function tB(e,t){return{query:`?$select=${encodeURIComponent(e)}`,options:{headers:{...t??{},Prefer:"return=representation"}}}}z.echoWrite=tB;function wC(e){return typeof e=="string"&&e.trim()!==""&&e.trim()!=="*"}z.isVersionToken=wC;function rB(e,t,r){if(!wC(e))throw new ko.SdkError(z.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}z.requireEtag=rB;function CC(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}z.readEtag=CC;async function nB(e,t,r,n){let i=`/${t}(${n})${(0,$a.odataQuery)([["$select",r]])}`;return CC(Om(await e.get(i),e.apiUrl(i)))}z.readRowEtag=nB;function Im(e,t){var r;let n=e.body;if(n&&typeof n[t]=="string")return(0,$a.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,$a.normalizeGuid)(a[1],t)}return null}z.readCreatedId=Im;function iB(e,t,r){return r?{...e,[t]:(0,$a.normalizeGuid)(r,t)}:e}z.withClientMintedId=iB;function oB(e,t,r){let n=Im(e,t);if(!n)throw new ko.InvalidArgumentError(`Dataverse did not return an id for the created ${r}`);return n}z.requireCreatedId=oB;function aB(e,t,r,n){let i=Im(e,t);if(i)return i;if(n)return(0,$a.normalizeGuid)(n,t);throw new ko.InvalidArgumentError(`Dataverse did not return an id for the created ${r}`)}z.resolveCreatedId=aB;function Om(e,t){if(e.status===412)throw new ko.SdkError(z.VERSION_CONFLICT_CODE,`Version conflict (412) from ${t}`);if(e.status<200||e.status>=300)throw new ko.ConnectionError(t,e.status,fB(e.body),e.body);return e}z.ensureSuccess=Om;function EC(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)}z.isSqlDeadlockVictim=EC;z.DEADLOCK_BACKOFF_MS=[1e3,2e3,4e3];z.AMBIGUOUS_WRITE_STATUSES=new Set([408,502,503,504]);z.CONCURRENCY_LOCK_CODE="0x80071151";function AC(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()===z.CONCURRENCY_LOCK_CODE}z.isConcurrencyLockRefusal=AC;function sB(e){return e instanceof ko.ConnectionError&&e.statusCode===429&&AC({status:429,headers:{},body:e.cause})}z.isConcurrencyLockRefusalError=sB;z.LOCK_BACKOFF_MS=[2e3,3e3,...Array.from({length:35},()=>5e3)];z.TRANSACTION_NOT_STARTED_CODE="0x80040251";function lB(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()===z.TRANSACTION_NOT_STARTED_CODE}z.isTransactionNotStarted=lB;var uB=/(?:^|[^a-z0-9_])AppModule_DVTableSearch_M365AppModuleId(?![a-z0-9_])/i;function SC(e){return uB.test(e)&&/\bSql Number:\s*547\b/i.test(e)}z.namesAppSearchIndexRace=SC;function NC(e){return e.status!==400||e.body===void 0||e.body===null?!1:SC(typeof e.body=="string"?e.body:JSON.stringify(e.body))}z.isAppSearchIndexRace=NC;async function Pm(e,t,r=z.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]))}}z.resendWhile=Pm;function cB(e){return Pm(EC,e,z.DEADLOCK_BACKOFF_MS)}z.resendDeadlockVictim=cB;function dB(e){return Pm(NC,e,z.DEADLOCK_BACKOFF_MS)}z.resendAppSearchIndexRace=dB;function fB(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 pB(e,t,r,n){let i=(0,$a.normalizeGuid)(r,"id"),o=`/${t}(${i})`;Om(await e.delete(o,n?{headers:{"If-Match":n}}:void 0),e.apiUrl(o))}z.deleteRecord=pB;function mB(e){return e instanceof ko.ConnectionError&&e.statusCode===404}z.isAlreadyDeleted=mB;function hB(){return new Date().toISOString()}z.nowIso=hB});var Lt=v(xa=>{"use strict";Object.defineProperty(xa,"__esModule",{value:!0});xa.describeMalformedValue=xa.collectPages=void 0;var _C=ye(),Rm=Q();async function gB(e,t,r,n,i){let o=[],a=new Set,s=e.apiUrl(t),l=(0,_C.ensureSuccess)(await e.get(t,i),s);for(n?.(l);;){let u=l.body,c=u?.value;if(!Array.isArray(c))throw new Rm.ConnectionError(s,l.status,`${r}: paginated read returned a malformed page \u2014 expected an OData 'value' array but got ${km(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 Rm.ConnectionError(s,l.status,`${r}: paginated read returned a malformed @odata.nextLink (${km(d)}); cannot follow it, and refusing to return partial results.`);if(a.has(d))throw new Rm.InvalidArgumentError(`${r}: aborting pagination \u2014 the server returned a repeated @odata.nextLink ('${d}'), which would loop indefinitely.`);a.add(d),s=d,l=(0,_C.ensureSuccess)(await e.getAbsolute(d,i),d)}return o}xa.collectPages=gB;function km(e){return e===null?"null":e===void 0?"undefined (missing)":`a ${typeof e}`}xa.describeMalformedValue=km});var Lm=v($o=>{"use strict";Object.defineProperty($o,"__esModule",{value:!0});$o.assertWorkflowKind=$o.WORKFLOW_KIND_MISMATCH_CODE=void 0;var Lo=Qi(),yB=Q(),TC=ye(),bB=le();$o.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 vB(e,t,r){var n,i;let o=`/workflows(${t})${(0,bB.odataQuery)([["$select","category"]])}`,a=await e.get(o);if(a.status===404)return null;(0,TC.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 yB.SdkError($o.WORKFLOW_KIND_MISMATCH_CODE,`Refusing to delete workflow '${t}' as a ${DC[r]}: it is ${u}. Nothing was changed. Check the id.`)}return(0,TC.readEtag)(a)}$o.assertWorkflowKind=vB});var xm=v(Yr=>{"use strict";Object.defineProperty(Yr,"__esModule",{value:!0});Yr.deleteWorkflowResending=Yr.isWorkflowDeleteUnsettled=Yr.failedAfterResend=Yr.WORKFLOW_DELETE_UNSETTLED_CODE=void 0;var bl=Q(),hi=ye(),OC=le();Yr.WORKFLOW_DELETE_UNSETTLED_CODE="WORKFLOW_DELETE_UNSETTLED";var PC=new WeakSet;function $m(e){return typeof e=="object"&&e!==null&&PC.add(e),e}function wB(e){return typeof e=="object"&&e!==null&&PC.has(e)}Yr.failedAfterResend=wB;function CB(e){return e instanceof bl.SdkError&&e.code===Yr.WORKFLOW_DELETE_UNSETTLED_CODE}Yr.isWorkflowDeleteUnsettled=CB;function EB(e,t){try{(0,hi.ensureSuccess)(e,t)}catch(r){return r}}function AB(e){return(0,hi.isSqlDeadlockVictim)(e)?"lost a SQL deadlock (HTTP 500, Sql Number 1205)":`lost its transaction (HTTP 500 ${hi.TRANSACTION_NOT_STARTED_CODE})`}async function IC(e,t){try{return(await e.get(`/workflows(${t})${(0,OC.odataQuery)([["$select","workflowid"]])}`)).status===404}catch{return!1}}async function SB(e,t,{bindingToken:r,kindName:n,deactivated:i=!1,resendDeadlockVictim:o=!1,ifMatchOnFirst:a=!1}){let s=(0,OC.normalizeGuid)(t,"id");if(a&&!r)throw new bl.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,hi.isTransactionNotStarted)(p)||o&&(0,hi.isSqlDeadlockVictim)(p),d=0,f,m;try{m=await(0,hi.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?hi.DEADLOCK_BACKOFF_MS:[])}catch(p){if(p instanceof bl.ConnectionError&&p.statusCode===0&&r&&await IC(e,s))return;throw d>1?$m(p):p}if(!(d>1&&m.status===404)){if(d>1&&m.status===412){let p=AB(f),h=new bl.SdkError(Yr.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 $m((0,bl.attachCause)(h,EB(f,u)))}if(!(r&&hi.AMBIGUOUS_WRITE_STATUSES.has(m.status)&&await IC(e,s)))try{(0,hi.ensureSuccess)(m,u)}catch(p){throw d>1?$m(p):p}}}Yr.deleteWorkflowResending=SB});var Fm=v(Bn=>{"use strict";Object.defineProperty(Bn,"__esModule",{value:!0});Bn.businessRuleApi=Bn.BUSINESS_RULE_LEFT_DEACTIVATED_CODE=Bn.WFOM_API_UNAVAILABLE_CODE=void 0;var Un=Qi(),NB=Lt(),_B=Lm(),TB=xm(),Gt=ye(),gi=le(),Oc=Q();Bn.WFOM_API_UNAVAILABLE_CODE="BUSINESS_RULE_API_UNAVAILABLE";Bn.BUSINESS_RULE_LEFT_DEACTIVATED_CODE="BUSINESS_RULE_LEFT_DEACTIVATED";async function RC(e,t,r,n){let i=`/workflows(${OB})/Microsoft.Dynamics.CRM.${t}`;try{return(0,Gt.ensureSuccess)(await e.post(i,{Entity:r.Entity,WfomJson:r.WfomJson},{headers:n}),e.apiUrl(i))}catch(o){throw o?.statusCode!==404?o:new Oc.SdkError(Bn.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 DB(e,t){let r=`/workflows(${t})${(0,gi.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,Gt.readEtag)(n),statecode:typeof i?.statecode=="number"?i.statecode:null,statuscode:typeof i?.statuscode=="number"?i.statuscode:null}}catch{return null}}async function IB(e,t,r){let n=await DB(e,t);if(n===null||n.etag===null)throw new Oc.SdkError(Gt.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 Oc.SdkError(Gt.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 OB="00000000-0000-0000-0000-000000000000",Ic={"Content-Type":"application/json",Accept:"application/json","OData-Version":"4.0","OData-MaxVersion":"4.0"},PB="workflowid,name,description,primaryentity,statecode,category,type",RB="category eq 2 and type eq 1";async function kC(e,t,r){var n;if(r==="Draft")return null;let i=(0,gi.normalizeGuid)(t,"workflowid"),o=r==="Active",a={statecode:o?Un.StateCode.Activated:Un.StateCode.Draft,statuscode:o?Un.StatusCode.Activated:Un.StatusCode.Draft},s=`/workflows(${i})`,l=(0,Gt.ensureSuccess)(await e.patch(s,a,{headers:Ic}),e.apiUrl(s));return(n=(0,Gt.readEtag)(l))!==null&&n!==void 0?n:await vl(e,i)}async function vl(e,t){let r=`/workflows(${t})${(0,gi.odataQuery)([["$select","workflowid"]])}`;try{let n=await e.get(r);return n.status>=200&&n.status<300?(0,Gt.readEtag)(n):null}catch{return null}}async function kB(e,t,r){let n=await vl(e,t),i=await r(),o=(0,Gt.readEtag)(i);if(o)return{response:i,etag:o};let a=await vl(e,t);return{response:i,etag:n!==null&&n===a?a:null}}Bn.businessRuleApi={async get(e,t){let r=(0,gi.normalizeGuid)(t,"id"),n=`/workflows(${r})/Microsoft.Dynamics.CRM.RetrieveProcessWithWfomJson`,{response:i,etag:o}=await kB(e,r,async()=>(0,Gt.ensureSuccess)(await e.get(n),e.apiUrl(n)));return{raw:i.body,etag:o}},async list(e,t){let r=[RB];t?.entityLogicalName&&r.push(`primaryentity eq '${(0,gi.odataLiteral)(t.entityLogicalName)}'`);let n=`/workflows${(0,gi.odataQuery)([["$select",PB],["$filter",r.join(" and ")]])}`;return(await(0,NB.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,gi.normalizeGuid)(n.Entity.workflowid,"workflowid"),o=await RC(e,"CreateProcessWithWfomJson",n,Ic),a=(0,Gt.resolveCreatedId)(o,"workflowid","business rule",i),s=null;try{s=await kC(e,a,n.status)}catch(l){try{await(0,Gt.deleteRecord)(e,"workflows",a)}catch{}throw l}return{id:a,etag:(r=s??(0,Gt.readEtag)(o))!==null&&r!==void 0?r:await vl(e,a)}},async update(e,t,r,n){var i,o;let a=r,s=(0,gi.normalizeGuid)(t,"id"),l=`/workflows(${s})`,u={...Ic,"If-Match":(0,Gt.requireEtag)(n,"business rule",s)},c=await IB(e,s,u["If-Match"]),d=c.statecode===Un.StateCode.Activated;d&&(0,Gt.ensureSuccess)(await e.patch(l,{statecode:Un.StateCode.Draft,statuscode:Un.StatusCode.Draft},{headers:u}),e.apiUrl(l));let f;try{f=await RC(e,"UpdateProcessWithWfomJson",a,u)}catch(p){if(d)try{(0,Gt.ensureSuccess)(await e.patch(l,{statecode:Un.StateCode.Activated,statuscode:(i=c.statuscode)!==null&&i!==void 0?i:Un.StatusCode.Activated},{headers:Ic}),e.apiUrl(l))}catch(h){throw new Oc.SdkError(Bn.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 kC(e,s,a.status);return{id:s,etag:(o=m??(0,Gt.readEtag)(f))!==null&&o!==void 0?o:await vl(e,s)}},async delete(e,t){let r=(0,gi.normalizeGuid)(t,"id"),n=await(0,_B.assertWorkflowKind)(e,r,Un.WorkflowCategory.BusinessRule);return(0,TB.deleteWorkflowResending)(e,r,{bindingToken:n,kindName:"business rule"})}}});var Qr=v(Et=>{"use strict";Object.defineProperty(Et,"__esModule",{value:!0});Et.publishBoundEntity=Et.boundEntityPublishScope=Et.publishGenPageById=Et.publishDashboardById=Et.publishWebResourceById=Et.publishEntity=Et.publishAppModule=Et.publishXml=void 0;var LC=ye(),wl=le(),$C="/PublishXml";async function Fa(e,t){(0,LC.ensureSuccess)(await(0,LC.resendDeadlockVictim)(()=>e.post($C,{ParameterXml:t})),e.apiUrl($C))}Et.publishXml=Fa;function LB(e,t){return Fa(e,`<importexportxml><appmodules><appmodule>${(0,wl.xmlText)(t)}</appmodule></appmodules></importexportxml>`)}Et.publishAppModule=LB;function xC(e,t){return Fa(e,`<importexportxml><entities><entity>${(0,wl.xmlText)(t)}</entity></entities></importexportxml>`)}Et.publishEntity=xC;function $B(e,t){return Fa(e,`<importexportxml><webresources><webresource>${(0,wl.xmlText)(t)}</webresource></webresources></importexportxml>`)}Et.publishWebResourceById=$B;function xB(e,t){return Fa(e,`<importexportxml><dashboards><dashboard>${(0,wl.xmlText)(t)}</dashboard></dashboards></importexportxml>`)}Et.publishDashboardById=xB;function FB(e,t){return Fa(e,`<importexportxml><uxagentprojects><uxagentproject>${(0,wl.xmlText)(t)}</uxagentproject></uxagentprojects></importexportxml>`)}Et.publishGenPageById=FB;function MB(e){let t=e?.entityLogicalName;return t?{envelope:"entity",entityLogicalName:t,blastRadiusWarning:"ENTITY_ENVELOPE_ALSO_SHIPS_UNRELATED_UNPUBLISHED_CHANGES"}:{envelope:"entity"}}Et.boundEntityPublishScope=MB;function UB(e,t){let r=t?.entityLogicalName;return r?xC(e,r):Promise.resolve()}Et.publishBoundEntity=UB});var Ma=v(Rc=>{"use strict";Object.defineProperty(Rc,"__esModule",{value:!0});Rc.JsonPointer=void 0;var qr=Q(),Pc=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 qr.JsonPointerError(t,'non-empty pointers must start with "/"');return t.substring(1).split("/").map(r=>{if(/~(?![01])/.test(r))throw new qr.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 qr.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 qr.JsonPointerError(r,`'${a}' is not a valid array index`);if(s>o.length)throw new qr.JsonPointerError(r,`array index '${a}' is out of range`);o[s]=n}else{if(e.isReservedToken(a))throw new qr.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 qr.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 qr.JsonPointerError(r,`array index '${o}' is out of range`);i.splice(a,1)}else{if(e.isReservedToken(o))throw new qr.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 qr.JsonPointerError(r,"add target must be an array");u.push(n);return}let a=e.resolve(t,r);if(!Array.isArray(a))throw new qr.JsonPointerError(r,"add target must be an array");let s=i===void 0?a.length:i;if(s<0||s>a.length)throw new qr.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 qr.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)}};Rc.JsonPointer=Pc;Pc.RESERVED_TOKENS=new Set(["__proto__","prototype","constructor"])});var MC=v(kc=>{"use strict";Object.defineProperty(kc,"__esModule",{value:!0});kc.findElements=void 0;var FC=Ma();function BB(e,t){let r=[];return Mm(e,"",t,r),r}kc.findElements=BB;function Mm(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)=>{Mm(i,FC.JsonPointer.append(t,o),r,n)});else for(let i of Object.keys(e))Mm(e[i],FC.JsonPointer.append(t,i),r,n)}});var Um=v(qn=>{"use strict";Object.defineProperty(qn,"__esModule",{value:!0});qn.assertMutationResult=qn.assertExistsResult=qn.assertReadResult=qn.assertStorageContract=void 0;var qB=["readText","writeTextAtomic","deleteFile","deleteByPrefix"],VB=["ensureContainer","exists"];function GB(e){if(typeof e!="object"||e===null)throw new Error("workspaceStorage must be an object implementing WorkspaceStorage.");for(let t of qB)if(typeof e[t]!="function")throw new Error(`workspaceStorage is missing the required method '${t}'.`);for(let t of VB){let r=e[t];if(r!==void 0&&typeof r!="function")throw new Error(`workspaceStorage.${t} must be a function when present.`)}return e}qn.assertStorageContract=GB;function WB(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.`)}qn.assertReadResult=WB;function zB(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.`)}qn.assertExistsResult=zB;function jB(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.`)}qn.assertMutationResult=jB});var Bm=v(Ua=>{"use strict";Object.defineProperty(Ua,"__esModule",{value:!0});Ua.retryTransientIoAsync=Ua.retryTransientIo=void 0;var HB=new Set(["EPERM","EACCES","EBUSY","UNKNOWN"]),KB=5,UC=10;function JB(e){for(let t=1;;t+=1)try{return e()}catch(r){if(!BC(r,t))throw r;QB(UC*t)}}Ua.retryTransientIo=JB;async function YB(e){for(let t=1;;t+=1)try{return await e()}catch(r){if(!BC(r,t))throw r;await new Promise(n=>setTimeout(n,UC*t))}}Ua.retryTransientIoAsync=YB;function BC(e,t){let r=e.code;return t<KB&&!!r&&HB.has(r)}function QB(e){try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)}catch{let t=Date.now()+e;for(;Date.now()<t;);}}});var zC=v(Vr=>{"use strict";Object.defineProperty(Vr,"__esModule",{value:!0});Vr.canonicalArtifactId=Vr.WorkspaceManager=Vr.WORKSPACE_SCHEMA_VERSION=Vr.retryTransientIo=void 0;var Wt=Um(),Vn=Q(),XB=Bm();Object.defineProperty(Vr,"retryTransientIo",{enumerable:!0,get:function(){return XB.retryTransientIo}});function qC(e){let t=e;return typeof t.pathFor=="function"&&typeof t.getRoot=="function"?e:null}Vr.WORKSPACE_SCHEMA_VERSION=1;var Xi={form:"forms",view:"views",businessRule:"business-rules",app:"apps",command:"commands",chart:"charts",dashboard:"dashboards",genPage:"gen-pages",bpf:"business-process-flows"},ZB="manifest.json",Ba=".metadata",qm="entities";function VC(e){try{return Promise.resolve(e())}catch(t){return Promise.reject(t)}}function Vm(e){if(e.schemaVersion!==void 0&&e.schemaVersion>Vr.WORKSPACE_SCHEMA_VERSION)throw new Vn.IncompatibleWorkspaceError(e.schemaVersion,Vr.WORKSPACE_SCHEMA_VERSION)}function GC(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Lc(e){return e.trim().toLowerCase().replace(/\/+$/,"")}var Gm=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),[Xi[t],`${Cl(r)}.json`]}metaKey(t,r){return this.assertSafeId(r),[Ba,Xi[t],`${Cl(r)}.meta.json`]}entityKey(t){return this.assertSafeId(t),[Ba,qm,`${t.toLowerCase()}.json`]}fsStore(){let t=qC(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=qC(this.storage);return t?t.getRoot():this.workspaceLabel}getArtifactDir(t){return this.fsStore().pathFor([Xi[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 Vn.PathTraversalError(String(t),this.workspaceLabel)}get manifestKey(){return[ZB]}assertDataKey(t,r){if(!Array.isArray(t)||t.length<2)throw new Vn.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,Wt.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=[[Ba,qm]];for(let i of Object.keys(Xi))r.push([Xi[i]],[Ba,Xi[i]]);let n=await Promise.allSettled(r.map(i=>VC(()=>t(i))));for(let i of n){if(i.status==="rejected")throw i.reason;(0,Wt.assertMutationResult)(i.value,"ensureContainer")}}async isInitialized(){return this.storage.exists?(0,Wt.assertExistsResult)(await this.storage.exists(this.manifestKey),"manifest.json"):(0,Wt.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 Vn.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 Vn.WorkspaceNotInitializedError(this.workspaceLabel);this.assertBoundHere(t.value),this.bound=!0}assertBoundHere(t){if(!GC(t))throw new Vn.WorkspaceOrgMismatchError("",this.instanceUrl);Vm(t);let r=typeof t.instanceUrl=="string"?t.instanceUrl.trim():"",n=Lc(r);if(!n||n!==Lc(this.instanceUrl))throw new Vn.WorkspaceOrgMismatchError(r,this.instanceUrl)}async clean(){let t=await this.readStoredManifest();if(!t.present||!GC(t.value))throw new Vn.WorkspaceNotInitializedError(this.workspaceLabel);let r=t.value;Vm(r);let n=Object.keys(Xi).map(o=>[Xi[o]]);n.push([Ba]);let i=await Promise.allSettled(n.map(o=>VC(()=>this.storage.deleteByPrefix(o))));for(let o of i){if(o.status==="rejected")throw o.reason;(0,Wt.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,Wt.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=WC(n);if(i!==void 0&&o===i){await this.upsertManifestEntry(t,r,n,{unlessCurrent:!0});return}(0,Wt.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,Wt.assertMutationResult)(await this.storage.deleteFile(this.artifactKey(t,r)),"deleteFile"),(0,Wt.assertMutationResult)(await this.storage.deleteFile(this.metaKey(t,r)),"deleteFile");let n=Cl(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,Wt.assertMutationResult)(await this.storage.deleteByPrefix([Ba,qm]),"deleteByPrefix");return}(0,Wt.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 Vn.WorkspaceNotInitializedError(this.workspaceLabel);return Vm(t),t}async writeManifest(t){await this.writeJsonUnchecked(this.manifestKey,{...t,schemaVersion:Vr.WORKSPACE_SCHEMA_VERSION})}async updateManifest(t){await this.withManifest(async()=>{let r=await this.getManifest();if(t.instanceUrl!==void 0&&Lc(String(t.instanceUrl))!==Lc(r.instanceUrl))throw new Vn.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=Cl(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,Wt.assertMutationResult)(await this.storage.deleteFile(t),"deleteFile")}async exists(t){return await this.ensureBound(),this.storage.exists?(0,Wt.assertExistsResult)(await this.storage.exists(t),t.join("/")):(0,Wt.assertReadResult)(await this.storage.readText(t),t.join("/"))!==null}async readJsonUnchecked(t){let r=(0,Wt.assertReadResult)(await this.storage.readText(t),t.join("/"));return r===null?null:JSON.parse(r)}async writeJsonUnchecked(t,r){(0,Wt.assertMutationResult)(await this.storage.writeTextAtomic(t,WC(r)),"writeTextAtomic")}};Vr.WorkspaceManager=Gm;function WC(e){return`${JSON.stringify(e,null,2)}-`}function Cl(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()}Vr.canonicalArtifactId=Cl});var Wm=v(qa=>{"use strict";Object.defineProperty(qa,"__esModule",{value:!0});qa.deepEqual=qa.deepDiff=void 0;var eq=Ma();function tq(e,t){let r=[];return HC(e,t,"",r,0),r}qa.deepDiff=tq;var $c=Symbol("missing"),xc=512;function HC(e,t,r,n,i){if(e===t)return;if(i>xc)throw new RangeError(`deepDiff exceeded the maximum supported depth of ${xc}`);let o=Fc(e),a=Fc(t);if(o&&a&&Array.isArray(e)===Array.isArray(t)){let s=rq(e,t);for(let l of s){let u=jC(e,l),c=jC(t,l),d=eq.JsonPointer.append(r,l);u===$c?n.push({pointer:d,type:"added",newValue:c}):c===$c?n.push({pointer:d,type:"removed",oldValue:u}):HC(u,c,d,n,i+1)}return}KC(e,t)||n.push({pointer:r,type:"modified",oldValue:e,newValue:t})}function Fc(e){return e!==null&&typeof e=="object"}function rq(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 jC(e,t){if(Array.isArray(e)){let r=Number(t);return r<e.length?e[r]:$c}return t in e?e[t]:$c}function KC(e,t){return JC(e,t,0)}qa.deepEqual=KC;function JC(e,t,r){if(e===t)return!0;if(r>xc)throw new RangeError(`deepEqual exceeded the maximum supported depth of ${xc}`);if(!Fc(e)||!Fc(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&&JC(e[o],t[o],r+1))}});var QC=v(Va=>{"use strict";Object.defineProperty(Va,"__esModule",{value:!0});Va.VersionManager=Va.PROJECTION_VERSION=void 0;var YC=Wm(),nq=ye();Va.PROJECTION_VERSION=8;var zm=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,YC.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,YC.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,nq.isVersionToken)(i.etag)?!0:i.etag!==n}};Va.VersionManager=zm});var ZC=v((jm,XC)=>{(function(e,t){typeof define=="function"&&define.amd?define([],t):typeof jm=="object"?XC.exports=t():e.compareVersions=t()})(jm,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 iE=v(He=>{"use strict";Object.defineProperty(He,"__esModule",{value:!0});He.EnvironmentFlowHostingType=He.EnvironmentDisableReasonCode=He.EnvironmentMigrationConstants=He.EnvironmentProvisioningStates=He.EnvironmentLocations=He.EnvironmentCreationTypeConstants=He.EnvironmentType=He.EnvironmentSkuConstants=He.environmentPermissions=He.DatabaseType=void 0;var eE;(function(e){e.CommonDataService="CommonDataService",e.None="None"})(eE||(He.DatabaseType=eE={}));He.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"};He.EnvironmentSkuConstants={NotSpecified:"NotSpecified",Standard:"Standard",Premium:"Premium",Developer:"Developer",Basic:"Basic",Production:"Production",Sandbox:"Sandbox",Trial:"Trial",Default:"Default",Teams:"Teams",Platform:"Platform"};var tE;(function(e){e[e.CDS2=0]="CDS2",e[e.CDS1=1]="CDS1",e[e.Empty=2]="Empty"})(tE||(He.EnvironmentType=tE={}));He.EnvironmentCreationTypeConstants={NotSpecified:"NotSpecified",Legacy:"Legacy",DefaultTenant:"DefaultTenant",User:"User",CommonDataModelLegacy:"CommonDataModelLegacy"};He.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"};He.EnvironmentProvisioningStates={NotSpecified:"NotSpecified",Succeeded:"Succeeded",Deleting:"Deleting",Deleted:"Deleted",FailedDeleting:"FailedDeleting",LinkedDatabaseProvisioning:"LinkedDatabaseProvisioning",LinkedDatabaseFailedProvisioning:"LinkedDatabaseFailedProvisioning",LinkedDatabaseFailedConfiguring:"LinkedDatabaseFailedConfiguring",LinkedDatabaseUnavailable:"LinkedDatabaseUnavailable",Creating:"Creating"};He.EnvironmentMigrationConstants={phases:{completed:"Completed"}};var rE;(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"})(rE||(He.EnvironmentDisableReasonCode=rE={}));var nE;(function(e){e.LogicApps="LogicApps",e.SelfHostSingleTenant="SelfHostSingleTenant",e.SelfHostMultiTenant="SelfHostMultiTenant"})(nE||(He.EnvironmentFlowHostingType=nE={}))});var fE=v(_=>{"use strict";var iq=_&&_.__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 oq=iq(ZC()),Pe=iE(),El=Km();function aq(e){let t=bi(e);return t&&t.version}_.getCrmVersion=aq;function bi(e){return e&&e.properties&&e.properties.linkedEnvironmentMetadata}_.getLinkedEnvironmentMetadata=bi;function yi(e,t){return e?!!e[t]:!1}_.doesUserHavePermission=yi;_.crmBapSolutionId="00000001-0000-0000-0001-00000000009b";_.DEFAULT_SOLUTION_ID="fd140aaf-4df4-11dd-bd17-0019b9312238";_.DEFAULT_SOLUTION_UNIQUE_NAME="Default";function xo(e){return!!bi(e)&&oE(e)}_.environmentHasCds2Database=xo;function sq(e){if(e&&xo(e)){let t=Zi(e);return(0,El.getCrmAdminSecurityRolesUrl)(t)}return""}_.getSecurityUsersUrl=sq;function lq(e){if(e&&xo(e)){let t=Zi(e);return(0,El.getCrmAdminSecurityUsersUrl)(t)}return""}_.getSecurityRolesUrl=lq;function uq(e){if(e&&xo(e)){let t=Zi(e);(0,El.getCrmAllSolutionsUrl)(t)}return""}_.getAllSolutionsUrl=uq;function cq(e){if(e&&xo(e)){let t=Zi(e);return(0,El.getCrmAllPublishersUrl)(t)}return""}_.getAllPublishersUrl=cq;function dq(e){return e&&xo(e)?Zi(e):""}_.getAllThemesUrl=dq;function oE(e){return!!e&&e.properties&&!!e.properties.provisioningState&&e.properties.provisioningState.toUpperCase()===Pe.EnvironmentProvisioningStates.Succeeded.toUpperCase()}_.isEnvironmentInSuccessfulState=oE;function fq(e){if(e&&xo(e)){let t=Zi(e);return(0,El.getCrmDevResourcesUrl)(t)}return""}_.getDevResourcesUrl=fq;function pq(e){return`${e}designer/app/{${_.crmBapSolutionId}}/CreateNewApp}}`}_.getCrmAppDesignerUrl=pq;function Zi(e){let t=bi(e);if(t){let r=t.instanceUrl;return r?r.endsWith("/")?r:r+"/":""}return""}_.getCrmInstanceUrl=Zi;function mq(e){let t=bi(e);return t?t.uniqueName:""}_.getCrmInstanceName=mq;function hq(e){return bi(e)?Pe.EnvironmentType.CDS2:e&&e.properties&&e.properties.namespace?Pe.EnvironmentType.CDS1:Pe.EnvironmentType.Empty}_.getEnvironmentType=hq;function gq(e){return e&&e.properties&&e.properties.environmentSku===Pe.EnvironmentSkuConstants.Developer}_.isDevEnvironment=gq;function yq(e){return e&&e.properties&&e.properties.environmentSku===Pe.EnvironmentSkuConstants.Production}_.isProdEnvironment=yq;function bq(e){return e&&e.properties&&e.properties.environmentSku===Pe.EnvironmentSkuConstants.Sandbox}_.isSandboxEnvironment=bq;function Al(e){return e&&e.properties&&e.properties.environmentSku===Pe.EnvironmentSkuConstants.Teams}_.isTeamsEnvironment=Al;function vq(e){return e&&e.properties&&e.properties.environmentSku===Pe.EnvironmentSkuConstants.Platform}_.isPlatformEnvironment=vq;var wq=e=>{var t;return((t=e.properties)===null||t===void 0?void 0:t.environmentSku)===Pe.EnvironmentSkuConstants.Trial};_.isTrialEnvironment=wq;function Cq(e){return e&&e.properties&&(e.properties.isDefault||e.properties.creationType===Pe.EnvironmentCreationTypeConstants.DefaultTenant)}_.isDefaultEnvironment=Cq;function Eq(e){return e&&e.properties&&!!e.properties.states&&!!e.properties.states.runtime&&e.properties.states.runtime.id==="Disabled"}_.isDisabledEnvironment=Eq;function Aq(e){return e&&e.properties&&yi(e.properties.permissions,Pe.environmentPermissions.CreateDatabase)}_.canUserCreateDatabase=Aq;function Sq(e){return!!(e&&e.properties&&e.properties.provisioningState&&dE(e.properties.provisioningState,Pe.EnvironmentProvisioningStates.LinkedDatabaseProvisioning))}_.isDatabaseInProvisioningState=Sq;function Nq(e){return!!e&&!!e.properties&&e.properties.provisioningState===Pe.EnvironmentProvisioningStates.Creating}_.isEnvironmentInCreatingState=Nq;function _q(e){return e&&e.properties&&(e.properties.provisioningState===Pe.EnvironmentProvisioningStates.Deleted||e.properties.provisioningState===Pe.EnvironmentProvisioningStates.Deleting||e.properties.provisioningState===Pe.EnvironmentProvisioningStates.FailedDeleting)}_.isEnvironmentInDeletedState=_q;function Tq(e){return!!e&&!!e.properties&&!!e.properties.expirationTime&&Date.parse(e.properties.expirationTime)<Date.now()}_.isEnvironmentExpired=Tq;function Dq(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=Dq;function Iq(e){return!!e&&!!e.properties&&!!e.properties.cluster&&e.properties.cluster.category==="Test"}_.isEnvironmentInTestCluster=Iq;function Oq(e){return!!e&&!!e.properties&&!!e.properties.cluster&&e.properties.cluster.category==="Preprod"}_.isEnvironmentInPreprodCluster=Oq;function Pq(e){return!!e&&!!e.properties&&!!e.properties.cluster&&e.properties.cluster.category==="FirstRelease"}_.isEnvironmentInFirstReleaseCluster=Pq;function Rq(e){return e&&e.name||""}_.getEnvironmentName=Rq;function kq(e){return e&&e.properties&&e.properties.displayName||""}_.getEnvironmentDisplayName=kq;var aE="9.1.0.8202";_.cdsVersionSupportingOSColorEdit="9.1.0000.20708";function Lq(e){return uE(e,aE)}_.doesCds2EnvironmentSupportApiVersion9_1=Lq;function $q(e){return Hm(e,aE)}_.doesCds2VersionSupportApiVersion9_1=$q;function sE(e){let t=bi(e);if(t)return t.securityGroupId}function lE(e){return e&&e.properties&&e.properties.connectedGroups}function xq(e,t){let r=lE(e);return!!r&&!!r.find(n=>n.id===t)||sE(e)===t}_.hasSecurityGroupId=xq;function Fq(e){let t=lE(e);return t&&t.length>0&&t[0].id?t[0].id:sE(e)}_.getSecurityOrConnectedGroupId=Fq;function uE(e,t){let r=e.version;return r?Hm(r,t):!1}_.isCds2EnvironmentVersionAtLeast=uE;function Hm(e,t){return t?e?(0,oq.default)(e,t)>=0:!1:!0}_.checkVersions=Hm;function Mq(e){return e&&e.properties&&e.properties.updateCadence&&e.properties.updateCadence.id||"NotSpecified"}_.getEnvironmentUpdateCadence=Mq;function Uq(e){let t=bi(e);return t?Number(t.baseLanguage):0}_.getEnvironmentLanguageCode=Uq;function cE(e){let t=bi(e);return t?t.instanceApiUrl:void 0}_.getEnvironmentInstanceApiUrl=cE;function Bq(e){let t=cE(e);return t?t+"/api/data/v9.2":""}_.getEnvironmentWebApiUrl=Bq;function qq(e){let t=Zi(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=qq;var Vq=e=>{var t;return((t=e.properties)===null||t===void 0?void 0:t.databaseType)===Pe.DatabaseType.CommonDataService};_.hasCommonDataServiceDatabase=Vq;var Gq=e=>{var t;return yi((t=e.properties)===null||t===void 0?void 0:t.permissions,Pe.environmentPermissions.AdminReadEnvironment)};_.doesUserHaveAdminPermission=Gq;var Wq=e=>{var t;return yi((t=e.properties)===null||t===void 0?void 0:t.permissions,Pe.environmentPermissions.CreatePowerApp)};_.doesUserHaveCreateAppPermission=Wq;var zq=e=>(0,_.doesUserHaveAdminPermission)(e)&&(0,_.hasCommonDataServiceDatabase)(e)?!0:(0,_.doesUserHaveCreateAppPermission)(e)?Al(e)||(0,_.doesUserHaveDatabaseTablePermissions)(e):!1;_.isUserMakerWithDataAccess=zq;var jq=e=>(0,_.doesUserHaveCreateAppPermission)(e)&&!Al(e)&&!(0,_.doesUserHaveDatabaseTablePermissions)(e)&&(!(0,_.doesUserHaveAdminPermission)(e)||!(0,_.hasCommonDataServiceDatabase)(e));_.isUserMakerWithoutDataAccess=jq;var Hq=e=>[Pe.environmentPermissions.CreateDatabaseEntities,Pe.environmentPermissions.ListDatabaseEntities,Pe.environmentPermissions.UpdateDatabaseEntities,Pe.environmentPermissions.DeleteDatabaseEntities].every(t=>{var r;return yi((r=e.properties)===null||r===void 0?void 0:r.permissions,t)});_.doesUserHaveDatabaseTablePermissions=Hq;var Kq=e=>{var t;return yi((t=e.properties)===null||t===void 0?void 0:t.permissions,Pe.environmentPermissions.CreateDatabase)};_.doesUserHaveCreateDatabasePermission=Kq;function dE(e,t){return!e&&!t?!0:!e||!t?!1:e.toUpperCase()===t.toUpperCase()}_.equalsIgnoreCase=dE;var Jq=e=>{var t;return yi((t=e.properties)===null||t===void 0?void 0:t.permissions,Pe.environmentPermissions.CreateFlow)};_.doesUserHaveCreateFlowPermission=Jq;var Yq=e=>(0,_.doesUserHaveAdminPermission)(e)&&(0,_.hasCommonDataServiceDatabase)(e)?!0:(0,_.doesUserHaveCreateFlowPermission)(e)?Al(e)||(0,_.doesUserHaveDatabaseTablePermissions)(e):!1;_.isUserPautoMakerWithDataAccess=Yq;var Qq=e=>(0,_.doesUserHaveCreateFlowPermission)(e)&&!Al(e)&&!(0,_.doesUserHaveDatabaseTablePermissions)(e)&&(!(0,_.doesUserHaveAdminPermission)(e)||!(0,_.hasCommonDataServiceDatabase)(e));_.isUserPautoMakerWithoutDataAccess=Qq;var Xq=e=>{var t,r;return!yi((t=e.properties)===null||t===void 0?void 0:t.permissions,Pe.environmentPermissions.CreateFlow)&&yi((r=e.properties)===null||r===void 0?void 0:r.permissions,Pe.environmentPermissions.ReadEnvironment)};_.doesUserHaveFlowRunOnlyPermission=Xq});var Km=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 pE=fE();A.ODATA_MAX_PAGE_SIZE="odata.maxpagesize";A.ODATA_NEXT_LINK="@odata.nextLink";A.cdsServiceUrl="https://cds-org/";var Nl;(function(e){e.AllSolutions="11",e.AllPublishers="10",e.DevResources="05"})(Nl||(Nl={}));function Zq(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=Zq;function e3(e,t){let r=`dType=1&isproactivecheck=true&objecttype=7100&operationtype=dependenciesforuninstall&objectid=${t}`;return`${e}tools/dependency/dependencyviewdialog.aspx?${r}`}A.getShowSolutionDependenciesUrl=e3;function t3(e,t){return`${e}tools/muiProvisioning/Dialogs/LangTranslationsImport.aspx?dType=1&appSolutionId=${t}`}A.getImportSolutionTranslationUrl=t3;function r3(e,t){return`${e}_grid/cmds/dlg_exportsolution.aspx?command=exporttranslation&appSolutionId=${t}`}A.getExportSolutionTranslationUrl=r3;function n3(e,t){return e!==void 0&&t!==void 0&&`CrmTranslations_${e}_${t.replace(/[.]/g,"_")}.zip`||""}A.getExportTranslationFileName=n3;function i3(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=i3;function Jm(e,t){return`${e}tools/systemcustomization/systemCustomization.aspx?pid=${t}`}function o3(e){return Jm(e,Nl.AllSolutions)}A.getCrmAllSolutionsUrl=o3;function a3(e){return Jm(e,Nl.AllPublishers)}A.getCrmAllPublishersUrl=a3;function s3(e){return Jm(e,Nl.DevResources)}A.getCrmDevResourcesUrl=s3;function l3(e,t=pE.crmBapSolutionId){return`${e}designer/app/${t}#/CreateNewApp`}A.getCrmAppDesignerUrl=l3;function u3(e){return`${e}apps`}A.getCrmMyAppsUrl=u3;function c3(e){return mE(e,"role")+"&forceUCI=0"}A.getCrmAdminSecurityRolesUrl=c3;function d3(e){return`${mE(e,"systemuser")}&forceclassic=1`}A.getCrmAdminSecurityUsersUrl=d3;function mE(e,t){return`${e}main.aspx?pagetype=entitylist&etn=${t}`}function f3(e,t){return`${e}main.aspx?appid=${t}`}A.getPlayAppModuleUrl=f3;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 p3(e,t,r=pE.crmBapSolutionId){return`${e}designer/app/${r}/${t}/AppDesignerCanvas/${t}`}A.getAppModuleDesignerUrl=p3;function m3(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=m3;function h3(e,t,r){return`/e/${e}/s/${t}/dashboard/${r}`}A.getOpenModernDashboardUrl=h3;function g3(e,t,r){let n=r!==void 0?r.toString():void 0;return`/e/${e}/s/${t}/dashboard/new${n?`/${n}`:""}`}A.getNewModernDashboardUrl=g3;function y3(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=y3;function b3(e,t,r,n){return`/e/${e}/s/${t}/n/${r}/dashboard/${n}`}A.getOpenModernEntityDashboardUrl=b3;function v3(e,t,r,n){return`${e}main.aspx?appSolutionId=%7b${t}%7d&extraqs=etc=${r||""}`+(n?`%26id=${n}`:"")+"&pagetype=vizdesigner"}A.getChartDesignerUrl=v3;function w3(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=w3;function C3(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=C3;function E3(e,t){return`${e}Tools/ProcessControl/UnifiedProcessDesigner.aspx?id=${t}`}A.getBusinessProcessFlowDesignerUrl=E3;function A3(e,t,r){return`${e}CRMReports/reportproperty.aspx?appSolutionId=%7b${r}%7d&disablePersonal=true&id=%7b${t}%7d`}A.getReportDesignerUrl=A3;function S3(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=S3;function N3(e,t){return`${e}WebResources/${t}`}A.getWebResourceFileUrl=N3;function _3(e,t,r){return`${e}designer/sitemap/${r}/${t}/SiteMapHome/${t}`}A.getSiteMapDesignerUrl=_3;function T3(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=T3;function D3(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=D3;function I3(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=I3;function O3(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=O3;function P3(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=P3;function R3(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=R3;function k3(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=k3;function L3(e){return`${e}tools/publisher/edit.aspx`}A.getCreateNewPublisherUrl=L3;function $3(e,t){return`${e}tools/kbtemplateeditor/kbtemplateeditor.aspx?appSolutionId=${t}`}A.getCreateNewArticleTemplateUrl=$3;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 x3(e,t){return`${A.xrmApiUrl}/RetrieveRequiredComponents(ObjectId=${e},ComponentType=${t})`}A.getRequiredComponentsQueryUrl=x3;function F3(e,t){return`${A.cdsServiceUrl}${A.xrmApiUrl}/RetrieveDependentComponentsWithMetadata(ObjectId=${e},ComponentType=${t})`}A.getDependentComponentsWithMetadataQueryUrl=F3;A.solutionsQueryUrl="/api/data/v9.0/solutions?$expand=publisherid&$filter=(isvisible eq true)";function M3(e){return`/api/data/v9.0/solutions?$expand=publisherid&$filter=(uniquename eq '${e}')`}A.getSolutionsByUniqueNameQueryUrl=M3;function U3(e){return`/api/data/v9.0/solutions(${e})?$expand=publisherid`}A.getSolutionQueryUrl=U3;function B3(e){return`${e}api/data/v9.1/ProvisionLanguageForUser`}A.getProvisionLanguageUrl=B3;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 q3(e,t,r,n=!1,i=!1,o=!1,a=!1,s=!1,l=!1,u=!1){return`/api/data/v9.1/deploymentstageruns- ?$select=artifactname,artifactversion,deploymentstagerunid,devenvironmentid,endtime,errormessage,${s?"_artifactid_value,isredeployment,":""}${n?"deploymentnotes,":""}operation,operationdetails,operationstatus,${l?"retrycount,":""}${i?"scheduledtime,":""}${u?"solutionid,":""}stagerunstatus,starttime,suboperation,targetenvironmentid,${o?"predeploymentstepnotes,":""}validationresults,${a?"approvalcomments,":""}_devdeploymentenvironment_value,_targetdeploymentenvironment_value- &$expand=deploymentstageid($select=deploymentstageid,name,_deploymentpipelineid_value),targetdeploymentenvironment($select=deploymentenvironmentid,environmentid,name),createdby($select=azureactivedirectoryobjectid,fullname,ownerid,systemuserid)${l?",RetryUser($select=azureactivedirectoryobjectid,fullname,ownerid,systemuserid)":""}- &$filter=deploymentstageid/_deploymentpipelineid_value eq ${e} and devenvironmentid eq '${t}' and artifactname eq '${r}' and ((operation ne 200000201) or (operation eq 200000201 and operationstatus eq 200000003))- &$orderby=starttime desc`}A.getDeploymentStageRunsUrl=q3;function V3(e,t,r){return`/api/data/v9.1/RetrieveDeploymentPipelineInfo(DeploymentPipelineId=${e},SourceEnvironmentId='${t}',ArtifactName='${r}')`}A.retrieveDeploymentPipelineInfoUrl=V3;function G3(e){return`/api/data/v9.0/deploymentenvironments+var p6=Object.create;var lh=Object.defineProperty;var m6=Object.getOwnPropertyDescriptor;var h6=Object.getOwnPropertyNames;var g6=Object.getPrototypeOf,y6=Object.prototype.hasOwnProperty;var B=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(r){throw n=[r],r}};var C=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(n){throw t=0,n}},Fi=(e,t)=>{for(var n in t)lh(e,n,{get:t[n],enumerable:!0})},uh=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of h6(t))!y6.call(e,i)&&i!==n&&lh(e,i,{get:()=>t[i],enumerable:!(r=m6(t,i))||r.enumerable});return e},Os=(e,t,n)=>(uh(e,t,"default"),n&&uh(n,t,"default")),Xe=(e,t,n)=>(n=e!=null?p6(g6(e)):{},uh(t||!e||!e.__esModule?lh(n,"default",{value:e,enumerable:!0}):n,e)),_i=e=>uh(lh({},"__esModule",{value:!0}),e);var Ds=C(L=>{"use strict";Object.defineProperty(L,"__esModule",{value:!0});L.DateTimeBehavior=L.PrecisionSource=L.StringFormatName=L.SourceType=L.ImeMode=L.SolutionEntityTypeCodeExtToComponentTypeCode=L.SolutionComponentTypeCodeToEntityTypeCodeExt=L.SolutionComponentVirtualAttributeSubtype=L.EntityTypeCode=L.SolutionComponentTypeCodeExt=L.RootComponentBehavior=L.SolutionComponentTypeCode=L.EntityKeyIndexStatus=L.ViewStateCode=L.ViewStatusCode=L.RelationshipSecurityTypes=L.CascadeType=L.RelationshipTypeExt=L.RelationshipType=L.AppSubType=L.BusinessProcessType=L.WorkflowCategory=L.WorkflowScope=L.WorkflowTypeCode=L.StatusCodeEnabledDisabled=L.StateCodeEnabledDisabled=L.StatusCode=L.StateCode=L.OptionSetType=L.AttributeTypeCodeNum=L.AttributeFormatName=L.AttributeFormatCode=L.AttributeTypeName=L.AttributeTypeCode=L.PluginSourceType=L.AuthType=L.PluginIsolationMode=L.ComponentState=L.ChartType=L.ChartsType=L.ViewType=L.AttributeType=L.ActivationState=L.FormPresentation=L.FormType=L.TableTypeCode=L.TableTypes=L.ActivityTypeMask=L.PrincipalType=L.OwnershipTypes=void 0;L.QueryType=L.KnownCustomSolutionComponentEntitySetName=L.TeamTypeEnum=L.EnvironmentVariableDefinitionTypeEnum=L.ConnectorTypeEnum=L.RoleInheritance=L.DefaultRoleTemplates=L.DeleteDependencyErrorCode=L.ServiceEndpointConnectionMode=L.ServiceEndpointContract=L.ServiceNamespaceFormat=L.ConnectionRoleCategory=L.ReportTypeCode=L.SdkMessageProcessingMode=L.SupportedDeployment=L.SdkMessageProcessingStage=L.WebResourceTypeCode=L.IntegerFormat=L.DateTimeFormat=void 0;var fT;(function(e){e.None="None",e.UserOwned="UserOwned",e.TeamOwned="TeamOwned",e.BusinessOwned="BusinessOwned",e.OrganizationOwned="OrganizationOwned",e.BusinessParented="BusinessParented",e.Filtered="Filtered"})(fT||(L.OwnershipTypes=fT={}));var pT;(function(e){e.User="Microsoft.Dynamics.CRM.systemuser",e.Team="Microsoft.Dynamics.CRM.team"})(pT||(L.PrincipalType=pT={}));var mT;(function(e){e[e.DoNotDisplayInActivityMenus=0]="DoNotDisplayInActivityMenus",e[e.DisplayInActivityMenus=1]="DisplayInActivityMenus"})(mT||(L.ActivityTypeMask=mT={}));var hT;(function(e){e.Activity="Activity",e.Virtual="Virtual",e.Standard="Standard",e.Elastic="Elastic"})(hT||(L.TableTypes=hT={}));var gT;(function(e){e.Standard="Standard",e.Virtual="Virtual",e.Elastic="Elastic"})(gT||(L.TableTypeCode=gT={}));var yT;(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"})(yT||(L.FormType=yT={}));var bT;(function(e){e[e.ClassicForm=0]="ClassicForm",e[e.AirForm=1]="AirForm",e[e.ConvertedICForm=2]="ConvertedICForm"})(bT||(L.FormPresentation=bT={}));var vT;(function(e){e[e.Inactive=0]="Inactive",e[e.Active=1]="Active"})(vT||(L.ActivationState=vT={}));var wT;(function(e){e[e.String=0]="String",e[e.Number=1]="Number",e[e.Picklist=2]="Picklist"})(wT||(L.AttributeType=wT={}));var ET;(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"})(ET||(L.ViewType=ET={}));var AT;(function(e){e[e.ASPChart=0]="ASPChart",e[e.PowerBI=1]="PowerBI"})(AT||(L.ChartsType=AT={}));var CT;(function(e){e[e.DataAndInteractionCentric=0]="DataAndInteractionCentric",e[e.InteractionCentric=1]="InteractionCentric"})(CT||(L.ChartType=CT={}));var ST;(function(e){e[e.Published=0]="Published",e[e.Unpublished=1]="Unpublished",e[e.Deleted=2]="Deleted",e[e.DeletedUnpublished=3]="DeletedUnpublished"})(ST||(L.ComponentState=ST={}));var NT;(function(e){e[e.None=1]="None",e[e.Sandbox=2]="Sandbox",e[e.External=3]="External"})(NT||(L.PluginIsolationMode=NT={}));var _T;(function(e){e[e.BasicAuth=0]="BasicAuth"})(_T||(L.AuthType=_T={}));var IT;(function(e){e[e.Database=0]="Database",e[e.Disk=1]="Disk",e[e.Normal=2]="Normal",e[e.AzureWebApp=3]="AzureWebApp"})(IT||(L.PluginSourceType=IT={}));var TT;(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"})(TT||(L.AttributeTypeCode=TT={}));var OT;(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"})(OT||(L.AttributeTypeName=OT={}));var DT;(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"})(DT||(L.AttributeFormatCode=DT={}));var PT;(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"})(PT||(L.AttributeFormatName=PT={}));var RT;(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"})(RT||(L.AttributeTypeCodeNum=RT={}));var kT;(function(e){e.Picklist="Picklist",e.State="State",e.Status="Status",e.Boolean="Boolean"})(kT||(L.OptionSetType=kT={}));var $T;(function(e){e[e.Draft=0]="Draft",e[e.Activated=1]="Activated"})($T||(L.StateCode=$T={}));var LT;(function(e){e[e.Draft=1]="Draft",e[e.Activated=2]="Activated"})(LT||(L.StatusCode=LT={}));var MT;(function(e){e[e.Enabled=0]="Enabled",e[e.Disabled=1]="Disabled"})(MT||(L.StateCodeEnabledDisabled=MT={}));var xT;(function(e){e[e.Enabled=1]="Enabled",e[e.Disabled=2]="Disabled"})(xT||(L.StatusCodeEnabledDisabled=xT={}));var FT;(function(e){e[e.Definition=1]="Definition",e[e.Activation=2]="Activation",e[e.Template=3]="Template"})(FT||(L.WorkflowTypeCode=FT={}));var UT;(function(e){e[e.User=1]="User",e[e.BusinessUnit=2]="BusinessUnit",e[e.ParentChildBusinessUnit=3]="ParentChildBusinessUnit",e[e.Organization=4]="Organization"})(UT||(L.WorkflowScope=UT={}));var qT;(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"})(qT||(L.WorkflowCategory=qT={}));var BT;(function(e){e[e.None=-1]="None",e[e.BusinessFlow=0]="BusinessFlow",e[e.TaskFlow=1]="TaskFlow"})(BT||(L.BusinessProcessType=BT={}));var VT;(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"})(VT||(L.AppSubType=VT={}));var GT;(function(e){e.OneToManyRelationship="OneToManyRelationship",e.ManyToManyRelationship="ManyToManyRelationship"})(GT||(L.RelationshipType=GT={}));var jT;(function(e){e.ManyToOneRelationship="ManyToOneRelationship",e.OneToManyRelationship="OneToManyRelationship",e.ManyToManyRelationship="ManyToManyRelationship"})(jT||(L.RelationshipTypeExt=jT={}));var WT;(function(e){e.NoCascade="NoCascade",e.Cascade="Cascade",e.Active="Active",e.UserOwned="UserOwned",e.RemoveLink="RemoveLink",e.Restrict="Restrict"})(WT||(L.CascadeType=WT={}));var zT;(function(e){e.None="None",e.Append="Append",e.ParentChild="ParentChild",e.Pointer="Pointer",e.Inheritance="Inheritance"})(zT||(L.RelationshipSecurityTypes=zT={}));var HT;(function(e){e[e.Active=1]="Active",e[e.Inactive=2]="Inactive"})(HT||(L.ViewStatusCode=HT={}));var KT;(function(e){e[e.Active=0]="Active",e[e.Inactive=1]="Inactive"})(KT||(L.ViewStateCode=KT={}));var JT;(function(e){e.Active="Active",e.Failed="Failed",e.InProgress="InProgress",e.Pending="Pending"})(JT||(L.EntityKeyIndexStatus=JT={}));var YT;(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"})(YT||(L.SolutionComponentTypeCode=YT={}));var QT;(function(e){e[e.IncludeSubcomponents=0]="IncludeSubcomponents",e[e.DoNotIncludeSubcomponents=1]="DoNotIncludeSubcomponents",e[e.IncludeAsShellOnly=2]="IncludeAsShellOnly"})(QT||(L.RootComponentBehavior=QT={}));var ch;(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"})(ch||(L.SolutionComponentTypeCodeExt=ch={}));var dh;(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"})(dh||(L.EntityTypeCode=dh={}));var XT;(function(e){e.MultiSelectPicklist="MultiSelectPicklist",e.File="File",e.Image="Image"})(XT||(L.SolutionComponentVirtualAttributeSubtype=XT={}));function b6(e){let t=ch[e];return dh[t]}L.SolutionComponentTypeCodeToEntityTypeCodeExt=b6;function v6(e){let t=dh[e];return ch[t]}L.SolutionEntityTypeCodeExtToComponentTypeCode=v6;var ZT;(function(e){e.Active="Active",e.Auto="Auto",e.Disabled="Disabled",e.Inactive="Inactive"})(ZT||(L.ImeMode=ZT={}));var eO;(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"})(eO||(L.SourceType=eO={}));var tO;(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"})(tO||(L.StringFormatName=tO={}));var nO;(function(e){e[e.PrecisionProperty=0]="PrecisionProperty",e[e.Organization=1]="Organization",e[e.TransactionCurrency=2]="TransactionCurrency"})(nO||(L.PrecisionSource=nO={}));var rO;(function(e){e.UserLocal="UserLocal",e.DateOnly="DateOnly",e.TimeZoneIndependent="TimeZoneIndependent"})(rO||(L.DateTimeBehavior=rO={}));var iO;(function(e){e.DateOnly="DateOnly",e.DateAndTime="DateAndTime"})(iO||(L.DateTimeFormat=iO={}));var oO;(function(e){e.None="None",e.Duration="Duration",e.TimeZone="TimeZone",e.Language="Language",e.Locale="Locale"})(oO||(L.IntegerFormat=oO={}));var aO;(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"})(aO||(L.WebResourceTypeCode=aO={}));var sO;(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"})(sO||(L.SdkMessageProcessingStage=sO={}));var uO;(function(e){e[e.ServerOnly=0]="ServerOnly",e[e.OutlookClientOnly=1]="OutlookClientOnly",e[e.Both=2]="Both"})(uO||(L.SupportedDeployment=uO={}));var lO;(function(e){e[e.Synchronous=0]="Synchronous",e[e.Asynchronous=1]="Asynchronous"})(lO||(L.SdkMessageProcessingMode=lO={}));var cO;(function(e){e[e.ReportingServicesReport=1]="ReportingServicesReport",e[e.OtherReport=2]="OtherReport",e[e.LinkedReport=3]="LinkedReport"})(cO||(L.ReportTypeCode=cO={}));var dO;(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"})(dO||(L.ConnectionRoleCategory=dO={}));var fO;(function(e){e[e.Name=1]="Name",e[e.Address=2]="Address"})(fO||(L.ServiceNamespaceFormat=fO={}));var pO;(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"})(pO||(L.ServiceEndpointContract=pO={}));var mO;(function(e){e[e.Normal=1]="Normal",e[e.Federated=2]="Federated"})(mO||(L.ServiceEndpointConnectionMode=mO={}));var hO;(function(e){e.CannotDeleteInUseComponent="0x8004f01f",e.CannotDeleteInUseAttribute="0x80048418",e.CannotDeleteInUseOptionSet="0x80048417",e.CannotDeleteInUseEntity="0x80048420",e.CannotUninstallWithDependencies="0x8004F01D"})(hO||(L.DeleteDependencyErrorCode=hO={}));var gO;(function(e){e.SystemAdministrator="627090FF-40A3-4053-8790-584EDC5BE201",e.SystemCustomizer="119F245C-3CC8-4B62-B31C-D1A046CED15D"})(gO||(L.DefaultRoleTemplates=gO={}));var yO;(function(e){e[e.DefaultTeamPrivilege=0]="DefaultTeamPrivilege",e[e.DirectUserAndTeamPrivilege=1]="DirectUserAndTeamPrivilege"})(yO||(L.RoleInheritance=yO={}));var bO;(function(e){e[e.NotSpecified=0]="NotSpecified",e[e.CustomConnector=1]="CustomConnector"})(bO||(L.ConnectorTypeEnum=bO={}));var vO;(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"})(vO||(L.EnvironmentVariableDefinitionTypeEnum=vO={}));var wO;(function(e){e[e.Owner=0]="Owner",e[e.Access=1]="Access",e[e.AADSecurityGroup=2]="AADSecurityGroup",e[e.AADOfficeGroup=3]="AADOfficeGroup"})(wO||(L.TeamTypeEnum=wO={}));var EO;(function(e){e.Bots="bots"})(EO||(L.KnownCustomSolutionComponentEntitySetName=EO={}));var AO;(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"})(AO||(L.QueryType=AO={}))});var Y=C(Z=>{"use strict";Object.defineProperty(Z,"__esModule",{value:!0});Z.PromotionError=Z.UpsertOutcomeUnknownError=Z.DataFixColumnsInvalidError=Z.DataFixError=Z.DateTimeBehaviorMissingError=Z.TableSearchNotAllowedError=Z.InspectionUnreadableError=Z.COMMAND_IMMUTABLE_COLUMN_CHANGED_CODE=Z.INSPECTION_UNREADABLE_CODE=Z.INSPECTION_NOT_SUPPORTED_CODE=Z.ArtifactInUseError=Z.AppThemeError=Z.IncompatibleWorkspaceError=Z.PathTraversalError=Z.AmbiguousArtifactError=Z.JsonPointerError=Z.NotImplementedError=Z.WorkspaceOrgMismatchError=Z.WorkspaceNotInitializedError=Z.attachCause=Z.WebResourceUnverifiedError=Z.ConnectionError=Z.VersionConflictError=Z.LocalEditsWouldBeLostError=Z.StaleArtifactError=Z.InvalidArgumentError=Z.ValidationError=Z.PathNotFoundError=Z.ArtifactNotFoundError=Z.readCleanupWarnings=Z.withCleanupWarnings=Z.readPartialEnrichment=Z.withPartialEnrichment=Z.readPartialTokens=Z.withPartialTokens=Z.SdkError=void 0;var yt=class extends Error{constructor(t,n){super(n),this.code=t,Object.setPrototypeOf(this,new.target.prototype),this.name=new.target.name}};Z.SdkError=yt;var CO=Symbol.for("cds-maker-sdk.partialWriteTokens");function w6(e,t){return typeof e=="object"&&e!==null&&(e[CO]=t),e}Z.withPartialTokens=w6;function E6(e){return Sv(e,CO)}Z.readPartialTokens=E6;function Sv(e,t){let n=e;for(let r=0;n&&typeof n=="object"&&r<8;r++){let i=n[t];if(i&&typeof i=="object")return i;n=n.cause}}var SO=Symbol.for("cds-maker-sdk.partialDefaultViewEnrichment");function A6(e,t){return typeof e=="object"&&e!==null&&(e[SO]=t),e}Z.withPartialEnrichment=A6;function C6(e){return Sv(e,SO)}Z.readPartialEnrichment=C6;var Zb=Symbol.for("cds-maker-sdk.cleanupWarnings");function S6(e,t){if(typeof e=="object"&&e!==null&&t.length>0){let n=e,r=n[Zb];n[Zb]=[...Array.isArray(r)?r:[],...t]}return e}Z.withCleanupWarnings=S6;function N6(e){let t=Sv(e,Zb);return t?[...t]:void 0}Z.readCleanupWarnings=N6;var ev=class extends yt{constructor(t,n){super("ARTIFACT_NOT_FOUND",`Artifact ${t}/${n} not found in workspace`),this.type=t,this.id=n}};Z.ArtifactNotFoundError=ev;var tv=class extends yt{constructor(t,n,r){super("PATH_NOT_FOUND",`Path ${r} not found in ${t}/${n}`),this.type=t,this.id=n,this.pointer=r}};Z.PathNotFoundError=tv;var nv=class extends yt{constructor(t,n,r,i){var o,a,s,u;let l=Array.isArray(r)?r:[{pointer:r,rule:i??"invalid",message:i??"invalid"}];super("VALIDATION_ERROR",`Validation failed for ${t}/${n}:+`+l.map(c=>` \u2022 ${c.pointer}: ${c.message} [${c.rule}]`).join(`+`)),this.type=t,this.id=n,this.issues=l,this.pointer=(a=(o=l[0])===null||o===void 0?void 0:o.pointer)!==null&&a!==void 0?a:"",this.rule=(u=(s=l[0])===null||s===void 0?void 0:s.rule)!==null&&u!==void 0?u:"invalid"}};Z.ValidationError=nv;var rv=class extends yt{constructor(t){super("INVALID_ARGUMENT",t)}};Z.InvalidArgumentError=rv;var iv=class extends yt{constructor(t,n,r,i="revalidated"){super("STALE_ARTIFACT",i==="pushed"?`Cannot apply the edit at ${r} to ${t}/${n}: 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 ${r} to ${t}/${n}: 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=n,this.pointer=r,this.reason=i}};Z.StaleArtifactError=iv;var ov=class extends yt{constructor(t,n,r,i){super("LOCAL_EDITS_WOULD_BE_LOST",`Refusing to fetch ${t}/${n}: the local copy has unpushed edits AND the server has moved since it was fetched (local=${r??"(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=n,this.localEtag=r,this.serverEtag=i}};Z.LocalEditsWouldBeLostError=ov;var av=class extends yt{constructor(t,n,r,i,o){super("VERSION_CONFLICT",`Version conflict for ${t}/${n}: local=${r??"(none)"}, server=${i??"(none)"}. Re-fetch and reapply changes.${o?` ${o}`:""}`),this.type=t,this.id=n,this.localEtag=r,this.serverEtag=i,this.detail=o}};Z.VersionConflictError=av;var sv=class extends yt{constructor(t,n,r,i){super("CONNECTION_ERROR",n>0?`HTTP ${n} from ${t}: ${r}`:`Transport failure reaching ${t}: ${r}`),this.url=t,this.statusCode=n,Object.defineProperty(this,"cause",{value:i,enumerable:!1,writable:!1,configurable:!0})}};Z.ConnectionError=sv;var uv=class extends yt{constructor(t,n,r){super("WEB_RESOURCE_UNVERIFIED",r),this.id=t,this.webResourceName=n}};Z.WebResourceUnverifiedError=uv;function NO(e,t){return typeof e=="object"&&e!==null&&Object.defineProperty(e,"cause",{value:t,enumerable:!1,writable:!0,configurable:!0}),e}Z.attachCause=NO;var lv=class extends yt{constructor(t){super("WORKSPACE_NOT_INITIALIZED",`Workspace not initialized at ${t}. Call initWorkspace() first.`),this.workspacePath=t}};Z.WorkspaceNotInitializedError=lv;var cv=class extends yt{constructor(t,n){super("WORKSPACE_ORG_MISMATCH",`This workspace belongs to ${t?`'${t}'`:"no recorded org"}, but this SDK targets '${n}'. 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 '${n}'.`),this.workspaceInstanceUrl=t,this.instanceUrl=n}};Z.WorkspaceOrgMismatchError=cv;var dv=class extends yt{constructor(t,n){super("NOT_IMPLEMENTED",`Operation '${t}' is not implemented yet${n?`: ${n}`:""}.`),this.operation=t}};Z.NotImplementedError=dv;var fv=class extends yt{constructor(t,n){super("INVALID_JSON_POINTER",`Invalid JSON Pointer '${t}': ${n}`),this.pointer=t}};Z.JsonPointerError=fv;var pv=class extends yt{constructor(t,n,r){super("AMBIGUOUS_ARTIFACT",`Found ${r} ${t} rows matching '${n}'; a name is not a unique key. Resolve by id / alternate key instead of relying on name-based idempotency.`),this.kind=t,this.identity=n,this.matchCount=r}};Z.AmbiguousArtifactError=pv;var mv=class extends yt{constructor(t,n){super("PATH_TRAVERSAL",`Refusing to resolve a path outside the workspace root: '${t}' is not within '${n}'.`),this.target=t,this.root=n}};Z.PathTraversalError=mv;var hv=class extends yt{constructor(t,n){super("INCOMPATIBLE_WORKSPACE",`Workspace schema version ${t} is newer than this SDK supports (v${n}). Upgrade the SDK, or re-create the workspace with this version.`),this.workspaceVersion=t,this.supportedVersion=n}};Z.IncompatibleWorkspaceError=hv;var gv=class extends yt{constructor(t,n,r,i){super(t,r),this.appId=n,this.webResourceName=i}};Z.AppThemeError=gv;var yv=class extends yt{constructor(t,n,r,i){super("ARTIFACT_IN_USE",r),this.type=t,this.id=n,this.dependents=i}};Z.ArtifactInUseError=yv;Z.INSPECTION_NOT_SUPPORTED_CODE="INSPECTION_NOT_SUPPORTED";Z.INSPECTION_UNREADABLE_CODE="INSPECTION_UNREADABLE";Z.COMMAND_IMMUTABLE_COLUMN_CHANGED_CODE="COMMAND_IMMUTABLE_COLUMN_CHANGED";var bv=class extends yt{constructor(t,n,r,i){super(Z.INSPECTION_UNREADABLE_CODE,`Cannot inspect ${t} '${n}': ${i} Nothing is reported \u2014 re-run the inspection; a partial read is never returned.`),this.type=t,this.id=n,this.statusCode=r}};Z.InspectionUnreadableError=bv;var vv=class extends yt{constructor(t){super("TABLE_SEARCH_NOT_ALLOWED",`Table '${t}' cannot be included in Dataverse search: its managed property CanEnableSyncToExternalSearchIndex is false (a solution-layer decision). Nothing was written.`),this.entityLogicalName=t}};Z.TableSearchNotAllowedError=vv;var wv=class extends yt{constructor(t,n){let r=n.map(o=>`'${o}'`).join(", "),i=n.map(o=>`updateColumn('${t}', '${o}', { dateTimeBehavior: 'UserLocal' })`).join(", then ");super("DATETIME_BEHAVIOR_MISSING",`Dataverse refused a new column or lookup on '${t}' (0x80048550) because its Date and Time column(s) ${r} have no DateTimeBehavior \u2014 an earlier createTable created them that way. Repair each with ${i} \u2014 UserLocal is how their values are already stored \u2014 then retry. Nothing was created by the refused request.`),this.table=t,this.columns=[...n]}};Z.DateTimeBehaviorMissingError=wv;var fh=class extends yt{constructor(t,n,r,i,o){super(t,n),this.httpStatus=r,this.path=i,this.maxRows=o}};Z.DataFixError=fh;var Ev=class extends fh{constructor(t){super("DATA_FIX_COLUMNS_INVALID",`The data fix cannot write ${t.length} column issue(s): `+t.map(n=>`${n.column} (${n.reason})`).join(", ")),this.issues=t}};Z.DataFixColumnsInvalidError=Ev;var Av=class extends yt{constructor(t,n,r,i,o,a){super("UPSERT_OUTCOME_UNKNOWN",o),this.entityLogicalName=t,this.key=n,this.statusCode=r,this.serverCode=i,NO(this,a)}};Z.UpsertOutcomeUnknownError=Av;var Cv=class extends yt{constructor(t){super(t.code,t.message),this.problem=t}};Z.PromotionError=Cv});var ae=C(pn=>{"use strict";Object.defineProperty(pn,"__esModule",{value:!0});pn.odataQuery=pn.normalizeGuid=pn.createSafeXmlElement=pn.assertNoControlChars=pn.assertODataName=pn.assertXmlName=pn.xmlText=pn.odataPathLiteral=pn.odataLiteral=void 0;var ph=Y();function _O(e){return String(e??"").replace(/'/g,"''")}pn.odataLiteral=_O;function _6(e){return encodeURIComponent(_O(e))}pn.odataPathLiteral=_6;function I6(e){return String(e??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}pn.xmlText=I6;function IO(e,t){let n=String(e??""),r=/^[A-Za-z_][0-9A-Za-z_.-]*$/,i=n.split(":");if(!(i.length<=2&&i.every(a=>r.test(a))&&!/^xmlns/i.test(n)))throw new ph.InvalidArgumentError(`${t} must be a valid XML element name (got '${e}')`);return e}pn.assertXmlName=IO;function T6(e,t){let n=String(e??"");if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(n))throw new ph.InvalidArgumentError(`${t} must be a valid OData identifier (letters, digits, underscore): got '${e}'`);return e}pn.assertODataName=T6;function O6(e,t){if(/[\u0000-\u001F\u007F]/.test(String(e??"")))throw new ph.InvalidArgumentError(`${t} must not contain control characters (including CR/LF): they would inject additional lines into the request`);return e}pn.assertNoControlChars=O6;function D6(e,t,n){return e.createElement(IO(t,n))}pn.createSafeXmlElement=D6;var P6=/^[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 R6(e,t){let n=String(e??""),r=n.length===38&&n.startsWith("{")&&n.endsWith("}")?n.slice(1,-1):n;if(!P6.test(r))throw new ph.InvalidArgumentError(`${t} must be a valid GUID (got '${e}')`);return r.toLowerCase()}pn.normalizeGuid=R6;function k6(e){let t=[];for(let[n,r]of e)r!=null&&r!==""&&t.push(`${n}=${encodeURIComponent(String(r))}`);return t.length>0?`?${t.join("&")}`:""}pn.odataQuery=k6});var pe=C(K=>{"use strict";Object.defineProperty(K,"__esModule",{value:!0});K.throttleDelayMs=K.THROTTLE_FALLBACK_DELAY_MS=K.isServiceProtectionRefusal=K.SERVICE_PROTECTION_CODES=K.nowIso=K.isAlreadyDeleted=K.deleteRecord=K.extractErrorMessage=K.resendAppSearchIndexRace=K.resendDeadlockVictim=K.resendWhile=K.sleep=K.isAppSearchIndexRace=K.namesAppSearchIndexRace=K.isTransactionNotStarted=K.TRANSACTION_NOT_STARTED_CODE=K.LOCK_BACKOFF_MS=K.isConcurrencyLockRefusalError=K.isConcurrencyLockRefusal=K.CONCURRENCY_LOCK_CODE=K.AMBIGUOUS_WRITE_STATUSES=K.DEADLOCK_BACKOFF_MS=K.isSqlDeadlockVictim=K.ensureSuccess=K.resolveCreatedId=K.requireCreatedId=K.withClientMintedId=K.readCreatedId=K.readRowEtag=K.readEtag=K.requireEtag=K.isVersionToken=K.echoWrite=K.DELETE_NO_ETAG_CODE=K.UPDATE_NO_ETAG_CODE=K.VERSION_CONFLICT_CODE=void 0;var Mu=Y(),Xl=ae();K.VERSION_CONFLICT_CODE="VERSION_CONFLICT";K.UPDATE_NO_ETAG_CODE="ARTIFACT_UPDATE_NO_ETAG";K.DELETE_NO_ETAG_CODE="ARTIFACT_DELETE_NO_ETAG";function $6(e,t){return{query:`?$select=${encodeURIComponent(e)}`,options:{headers:{...t??{},Prefer:"return=representation"}}}}K.echoWrite=$6;function TO(e){return typeof e=="string"&&e.trim()!==""&&e.trim()!=="*"}K.isVersionToken=TO;function L6(e,t,n){if(!TO(e))throw new Mu.SdkError(K.UPDATE_NO_ETAG_CODE,`Refusing to push ${t} '${n}': ${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}K.requireEtag=L6;function OO(e){var t;let n=(t=e.headers)!==null&&t!==void 0?t:{};for(let i of Object.keys(n))if(i.toLowerCase()==="etag")return n[i];let r=e.body;return r&&typeof r["@odata.etag"]=="string"?r["@odata.etag"]:null}K.readEtag=OO;async function M6(e,t,n,r){let i=`/${t}(${r})${(0,Xl.odataQuery)([["$select",n]])}`;return OO(_v(await e.get(i),e.apiUrl(i)))}K.readRowEtag=M6;function Nv(e,t){var n;let r=e.body;if(r&&typeof r[t]=="string")return(0,Xl.normalizeGuid)(r[t],t);let i=(n=e.headers)!==null&&n!==void 0?n:{};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,Xl.normalizeGuid)(a[1],t)}return null}K.readCreatedId=Nv;function x6(e,t,n){return n?{...e,[t]:(0,Xl.normalizeGuid)(n,t)}:e}K.withClientMintedId=x6;function F6(e,t,n){let r=Nv(e,t);if(!r)throw new Mu.InvalidArgumentError(`Dataverse did not return an id for the created ${n}`);return r}K.requireCreatedId=F6;function U6(e,t,n,r){let i=Nv(e,t);if(i)return i;if(r)return(0,Xl.normalizeGuid)(r,t);throw new Mu.InvalidArgumentError(`Dataverse did not return an id for the created ${n}`)}K.resolveCreatedId=U6;function _v(e,t){if(e.status===412)throw new Mu.SdkError(K.VERSION_CONFLICT_CODE,`Version conflict (412) from ${t}`);if(e.status<200||e.status>=300)throw new Mu.ConnectionError(t,e.status,LO(e.body),e.body);return e}K.ensureSuccess=_v;function DO(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)}K.isSqlDeadlockVictim=DO;K.DEADLOCK_BACKOFF_MS=[1e3,2e3,4e3];K.AMBIGUOUS_WRITE_STATUSES=new Set([408,502,503,504]);K.CONCURRENCY_LOCK_CODE="0x80071151";function PO(e){var t,n;if(e.status!==429)return!1;let r=(n=(t=e.body)===null||t===void 0?void 0:t.error)===null||n===void 0?void 0:n.code;return typeof r=="string"&&r.toLowerCase()===K.CONCURRENCY_LOCK_CODE}K.isConcurrencyLockRefusal=PO;function q6(e){return e instanceof Mu.ConnectionError&&e.statusCode===429&&PO({status:429,headers:{},body:e.cause})}K.isConcurrencyLockRefusalError=q6;K.LOCK_BACKOFF_MS=[2e3,3e3,...Array.from({length:35},()=>5e3)];K.TRANSACTION_NOT_STARTED_CODE="0x80040251";function B6(e){var t,n;if(e.status!==500)return!1;let r=(n=(t=e.body)===null||t===void 0?void 0:t.error)===null||n===void 0?void 0:n.code;return typeof r=="string"&&r.toLowerCase()===K.TRANSACTION_NOT_STARTED_CODE}K.isTransactionNotStarted=B6;var V6=/(?:^|[^a-z0-9_])AppModule_DVTableSearch_M365AppModuleId(?![a-z0-9_])/i;function RO(e){return V6.test(e)&&/\bSql Number:\s*547\b/i.test(e)}K.namesAppSearchIndexRace=RO;function kO(e){return e.status!==400||e.body===void 0||e.body===null?!1:RO(typeof e.body=="string"?e.body:JSON.stringify(e.body))}K.isAppSearchIndexRace=kO;function $O(e){return new Promise(t=>setTimeout(t,e))}K.sleep=$O;async function Iv(e,t,n=K.DEADLOCK_BACKOFF_MS){for(let r=0;;r+=1){let i=await t();if(r>=n.length||!e(i))return i;await $O(n[r])}}K.resendWhile=Iv;function G6(e){return Iv(DO,e,K.DEADLOCK_BACKOFF_MS)}K.resendDeadlockVictim=G6;function j6(e){return Iv(kO,e,K.DEADLOCK_BACKOFF_MS)}K.resendAppSearchIndexRace=j6;function LO(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"}K.extractErrorMessage=LO;async function W6(e,t,n,r){let i=(0,Xl.normalizeGuid)(n,"id"),o=`/${t}(${i})`;_v(await e.delete(o,r?{headers:{"If-Match":r}}:void 0),e.apiUrl(o))}K.deleteRecord=W6;function z6(e){return e instanceof Mu.ConnectionError&&e.statusCode===404}K.isAlreadyDeleted=z6;function H6(){return new Date().toISOString()}K.nowIso=H6;K.SERVICE_PROTECTION_CODES=new Set(["0x80072322","0x80072321","0x80072326"]);function K6(e){var t,n;if(e.status!==429)return!1;let r=(n=(t=e.body)===null||t===void 0?void 0:t.error)===null||n===void 0?void 0:n.code;return typeof r=="string"&&K.SERVICE_PROTECTION_CODES.has(r.toLowerCase())}K.isServiceProtectionRefusal=K6;K.THROTTLE_FALLBACK_DELAY_MS=5e3;function J6(e){var t;let n=(t=e.headers)!==null&&t!==void 0?t:{},r=Object.keys(n).find(o=>o.toLowerCase()==="retry-after"),i=r===void 0?"":String(n[r]).trim();return/^\d+$/.test(i)?Math.max(Number(i),1)*1e3:K.THROTTLE_FALLBACK_DELAY_MS}K.throttleDelayMs=J6});var Ke=C(Un=>{"use strict";Object.defineProperty(Un,"__esModule",{value:!0});Un.describeMalformedValue=Un.boundedPageComplete=Un.pageEnd=Un.moreRecordsClaim=Un.MORE_RECORDS_ANNOTATION=Un.continuePages=Un.collectPages=void 0;var MO=pe(),Tv=Y();async function Y6(e,t,n,r,i){let o=e.apiUrl(t),a=(0,MO.ensureSuccess)(await e.get(t,i),o);return r?.(a),xO(e,a,o,n,i)}Un.collectPages=Y6;async function xO(e,t,n,r,i){let o=[],a=new Set,s=n,u=t;for(;;){let l=u.body,c=l?.value;if(!Array.isArray(c))throw new Tv.ConnectionError(s,u.status,`${r}: paginated read returned a malformed page \u2014 expected an OData 'value' array but got ${mh(c)}; refusing to return partial results.`);for(let p of c)o.push(p);let d=Ov(l);if(d.kind==="end")break;if(d.kind==="incomplete")throw new Tv.ConnectionError(s,u.status,`${r}: paginated read returned ${d.why}; cannot read the rest, and refusing to return partial results.`);let f=d.link;if(a.has(f))throw new Tv.InvalidArgumentError(`${r}: aborting pagination \u2014 the server returned a repeated @odata.nextLink ('${f}'), which would loop indefinitely.`);a.add(f),s=f,u=(0,MO.ensureSuccess)(await e.getAbsolute(f,i),f)}return o}Un.continuePages=xO;Un.MORE_RECORDS_ANNOTATION="@Microsoft.Dynamics.CRM.morerecords";function FO(e,t=""){let n=e!==null&&typeof e=="object"?e[`${t}${Un.MORE_RECORDS_ANNOTATION}`]:void 0;return n==null||n===!1?"none":n===!0?"more":"malformed"}Un.moreRecordsClaim=FO;function Ov(e,t=""){let n=e!==null&&typeof e=="object"?e:{},r=`${t}@odata.nextLink`,i=n[r];if(i!=null)return typeof i=="string"&&i.length>0?{kind:"next",link:i}:{kind:"incomplete",cause:"link",why:`a malformed ${r} (${mh(i)})`};let o=`${t}${Un.MORE_RECORDS_ANNOTATION}`,a=FO(n,t);return a==="none"?{kind:"end"}:{kind:"incomplete",cause:"claim",why:a==="more"?`a page that says more rows exist (${o}) but gives no ${r} to read them`:`a malformed ${o} (${mh(n[o])})`}}Un.pageEnd=Ov;function Q6(e,t,n=1){return t>=n||Ov(e).kind==="end"}Un.boundedPageComplete=Q6;function mh(e){return e===null?"null":e===void 0?"undefined (missing)":`a ${typeof e}`}Un.describeMalformedValue=mh});var Dv=C(Fu=>{"use strict";Object.defineProperty(Fu,"__esModule",{value:!0});Fu.assertWorkflowKind=Fu.WORKFLOW_KIND_MISMATCH_CODE=void 0;var xu=Ds(),X6=Y(),UO=pe(),Z6=ae();Fu.WORKFLOW_KIND_MISMATCH_CODE="WORKFLOW_KIND_MISMATCH";var qO={[xu.WorkflowCategory.Workflow]:"classic workflow",[xu.WorkflowCategory.Dialog]:"dialog",[xu.WorkflowCategory.BusinessRule]:"business rule",[xu.WorkflowCategory.Action]:"custom action",[xu.WorkflowCategory.BusinessProcessFlow]:"business process flow",[xu.WorkflowCategory.Flow]:"cloud flow",[xu.WorkflowCategory.UIFlow]:"desktop flow"};async function eH(e,t,n){var r,i;let o=`/workflows(${t})${(0,Z6.odataQuery)([["$select","category"]])}`,a=await e.get(o);if(a.status===404)return null;(0,UO.ensureSuccess)(a,e.apiUrl(o));let s=(r=a.body)===null||r===void 0?void 0:r.category,u=typeof s=="number"?s:typeof s=="string"&&s!==""?Number(s):NaN;if(u!==n){let l=Number.isFinite(u)?`a ${(i=qO[u])!==null&&i!==void 0?i:"process"} (category ${u})`:"a process whose category could not be read";throw new X6.SdkError(Fu.WORKFLOW_KIND_MISMATCH_CODE,`Refusing to delete workflow '${t}' as a ${qO[n]}: it is ${l}. Nothing was changed. Check the id.`)}return(0,UO.readEtag)(a)}Fu.assertWorkflowKind=eH});var Rv=C(Ui=>{"use strict";Object.defineProperty(Ui,"__esModule",{value:!0});Ui.deleteWorkflowResending=Ui.isWorkflowDeleteUnsettled=Ui.failedAfterResend=Ui.WORKFLOW_DELETE_UNSETTLED_CODE=void 0;var bf=Y(),ka=pe(),VO=ae();Ui.WORKFLOW_DELETE_UNSETTLED_CODE="WORKFLOW_DELETE_UNSETTLED";var GO=new WeakSet;function Pv(e){return typeof e=="object"&&e!==null&&GO.add(e),e}function tH(e){return typeof e=="object"&&e!==null&&GO.has(e)}Ui.failedAfterResend=tH;function nH(e){return e instanceof bf.SdkError&&e.code===Ui.WORKFLOW_DELETE_UNSETTLED_CODE}Ui.isWorkflowDeleteUnsettled=nH;function rH(e,t){try{(0,ka.ensureSuccess)(e,t)}catch(n){return n}}function iH(e){return(0,ka.isSqlDeadlockVictim)(e)?"lost a SQL deadlock (HTTP 500, Sql Number 1205)":`lost its transaction (HTTP 500 ${ka.TRANSACTION_NOT_STARTED_CODE})`}async function BO(e,t){try{return(await e.get(`/workflows(${t})${(0,VO.odataQuery)([["$select","workflowid"]])}`)).status===404}catch{return!1}}async function oH(e,t,{bindingToken:n,kindName:r,deactivated:i=!1,resendDeadlockVictim:o=!1,ifMatchOnFirst:a=!1}){let s=(0,VO.normalizeGuid)(t,"id");if(a&&!n)throw new bf.InvalidArgumentError(`Refusing to delete ${r} '${s}': its delete must be conditional on a token this operation holds, and it holds none.`);let u=`/workflows(${s})`,l=e.apiUrl(u),c=m=>(0,ka.isTransactionNotStarted)(m)||o&&(0,ka.isSqlDeadlockVictim)(m),d=0,f,p;try{p=await(0,ka.resendWhile)(c,async()=>{d+=1;let m=d>1||a,h=await e.delete(u,m?{headers:{"If-Match":n}}:void 0);return f=f??h,h},n?ka.DEADLOCK_BACKOFF_MS:[])}catch(m){if(m instanceof bf.ConnectionError&&m.statusCode===0&&n&&await BO(e,s))return;throw d>1?Pv(m):m}if(!(d>1&&p.status===404)){if(d>1&&p.status===412){let m=iH(f),h=new bf.SdkError(Ui.WORKFLOW_DELETE_UNSETTLED_CODE,`Deleting ${r} '${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 Pv((0,bf.attachCause)(h,rH(f,l)))}if(!(n&&ka.AMBIGUOUS_WRITE_STATUSES.has(p.status)&&await BO(e,s)))try{(0,ka.ensureSuccess)(p,l)}catch(m){throw d>1?Pv(m):m}}}Ui.deleteWorkflowResending=oH});var qi=C(fr=>{"use strict";Object.defineProperty(fr,"__esModule",{value:!0});fr.existsByKey=fr.observeIfMatch=fr.readRowToken=fr.compareTokens=fr.failedReadStatus=fr.failureDetail=fr.planPushThrough=void 0;var hh=Y(),jO=pe(),kv=ae(),$v=class{constructor(t){this.sink=t,this.warnings=[]}observe(t){this.sink(t)}warn(t,n){this.warnings.push({code:t,message:n})}async reached(t,n){let r=n?await n():void 0;return this.projection={...t,...r!==void 0?{existence:r}:{}},{id:"",etag:null}}};async function aH(e,t,n,r){let i=new $v(r);if(n.held?await e.update(t,n.id,n.payload,n.held.etag,n.held.memberEtags,n.held.siblingEtags,i):await e.create(t,n.payload,n.id,i),!i.projection)throw new hh.SdkError("PREVIEW_PLAN_INCOMPLETE","A pre-push check ran a write path that returned without reaching its first write. This is a defect in the SDK.");return i.warnings.length>0?{...i.projection,warnings:i.warnings}:i.projection}fr.planPushThrough=aH;function Lv(e){return e instanceof hh.ConnectionError?`HTTP ${e.statusCode}: ${e.message}`:e instanceof hh.SdkError?`${e.code}: ${e.message}`:e instanceof Error?e.message:String(e)}fr.failureDetail=Lv;function sH(e){return e instanceof hh.ConnectionError&&e.statusCode===404?"goneOnServer":"readFailed"}fr.failedReadStatus=sH;function WO(e,t){return(0,jO.isVersionToken)(e)?typeof t!="string"||t===""?"missingServer":e===t?"equal":"different":"missingHeld"}fr.compareTokens=WO;async function zO(e,t){let n=`/${t.entitySet}(${t.id})${(0,kv.odataQuery)([["$select",t.idColumn]])}`,r;try{r=await e.get(n,t.headers?{headers:{...t.headers}}:void 0)}catch(i){return{kind:"failed",detail:Lv(i)}}return r.status===404?{kind:"notFound"}:r.status<200||r.status>=300?{kind:"failed",detail:`HTTP ${r.status}`}:{kind:"token",token:(0,jO.readEtag)(r)}}fr.readRowToken=zO;async function uH(e,t,n){var r;let i=await zO(e,n),o={guard:"ifMatch",componentName:n.componentName,componentId:n.id,held:(r=n.held)!==null&&r!==void 0?r:null};return i.kind==="notFound"?t.observe({...o,status:"goneOnServer",detail:"HTTP 404"}):i.kind==="failed"?t.observe({...o,status:"readFailed",detail:i.detail}):t.observe({...o,server:i.token,status:WO(n.held,i.token)}),i}fr.observeIfMatch=uH;async function lH(e,t,n){var r;let i=(0,kv.normalizeGuid)(n.id,n.key),o=`${n.collection}${(0,kv.odataQuery)([["$select",n.key],["$filter",`${n.key} eq ${i}`]])}`,a={guard:"existence",componentName:n.componentName,componentId:i};try{let s=await e.get(o,n.headers?{headers:{...n.headers}}:void 0),u=(r=s.body)===null||r===void 0?void 0:r.value;if(s.status>=200&&s.status<300&&Array.isArray(u))return t.observe({...a,status:u.length===0?"absent":"present"}),u.length===0?"absent":"present";t.observe({...a,status:"readFailed",detail:`HTTP ${s.status}`})}catch(s){t.observe({...a,status:"readFailed",detail:Lv(s)})}return"unread"}fr.existsByKey=lH});var Mv=C(po=>{"use strict";Object.defineProperty(po,"__esModule",{value:!0});po.businessRuleApi=po.BUSINESS_RULE_LEFT_DEACTIVATED_CODE=po.WFOM_API_UNAVAILABLE_CODE=void 0;var jo=Ds(),cH=Ke(),dH=Dv(),fH=Rv(),yh=qi(),er=pe(),$a=ae(),bh=Y();po.WFOM_API_UNAVAILABLE_CODE="BUSINESS_RULE_API_UNAVAILABLE";po.BUSINESS_RULE_LEFT_DEACTIVATED_CODE="BUSINESS_RULE_LEFT_DEACTIVATED";async function HO(e,t,n,r){let i=`/workflows(${hH})/Microsoft.Dynamics.CRM.${t}`;try{return(0,er.ensureSuccess)(await e.post(i,{Entity:n.Entity,WfomJson:n.WfomJson},{headers:r}),e.apiUrl(i))}catch(o){throw o?.statusCode!==404?o:new bh.SdkError(po.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 pH(e,t,n){let r=`/workflows(${t})${(0,$a.odataQuery)([["$select","workflowid,statecode,statuscode"]])}`;try{let i=await e.get(r);if(i.status<200||i.status>=300)return n?.(`HTTP ${i.status}`,i.status===404),null;let o=i.body;return{etag:(0,er.readEtag)(i),statecode:typeof o?.statecode=="number"?o.statecode:null,statuscode:typeof o?.statuscode=="number"?o.statuscode:null}}catch(i){return n?.((0,yh.failureDetail)(i),!1),null}}async function mH(e,t,n,r){let i={guard:"rowToken",componentName:"Workflow",componentId:t,held:n},o=await pH(e,t,r?(a,s)=>r.observe({...i,status:s?"goneOnServer":"readFailed",detail:a}):void 0);if(o!==null&&r?.observe({...i,server:o.etag,status:(0,yh.compareTokens)(n,o.etag)}),o===null||o.etag===null)throw new bh.SdkError(er.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(o.etag!==n)throw new bh.SdkError(er.VERSION_CONFLICT_CODE,`Version conflict updating business rule '${t}': it changed on the server since it was fetched (held ${n}, server ${o.etag}). Re-fetch the rule and re-apply the change.`);return{statecode:o.statecode,statuscode:o.statuscode}}var hH="00000000-0000-0000-0000-000000000000",gh={"Content-Type":"application/json",Accept:"application/json","OData-Version":"4.0","OData-MaxVersion":"4.0"},gH="workflowid,name,description,primaryentity,statecode,category,type",yH="category eq 2 and type eq 1";async function KO(e,t,n){var r;if(n==="Draft")return null;let i=(0,$a.normalizeGuid)(t,"workflowid"),o=n==="Active",a={statecode:o?jo.StateCode.Activated:jo.StateCode.Draft,statuscode:o?jo.StatusCode.Activated:jo.StatusCode.Draft},s=`/workflows(${i})`,u=(0,er.ensureSuccess)(await e.patch(s,a,{headers:gh}),e.apiUrl(s));return(r=(0,er.readEtag)(u))!==null&&r!==void 0?r:await vf(e,i)}async function vf(e,t){let n=`/workflows(${t})${(0,$a.odataQuery)([["$select","workflowid"]])}`;try{let r=await e.get(n);return r.status>=200&&r.status<300?(0,er.readEtag)(r):null}catch{return null}}async function bH(e,t,n){let r=await vf(e,t),i=await n(),o=(0,er.readEtag)(i);if(o)return{response:i,etag:o};let a=await vf(e,t);return{response:i,etag:r!==null&&r===a?a:null}}po.businessRuleApi={async get(e,t){let n=(0,$a.normalizeGuid)(t,"id"),r=`/workflows(${n})/Microsoft.Dynamics.CRM.RetrieveProcessWithWfomJson`,{response:i,etag:o}=await bH(e,n,async()=>(0,er.ensureSuccess)(await e.get(r),e.apiUrl(r)));return{raw:i.body,etag:o}},async list(e,t){let n=[yH];t?.entityLogicalName&&n.push(`primaryentity eq '${(0,$a.odataLiteral)(t.entityLogicalName)}'`);let r=`/workflows${(0,$a.odataQuery)([["$select",gH],["$filter",n.join(" and ")]])}`;return(await(0,cH.collectPages)(e,r,"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,n=void 0,r){var i;let o=t,a=(0,$a.normalizeGuid)(o.Entity.workflowid,"workflowid");if(r)return r.reached({effects:[{componentName:"Workflow",componentId:a,identity:"known",operation:"create"}],attemptsWrite:!0},()=>(0,yh.existsByKey)(e,r,{collection:"/workflows",key:"workflowid",id:a,componentName:"Workflow"}));let s=await HO(e,"CreateProcessWithWfomJson",o,gh),u=(0,er.resolveCreatedId)(s,"workflowid","business rule",a),l=null;try{l=await KO(e,u,o.status)}catch(c){try{await(0,er.deleteRecord)(e,"workflows",u)}catch{}throw c}return{id:u,etag:(i=l??(0,er.readEtag)(s))!==null&&i!==void 0?i:await vf(e,u)}},async update(e,t,n,r,i=void 0,o,a){var s,u;let l=n,c=(0,$a.normalizeGuid)(t,"id"),d=`/workflows(${c})`;a&&!(0,er.isVersionToken)(r)&&a.observe({guard:"rowToken",componentName:"Workflow",componentId:c,held:r,status:"missingHeld"});let f={...gh,"If-Match":(0,er.requireEtag)(r,"business rule",c)},p=await mH(e,c,f["If-Match"],a);if(a)return a.reached({effects:[{componentName:"Workflow",componentId:c,identity:"known",operation:"update"}],attemptsWrite:!0});let m=p.statecode===jo.StateCode.Activated;m&&(0,er.ensureSuccess)(await e.patch(d,{statecode:jo.StateCode.Draft,statuscode:jo.StatusCode.Draft},{headers:f}),e.apiUrl(d));let h;try{h=await HO(e,"UpdateProcessWithWfomJson",l,f)}catch(y){if(m)try{(0,er.ensureSuccess)(await e.patch(d,{statecode:jo.StateCode.Activated,statuscode:(s=p.statuscode)!==null&&s!==void 0?s:jo.StatusCode.Activated},{headers:gh}),e.apiUrl(d))}catch(b){throw new bh.SdkError(po.BUSINESS_RULE_LEFT_DEACTIVATED_CODE,`The business-rule write failed AND the rule could not be re-activated, so '${c}' is left DEACTIVATED (Draft) on the server. Re-activate it before relying on it. Original write failure: ${y instanceof Error?y.message:String(y)}. Restore failure: ${b instanceof Error?b.message:String(b)}`)}throw y}let g=await KO(e,c,l.status);return{id:c,etag:(u=g??(0,er.readEtag)(h))!==null&&u!==void 0?u:await vf(e,c)}},planPush(e,t,n){return(0,yh.planPushThrough)(po.businessRuleApi,e,t,n)},async delete(e,t){let n=(0,$a.normalizeGuid)(t,"id"),r=await(0,dH.assertWorkflowKind)(e,n,jo.WorkflowCategory.BusinessRule);return(0,fH.deleteWorkflowResending)(e,n,{bindingToken:r,kindName:"business rule"})}}});var mo=C(mn=>{"use strict";Object.defineProperty(mn,"__esModule",{value:!0});mn.publishBoundEntity=mn.boundEntityPublishScope=mn.publishGenPageById=mn.publishDashboardById=mn.publishWebResourceById=mn.publishEntity=mn.appModulePublishParameterXml=mn.publishAppModule=mn.publishXml=void 0;var JO=pe(),wf=ae(),YO="/PublishXml";async function Zl(e,t){(0,JO.ensureSuccess)(await(0,JO.resendDeadlockVictim)(()=>e.post(YO,{ParameterXml:t})),e.apiUrl(YO))}mn.publishXml=Zl;function vH(e,t){return Zl(e,QO(t))}mn.publishAppModule=vH;function QO(e){return`<importexportxml><appmodules><appmodule>${(0,wf.xmlText)(e)}</appmodule></appmodules></importexportxml>`}mn.appModulePublishParameterXml=QO;function XO(e,t){return Zl(e,`<importexportxml><entities><entity>${(0,wf.xmlText)(t)}</entity></entities></importexportxml>`)}mn.publishEntity=XO;function wH(e,t){return Zl(e,`<importexportxml><webresources><webresource>${(0,wf.xmlText)(t)}</webresource></webresources></importexportxml>`)}mn.publishWebResourceById=wH;function EH(e,t){return Zl(e,`<importexportxml><dashboards><dashboard>${(0,wf.xmlText)(t)}</dashboard></dashboards></importexportxml>`)}mn.publishDashboardById=EH;function AH(e,t){return Zl(e,`<importexportxml><uxagentprojects><uxagentproject>${(0,wf.xmlText)(t)}</uxagentproject></uxagentprojects></importexportxml>`)}mn.publishGenPageById=AH;function CH(e){let t=e?.entityLogicalName;return t?{envelope:"entity",entityLogicalName:t,blastRadiusWarning:"ENTITY_ENVELOPE_ALSO_SHIPS_UNRELATED_UNPUBLISHED_CHANGES"}:{envelope:"entity"}}mn.boundEntityPublishScope=CH;function SH(e,t){let n=t?.entityLogicalName;return n?XO(e,n):Promise.resolve()}mn.publishBoundEntity=SH});var ec=C(wh=>{"use strict";Object.defineProperty(wh,"__esModule",{value:!0});wh.JsonPointer=void 0;var Ii=Y(),vh=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 Ii.JsonPointerError(t,'non-empty pointers must start with "/"');return t.substring(1).split("/").map(n=>{if(/~(?![01])/.test(n))throw new Ii.JsonPointerError(t,`invalid '~' escape in token '${n}' (expected ~0 or ~1)`);return e.decodeToken(n)})}static compile(t){return t.length===0?"":"/"+t.map(n=>e.encodeToken(n)).join("/")}static resolve(t,n){let r=e.parse(n),i=t;for(let o of r)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,n,r){let i=e.parse(n);if(i.length===0)throw new Ii.JsonPointerError(n,"cannot set the document root");let{parent:o,lastToken:a}=e.resolveParent(t,i,n);if(Array.isArray(o)){let s=e.toArrayIndex(a,o.length);if(s===void 0)throw new Ii.JsonPointerError(n,`'${a}' is not a valid array index`);if(s>o.length)throw new Ii.JsonPointerError(n,`array index '${a}' is out of range`);o[s]=r}else{if(e.isReservedToken(a))throw new Ii.JsonPointerError(n,`refusing to write reserved property '${a}'`);o[a]=r}}static remove(t,n){let r=e.parse(n);if(r.length===0)throw new Ii.JsonPointerError(n,"cannot remove the document root");let{parent:i,lastToken:o}=e.resolveParent(t,r,n);if(Array.isArray(i)){let a=e.toArrayIndex(o,i.length);if(a===void 0||a>=i.length)throw new Ii.JsonPointerError(n,`array index '${o}' is out of range`);i.splice(a,1)}else{if(e.isReservedToken(o))throw new Ii.JsonPointerError(n,`refusing to remove reserved property '${o}'`);delete i[o]}}static add(t,n,r,i){let o=e.parse(n);if(o.length>0&&o[o.length-1]==="-"){let u=e.compile(o.slice(0,-1)),l=e.resolve(t,u);if(!Array.isArray(l))throw new Ii.JsonPointerError(n,"add target must be an array");l.push(r);return}let a=e.resolve(t,n);if(!Array.isArray(a))throw new Ii.JsonPointerError(n,"add target must be an array");let s=i===void 0?a.length:i;if(s<0||s>a.length)throw new Ii.JsonPointerError(n,`insert index ${s} is out of range`);a.splice(s,0,r)}static parent(t){let n=e.parse(t);return n.pop(),e.compile(n)}static lastToken(t){let n=e.parse(t);return n.length===0?"":n[n.length-1]}static append(t,n){return`${t}/${e.encodeToken(String(n))}`}static resolveParent(t,n,r){let i=n[n.length-1],o=e.compile(n.slice(0,-1)),a=e.resolve(t,o);if(a===null||typeof a!="object")throw new Ii.JsonPointerError(r,"parent path does not resolve to an object or array");return{parent:a,lastToken:i}}static toArrayIndex(t,n){if(t==="-")return n;if(/^(0|[1-9][0-9]*)$/.test(t))return Number(t)}};wh.JsonPointer=vh;vh.RESERVED_TOKENS=new Set(["__proto__","prototype","constructor"])});var eD=C(Eh=>{"use strict";Object.defineProperty(Eh,"__esModule",{value:!0});Eh.findElements=void 0;var ZO=ec();function NH(e,t){let n=[];return xv(e,"",t,n),n}Eh.findElements=NH;function xv(e,t,n,r){if(!(e===null||typeof e!="object"))if(n(e,t)&&r.push({pointer:t,value:e}),Array.isArray(e))e.forEach((i,o)=>{xv(i,ZO.JsonPointer.append(t,o),n,r)});else for(let i of Object.keys(e))xv(e[i],ZO.JsonPointer.append(t,i),n,r)}});var Fv=C(Wo=>{"use strict";Object.defineProperty(Wo,"__esModule",{value:!0});Wo.assertMutationResult=Wo.assertExistsResult=Wo.assertReadResult=Wo.assertStorageContract=void 0;var _H=["readText","writeTextAtomic","deleteFile","deleteByPrefix"],IH=["ensureContainer","exists"];function TH(e){if(typeof e!="object"||e===null)throw new Error("workspaceStorage must be an object implementing WorkspaceStorage.");for(let t of _H)if(typeof e[t]!="function")throw new Error(`workspaceStorage is missing the required method '${t}'.`);for(let t of IH){let n=e[t];if(n!==void 0&&typeof n!="function")throw new Error(`workspaceStorage.${t} must be a function when present.`)}return e}Wo.assertStorageContract=TH;function OH(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.`)}Wo.assertReadResult=OH;function DH(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.`)}Wo.assertExistsResult=DH;function PH(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.`)}Wo.assertMutationResult=PH});var Uv=C(tc=>{"use strict";Object.defineProperty(tc,"__esModule",{value:!0});tc.retryTransientIoAsync=tc.retryTransientIo=void 0;var RH=new Set(["EPERM","EACCES","EBUSY","UNKNOWN"]),kH=5,tD=10;function $H(e){for(let t=1;;t+=1)try{return e()}catch(n){if(!nD(n,t))throw n;MH(tD*t)}}tc.retryTransientIo=$H;async function LH(e){for(let t=1;;t+=1)try{return await e()}catch(n){if(!nD(n,t))throw n;await new Promise(r=>setTimeout(r,tD*t))}}tc.retryTransientIoAsync=LH;function nD(e,t){let n=e.code;return t<kH&&!!n&&RH.has(n)}function MH(e){try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)}catch{let t=Date.now()+e;for(;Date.now()<t;);}}});var sD=C(Ti=>{"use strict";Object.defineProperty(Ti,"__esModule",{value:!0});Ti.canonicalArtifactId=Ti.WorkspaceManager=Ti.WORKSPACE_SCHEMA_VERSION=Ti.retryTransientIo=void 0;var pr=Fv(),zo=Y(),xH=Uv();Object.defineProperty(Ti,"retryTransientIo",{enumerable:!0,get:function(){return xH.retryTransientIo}});function rD(e){let t=e;return typeof t.pathFor=="function"&&typeof t.getRoot=="function"?e:null}Ti.WORKSPACE_SCHEMA_VERSION=1;var Ps={form:"forms",view:"views",businessRule:"business-rules",app:"apps",command:"commands",chart:"charts",dashboard:"dashboards",genPage:"gen-pages",bpf:"business-process-flows",environmentVariable:"environment-variables",connectionReference:"connection-references",fieldSecurityProfile:"field-security-profiles",customApi:"custom-apis",duplicateRule:"duplicate-rules"},FH="manifest.json",nc=".metadata",qv="entities";function iD(e){try{return Promise.resolve(e())}catch(t){return Promise.reject(t)}}function Bv(e){if(e.schemaVersion!==void 0&&e.schemaVersion>Ti.WORKSPACE_SCHEMA_VERSION)throw new zo.IncompatibleWorkspaceError(e.schemaVersion,Ti.WORKSPACE_SCHEMA_VERSION)}function oD(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ah(e){return e.trim().toLowerCase().replace(/\/+$/,"")}var Vv=class{withManifest(t){let n=this.manifestQueue.then(t,t);return this.manifestQueue=n.then(()=>{},()=>{}),n}constructor(t,n,r){if(this.workspaceLabel=t,this.instanceUrl=n,this.manifestQueue=Promise.resolve(),this.bound=!1,r==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=r}artifactKey(t,n){return this.assertSafeId(n),[Ps[t],`${Ef(n)}.json`]}metaKey(t,n){return this.assertSafeId(n),[nc,Ps[t],`${Ef(n)}.meta.json`]}entityKey(t){return this.assertSafeId(t),[nc,qv,`${t.toLowerCase()}.json`]}fsStore(){let t=rD(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=rD(this.storage);return t?t.getRoot():this.workspaceLabel}getArtifactDir(t){return this.fsStore().pathFor([Ps[t]])}getArtifactFilePath(t,n){return this.fsStore().pathFor(this.artifactKey(t,n))}getMetaFilePath(t,n){return this.fsStore().pathFor(this.metaKey(t,n))}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 zo.PathTraversalError(String(t),this.workspaceLabel)}get manifestKey(){return[FH]}assertDataKey(t,n){if(!Array.isArray(t)||t.length<2)throw new zo.InvalidArgumentError(`${n} 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(r=>this.assertSafeId(r))}async init(){let t=await this.withManifest(async()=>{let n=await this.readStoredManifest();return n.present&&this.assertBoundHere(n.value),n.present});await this.ensureLayout(),t||await this.withManifest(async()=>{let n=await this.readStoredManifest();if(n.present){this.assertBoundHere(n.value);return}let r={instanceUrl:this.instanceUrl,createdAt:new Date().toISOString(),artifacts:[]};await this.writeManifest(r)}),this.bound=!0}async readStoredManifest(){let t=(0,pr.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),n=[[nc,qv]];for(let i of Object.keys(Ps))n.push([Ps[i]],[nc,Ps[i]]);let r=await Promise.allSettled(n.map(i=>iD(()=>t(i))));for(let i of r){if(i.status==="rejected")throw i.reason;(0,pr.assertMutationResult)(i.value,"ensureContainer")}}async isInitialized(){return this.storage.exists?(0,pr.assertExistsResult)(await this.storage.exists(this.manifestKey),"manifest.json"):(0,pr.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 zo.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,n=>{throw t(),n})}return this.verifying}async readAndCheckBinding(){let t=await this.readStoredManifest();if(!t.present)throw new zo.WorkspaceNotInitializedError(this.workspaceLabel);this.assertBoundHere(t.value),this.bound=!0}assertBoundHere(t){if(!oD(t))throw new zo.WorkspaceOrgMismatchError("",this.instanceUrl);Bv(t);let n=typeof t.instanceUrl=="string"?t.instanceUrl.trim():"",r=Ah(n);if(!r||r!==Ah(this.instanceUrl))throw new zo.WorkspaceOrgMismatchError(n,this.instanceUrl)}async clean(){let t=await this.readStoredManifest();if(!t.present||!oD(t.value))throw new zo.WorkspaceNotInitializedError(this.workspaceLabel);let n=t.value;Bv(n);let r=Object.keys(Ps).map(o=>[Ps[o]]);r.push([nc]);let i=await Promise.allSettled(r.map(o=>iD(()=>this.storage.deleteByPrefix(o))));for(let o of i){if(o.status==="rejected")throw o.reason;(0,pr.assertMutationResult)(o.value,"deleteByPrefix")}await this.ensureLayout(),await this.withManifest(()=>this.writeManifest({...n,instanceUrl:this.instanceUrl,artifacts:[],lastSyncAt:void 0})),this.bound=!0}async readArtifact(t,n){return await this.ensureInitialized(),this.readJsonUnchecked(this.artifactKey(t,n))}async readArtifactWithText(t,n){await this.ensureInitialized();let r=this.artifactKey(t,n),i=(0,pr.assertReadResult)(await this.storage.readText(r),r.join("/"));return i===null?null:{artifact:JSON.parse(i),text:i}}async writeArtifact(t,n,r,i){await this.ensureInitialized();let o=aD(r);if(i!==void 0&&o===i){await this.upsertManifestEntry(t,n,r,{unlessCurrent:!0});return}(0,pr.assertMutationResult)(await this.storage.writeTextAtomic(this.artifactKey(t,n),o),"writeTextAtomic"),await this.upsertManifestEntry(t,n,r)}async deleteArtifact(t,n){await this.ensureInitialized(),(0,pr.assertMutationResult)(await this.storage.deleteFile(this.artifactKey(t,n)),"deleteFile"),(0,pr.assertMutationResult)(await this.storage.deleteFile(this.metaKey(t,n)),"deleteFile");let r=Ef(n);await this.withManifest(async()=>{let i=await this.getManifest();i.artifacts=i.artifacts.filter(o=>!(o.type===t&&o.id===r)),await this.writeManifest(i)})}async readMeta(t,n){return await this.ensureBound(),this.readJsonUnchecked(this.metaKey(t,n))}async writeMeta(t,n,r){await this.ensureBound(),await this.writeJsonUnchecked(this.metaKey(t,n),r)}async listArtifacts(t,n){return await this.ensureInitialized(),(await this.getManifest()).artifacts.filter(r=>!(t&&r.type!==t||n?.entityLogicalName&&r.entityLogicalName!==n.entityLogicalName))}async readEntityMetadata(t){await this.ensureInitialized();let n=await this.readJsonUnchecked(this.entityKey(t));return!n||typeof n.schemaName!="string"||typeof n.primaryNameAttribute!="string"||typeof n.primaryIdAttribute!="string"||typeof n.isCustomEntity!="boolean"?null:n}async writeEntityMetadata(t,n){await this.ensureInitialized(),await this.writeJsonUnchecked(this.entityKey(t),n)}async dropEntityMetadata(t){if(await this.ensureInitialized(),t===void 0){(0,pr.assertMutationResult)(await this.storage.deleteByPrefix([nc,qv]),"deleteByPrefix");return}(0,pr.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 zo.WorkspaceNotInitializedError(this.workspaceLabel);return Bv(t),t}async writeManifest(t){await this.writeJsonUnchecked(this.manifestKey,{...t,schemaVersion:Ti.WORKSPACE_SCHEMA_VERSION})}async updateManifest(t){await this.withManifest(async()=>{let n=await this.getManifest();if(t.instanceUrl!==void 0&&Ah(String(t.instanceUrl))!==Ah(n.instanceUrl))throw new zo.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({...n,...t,instanceUrl:n.instanceUrl})})}async upsertManifestEntry(t,n,r,i={}){await this.withManifest(async()=>{let o=await this.getManifest(),a=Ef(n),s=r,u=typeof s.name=="string"?s.name:`${t}:${a}`,l=typeof s.entityLogicalName=="string"?s.entityLogicalName:void 0,c=o.artifacts.find(d=>d.type===t&&d.id===a);i.unlessCurrent&&c?.name===u&&c.entityLogicalName===l||(c?(c.name=u,c.entityLogicalName=l):o.artifacts.push({type:t,id:a,name:u,entityLogicalName:l,isDirty:!1}),await this.writeManifest(o))})}async readJson(t){return await this.ensureBound(),this.readJsonUnchecked(t)}async writeJson(t,n){this.assertDataKey(t,"writeJson"),await this.ensureBound(),await this.writeJsonUnchecked(t,n)}async removeFile(t){this.assertDataKey(t,"removeFile"),await this.ensureBound(),(0,pr.assertMutationResult)(await this.storage.deleteFile(t),"deleteFile")}async exists(t){return await this.ensureBound(),this.storage.exists?(0,pr.assertExistsResult)(await this.storage.exists(t),t.join("/")):(0,pr.assertReadResult)(await this.storage.readText(t),t.join("/"))!==null}async readJsonUnchecked(t){let n=(0,pr.assertReadResult)(await this.storage.readText(t),t.join("/"));return n===null?null:JSON.parse(n)}async writeJsonUnchecked(t,n){(0,pr.assertMutationResult)(await this.storage.writeTextAtomic(t,aD(n)),"writeTextAtomic")}};Ti.WorkspaceManager=Vv;function aD(e){return`${JSON.stringify(e,null,2)}+`}function Ef(e){let n=/^\{?([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 n?n[1].toLowerCase():e.toLowerCase()}Ti.canonicalArtifactId=Ef});var Rs=C(rc=>{"use strict";Object.defineProperty(rc,"__esModule",{value:!0});rc.deepEqual=rc.deepDiff=void 0;var UH=ec();function qH(e,t){let n=[];return lD(e,t,"",n,0),n}rc.deepDiff=qH;var Ch=Symbol("missing"),Sh=512;function lD(e,t,n,r,i){if(e===t)return;if(i>Sh)throw new RangeError(`deepDiff exceeded the maximum supported depth of ${Sh}`);let o=Nh(e),a=Nh(t);if(o&&a&&Array.isArray(e)===Array.isArray(t)){let s=BH(e,t);for(let u of s){let l=uD(e,u),c=uD(t,u),d=UH.JsonPointer.append(n,u);l===Ch?r.push({pointer:d,type:"added",newValue:c}):c===Ch?r.push({pointer:d,type:"removed",oldValue:l}):lD(l,c,d,r,i+1)}return}cD(e,t)||r.push({pointer:n,type:"modified",oldValue:e,newValue:t})}function Nh(e){return e!==null&&typeof e=="object"}function BH(e,t){if(Array.isArray(e)&&Array.isArray(t)){let r=Math.max(e.length,t.length),i=[];for(let o=0;o<r;o++)i.push(String(o));return i}let n=new Set([...Object.keys(e),...Object.keys(t)]);return Array.from(n)}function uD(e,t){if(Array.isArray(e)){let n=Number(t);return n<e.length?e[n]:Ch}return t in e?e[t]:Ch}function cD(e,t){return dD(e,t,0)}rc.deepEqual=cD;function dD(e,t,n){if(e===t)return!0;if(n>Sh)throw new RangeError(`deepEqual exceeded the maximum supported depth of ${Sh}`);if(!Nh(e)||!Nh(t)||Array.isArray(e)!==Array.isArray(t))return!1;let r=Object.keys(e),i=Object.keys(t);return r.length!==i.length?!1:r.every(o=>o in t&&dD(e[o],t[o],n+1))}});var pD=C(ic=>{"use strict";Object.defineProperty(ic,"__esModule",{value:!0});ic.VersionManager=ic.PROJECTION_VERSION=void 0;var fD=Rs(),VH=pe();ic.PROJECTION_VERSION=9;var Gv=class{constructor(t){this.workspace=t}async storeMeta(t,n,r,i){var o;let a=i===void 0?await this.getMeta(t,n):i,s=((o=r.snapshot)===null||o===void 0?void 0:o.status)==="Active",u=a?.everActivated===!0||s;await this.workspace.writeMeta(t,n,u?{...r,everActivated:u}:r)}async getMeta(t,n){return this.workspace.readMeta(t,n)}async isDirty(t,n,r){let i=await this.workspace.readArtifact(t,n);if(i===null)return!1;let o=r===void 0?await this.getMeta(t,n):r;return o?!(0,fD.deepEqual)(o.snapshot,i):!0}async diff(t,n){let r=await this.workspace.readArtifact(t,n),i=await this.getMeta(t,n),o;return r===null?o=i?[{pointer:"",type:"removed",oldValue:i.snapshot}]:[]:i?o=(0,fD.deepDiff)(i.snapshot,r):o=[{pointer:"",type:"added",newValue:r}],{artifactType:t,artifactId:n,changes:o}}async checkConflict(t,n,r){let i=await this.getMeta(t,n);return!i||!(0,VH.isVersionToken)(i.etag)?!0:i.etag!==r}};ic.VersionManager=Gv});var hD=C((jv,mD)=>{(function(e,t){typeof define=="function"&&define.amd?define([],t):typeof jv=="object"?mD.exports=t():e.compareVersions=t()})(jv,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 n(o){var a=o.replace(/^v/,"").replace(/\+.*$/,""),s=t(a,"-"),u=a.substring(0,s).split(".");return u.push(a.substring(s+1)),u}function r(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 u=n(a),l=n(s),c=0;c<Math.max(u.length-1,l.length-1);c++){var d=parseInt(u[c]||0,10),f=parseInt(l[c]||0,10);if(d>f)return 1;if(f>d)return-1}var p=u[u.length-1],m=l[l.length-1];if(p&&m){var h=p.split(".").map(r),g=m.split(".").map(r);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 wD=C(Jt=>{"use strict";Object.defineProperty(Jt,"__esModule",{value:!0});Jt.EnvironmentFlowHostingType=Jt.EnvironmentDisableReasonCode=Jt.EnvironmentMigrationConstants=Jt.EnvironmentProvisioningStates=Jt.EnvironmentLocations=Jt.EnvironmentCreationTypeConstants=Jt.EnvironmentType=Jt.EnvironmentSkuConstants=Jt.environmentPermissions=Jt.DatabaseType=void 0;var gD;(function(e){e.CommonDataService="CommonDataService",e.None="None"})(gD||(Jt.DatabaseType=gD={}));Jt.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"};Jt.EnvironmentSkuConstants={NotSpecified:"NotSpecified",Standard:"Standard",Premium:"Premium",Developer:"Developer",Basic:"Basic",Production:"Production",Sandbox:"Sandbox",Trial:"Trial",Default:"Default",Teams:"Teams",Platform:"Platform"};var yD;(function(e){e[e.CDS2=0]="CDS2",e[e.CDS1=1]="CDS1",e[e.Empty=2]="Empty"})(yD||(Jt.EnvironmentType=yD={}));Jt.EnvironmentCreationTypeConstants={NotSpecified:"NotSpecified",Legacy:"Legacy",DefaultTenant:"DefaultTenant",User:"User",CommonDataModelLegacy:"CommonDataModelLegacy"};Jt.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"};Jt.EnvironmentProvisioningStates={NotSpecified:"NotSpecified",Succeeded:"Succeeded",Deleting:"Deleting",Deleted:"Deleted",FailedDeleting:"FailedDeleting",LinkedDatabaseProvisioning:"LinkedDatabaseProvisioning",LinkedDatabaseFailedProvisioning:"LinkedDatabaseFailedProvisioning",LinkedDatabaseFailedConfiguring:"LinkedDatabaseFailedConfiguring",LinkedDatabaseUnavailable:"LinkedDatabaseUnavailable",Creating:"Creating"};Jt.EnvironmentMigrationConstants={phases:{completed:"Completed"}};var bD;(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"})(bD||(Jt.EnvironmentDisableReasonCode=bD={}));var vD;(function(e){e.LogicApps="LogicApps",e.SelfHostSingleTenant="SelfHostSingleTenant",e.SelfHostMultiTenant="SelfHostMultiTenant"})(vD||(Jt.EnvironmentFlowHostingType=vD={}))});var TD=C($=>{"use strict";var GH=$&&$.__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 jH=GH(hD()),ct=wD(),Af=zv();function WH(e){let t=Ma(e);return t&&t.version}$.getCrmVersion=WH;function Ma(e){return e&&e.properties&&e.properties.linkedEnvironmentMetadata}$.getLinkedEnvironmentMetadata=Ma;function La(e,t){return e?!!e[t]:!1}$.doesUserHavePermission=La;$.crmBapSolutionId="00000001-0000-0000-0001-00000000009b";$.DEFAULT_SOLUTION_ID="fd140aaf-4df4-11dd-bd17-0019b9312238";$.DEFAULT_SOLUTION_UNIQUE_NAME="Default";function Uu(e){return!!Ma(e)&&ED(e)}$.environmentHasCds2Database=Uu;function zH(e){if(e&&Uu(e)){let t=ks(e);return(0,Af.getCrmAdminSecurityRolesUrl)(t)}return""}$.getSecurityUsersUrl=zH;function HH(e){if(e&&Uu(e)){let t=ks(e);return(0,Af.getCrmAdminSecurityUsersUrl)(t)}return""}$.getSecurityRolesUrl=HH;function KH(e){if(e&&Uu(e)){let t=ks(e);(0,Af.getCrmAllSolutionsUrl)(t)}return""}$.getAllSolutionsUrl=KH;function JH(e){if(e&&Uu(e)){let t=ks(e);return(0,Af.getCrmAllPublishersUrl)(t)}return""}$.getAllPublishersUrl=JH;function YH(e){return e&&Uu(e)?ks(e):""}$.getAllThemesUrl=YH;function ED(e){return!!e&&e.properties&&!!e.properties.provisioningState&&e.properties.provisioningState.toUpperCase()===ct.EnvironmentProvisioningStates.Succeeded.toUpperCase()}$.isEnvironmentInSuccessfulState=ED;function QH(e){if(e&&Uu(e)){let t=ks(e);return(0,Af.getCrmDevResourcesUrl)(t)}return""}$.getDevResourcesUrl=QH;function XH(e){return`${e}designer/app/{${$.crmBapSolutionId}}/CreateNewApp}}`}$.getCrmAppDesignerUrl=XH;function ks(e){let t=Ma(e);if(t){let n=t.instanceUrl;return n?n.endsWith("/")?n:n+"/":""}return""}$.getCrmInstanceUrl=ks;function ZH(e){let t=Ma(e);return t?t.uniqueName:""}$.getCrmInstanceName=ZH;function e7(e){return Ma(e)?ct.EnvironmentType.CDS2:e&&e.properties&&e.properties.namespace?ct.EnvironmentType.CDS1:ct.EnvironmentType.Empty}$.getEnvironmentType=e7;function t7(e){return e&&e.properties&&e.properties.environmentSku===ct.EnvironmentSkuConstants.Developer}$.isDevEnvironment=t7;function n7(e){return e&&e.properties&&e.properties.environmentSku===ct.EnvironmentSkuConstants.Production}$.isProdEnvironment=n7;function r7(e){return e&&e.properties&&e.properties.environmentSku===ct.EnvironmentSkuConstants.Sandbox}$.isSandboxEnvironment=r7;function Cf(e){return e&&e.properties&&e.properties.environmentSku===ct.EnvironmentSkuConstants.Teams}$.isTeamsEnvironment=Cf;function i7(e){return e&&e.properties&&e.properties.environmentSku===ct.EnvironmentSkuConstants.Platform}$.isPlatformEnvironment=i7;var o7=e=>{var t;return((t=e.properties)===null||t===void 0?void 0:t.environmentSku)===ct.EnvironmentSkuConstants.Trial};$.isTrialEnvironment=o7;function a7(e){return e&&e.properties&&(e.properties.isDefault||e.properties.creationType===ct.EnvironmentCreationTypeConstants.DefaultTenant)}$.isDefaultEnvironment=a7;function s7(e){return e&&e.properties&&!!e.properties.states&&!!e.properties.states.runtime&&e.properties.states.runtime.id==="Disabled"}$.isDisabledEnvironment=s7;function u7(e){return e&&e.properties&&La(e.properties.permissions,ct.environmentPermissions.CreateDatabase)}$.canUserCreateDatabase=u7;function l7(e){return!!(e&&e.properties&&e.properties.provisioningState&&ID(e.properties.provisioningState,ct.EnvironmentProvisioningStates.LinkedDatabaseProvisioning))}$.isDatabaseInProvisioningState=l7;function c7(e){return!!e&&!!e.properties&&e.properties.provisioningState===ct.EnvironmentProvisioningStates.Creating}$.isEnvironmentInCreatingState=c7;function d7(e){return e&&e.properties&&(e.properties.provisioningState===ct.EnvironmentProvisioningStates.Deleted||e.properties.provisioningState===ct.EnvironmentProvisioningStates.Deleting||e.properties.provisioningState===ct.EnvironmentProvisioningStates.FailedDeleting)}$.isEnvironmentInDeletedState=d7;function f7(e){return!!e&&!!e.properties&&!!e.properties.expirationTime&&Date.parse(e.properties.expirationTime)<Date.now()}$.isEnvironmentExpired=f7;function p7(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=p7;function m7(e){return!!e&&!!e.properties&&!!e.properties.cluster&&e.properties.cluster.category==="Test"}$.isEnvironmentInTestCluster=m7;function h7(e){return!!e&&!!e.properties&&!!e.properties.cluster&&e.properties.cluster.category==="Preprod"}$.isEnvironmentInPreprodCluster=h7;function g7(e){return!!e&&!!e.properties&&!!e.properties.cluster&&e.properties.cluster.category==="FirstRelease"}$.isEnvironmentInFirstReleaseCluster=g7;function y7(e){return e&&e.name||""}$.getEnvironmentName=y7;function b7(e){return e&&e.properties&&e.properties.displayName||""}$.getEnvironmentDisplayName=b7;var AD="9.1.0.8202";$.cdsVersionSupportingOSColorEdit="9.1.0000.20708";function v7(e){return ND(e,AD)}$.doesCds2EnvironmentSupportApiVersion9_1=v7;function w7(e){return Wv(e,AD)}$.doesCds2VersionSupportApiVersion9_1=w7;function CD(e){let t=Ma(e);if(t)return t.securityGroupId}function SD(e){return e&&e.properties&&e.properties.connectedGroups}function E7(e,t){let n=SD(e);return!!n&&!!n.find(r=>r.id===t)||CD(e)===t}$.hasSecurityGroupId=E7;function A7(e){let t=SD(e);return t&&t.length>0&&t[0].id?t[0].id:CD(e)}$.getSecurityOrConnectedGroupId=A7;function ND(e,t){let n=e.version;return n?Wv(n,t):!1}$.isCds2EnvironmentVersionAtLeast=ND;function Wv(e,t){return t?e?(0,jH.default)(e,t)>=0:!1:!0}$.checkVersions=Wv;function C7(e){return e&&e.properties&&e.properties.updateCadence&&e.properties.updateCadence.id||"NotSpecified"}$.getEnvironmentUpdateCadence=C7;function S7(e){let t=Ma(e);return t?Number(t.baseLanguage):0}$.getEnvironmentLanguageCode=S7;function _D(e){let t=Ma(e);return t?t.instanceApiUrl:void 0}$.getEnvironmentInstanceApiUrl=_D;function N7(e){let t=_D(e);return t?t+"/api/data/v9.2":""}$.getEnvironmentWebApiUrl=N7;function _7(e){let t=ks(e);if(t==="")return"";let n=t.split("/");if(n.length!==4)return"";let r=n[2].split(".");return r[0]="globaldisco",n[2]=r.join("."),n.join("/")+"api/discovery/v2.0/Instances"}$.getEnvironmentDiscoveryUrl=_7;var I7=e=>{var t;return((t=e.properties)===null||t===void 0?void 0:t.databaseType)===ct.DatabaseType.CommonDataService};$.hasCommonDataServiceDatabase=I7;var T7=e=>{var t;return La((t=e.properties)===null||t===void 0?void 0:t.permissions,ct.environmentPermissions.AdminReadEnvironment)};$.doesUserHaveAdminPermission=T7;var O7=e=>{var t;return La((t=e.properties)===null||t===void 0?void 0:t.permissions,ct.environmentPermissions.CreatePowerApp)};$.doesUserHaveCreateAppPermission=O7;var D7=e=>(0,$.doesUserHaveAdminPermission)(e)&&(0,$.hasCommonDataServiceDatabase)(e)?!0:(0,$.doesUserHaveCreateAppPermission)(e)?Cf(e)||(0,$.doesUserHaveDatabaseTablePermissions)(e):!1;$.isUserMakerWithDataAccess=D7;var P7=e=>(0,$.doesUserHaveCreateAppPermission)(e)&&!Cf(e)&&!(0,$.doesUserHaveDatabaseTablePermissions)(e)&&(!(0,$.doesUserHaveAdminPermission)(e)||!(0,$.hasCommonDataServiceDatabase)(e));$.isUserMakerWithoutDataAccess=P7;var R7=e=>[ct.environmentPermissions.CreateDatabaseEntities,ct.environmentPermissions.ListDatabaseEntities,ct.environmentPermissions.UpdateDatabaseEntities,ct.environmentPermissions.DeleteDatabaseEntities].every(t=>{var n;return La((n=e.properties)===null||n===void 0?void 0:n.permissions,t)});$.doesUserHaveDatabaseTablePermissions=R7;var k7=e=>{var t;return La((t=e.properties)===null||t===void 0?void 0:t.permissions,ct.environmentPermissions.CreateDatabase)};$.doesUserHaveCreateDatabasePermission=k7;function ID(e,t){return!e&&!t?!0:!e||!t?!1:e.toUpperCase()===t.toUpperCase()}$.equalsIgnoreCase=ID;var $7=e=>{var t;return La((t=e.properties)===null||t===void 0?void 0:t.permissions,ct.environmentPermissions.CreateFlow)};$.doesUserHaveCreateFlowPermission=$7;var L7=e=>(0,$.doesUserHaveAdminPermission)(e)&&(0,$.hasCommonDataServiceDatabase)(e)?!0:(0,$.doesUserHaveCreateFlowPermission)(e)?Cf(e)||(0,$.doesUserHaveDatabaseTablePermissions)(e):!1;$.isUserPautoMakerWithDataAccess=L7;var M7=e=>(0,$.doesUserHaveCreateFlowPermission)(e)&&!Cf(e)&&!(0,$.doesUserHaveDatabaseTablePermissions)(e)&&(!(0,$.doesUserHaveAdminPermission)(e)||!(0,$.hasCommonDataServiceDatabase)(e));$.isUserPautoMakerWithoutDataAccess=M7;var x7=e=>{var t,n;return!La((t=e.properties)===null||t===void 0?void 0:t.permissions,ct.environmentPermissions.CreateFlow)&&La((n=e.properties)===null||n===void 0?void 0:n.permissions,ct.environmentPermissions.ReadEnvironment)};$.doesUserHaveFlowRunOnlyPermission=x7});var zv=C(P=>{"use strict";Object.defineProperty(P,"__esModule",{value:!0});P.getRequiredComponentsQueryUrl=P.solutionComponentCountSummariesQueryUrl=P.solutionComponentSummariesQueryUrl=P.solutionComponentConfigurationsQueryUrl=P.chartsQueryUrl=P.workflowsQueryUrl=P.entityDefinitionsQueryUrl=P.solutionComponentDefinitionsQueryUrl=P.getCreateNewArticleTemplateUrl=P.getCreateNewPublisherUrl=P.getEnableSecurityRolesUrl=P.getArticleTemplateUrl=P.getFieldSecurityProfileDesignerUrl=P.getSecurityRoleDesignerUrl=P.getMailMergeTemplateDesignerUrl=P.getEmailTemplateDesignerUrl=P.getConnectionRoleDesignerUrl=P.getSiteMapDesignerUrl=P.getWebResourceFileUrl=P.getWebResourceDesignerUrl=P.getReportDesignerUrl=P.getBusinessProcessFlowDesignerUrl=P.getProcessShareUrl=P.getProcessDesignerUrl=P.getChartDesignerUrl=P.getOpenModernEntityDashboardUrl=P.getNewModernEntityDashboardUrl=P.getNewModernDashboardUrl=P.getOpenModernDashboardUrl=P.getDashboardDesignerUrl=P.getAppModuleDesignerUrl=P.privilegesQueryUrls=P.xrmApiUrl=P.getPlayAppModuleUrl=P.getCrmAdminSecurityUsersUrl=P.getCrmAdminSecurityRolesUrl=P.getCrmMyAppsUrl=P.getCrmAppDesignerUrl=P.getCrmDevResourcesUrl=P.getCrmAllPublishersUrl=P.getCrmAllSolutionsUrl=P.getSolutionPublisherUrl=P.getExportTranslationFileName=P.getExportSolutionTranslationUrl=P.getImportSolutionTranslationUrl=P.getShowSolutionDependenciesUrl=P.getShowComponentDependenciesUrl=P.cdsServiceUrl=P.ODATA_NEXT_LINK=P.ODATA_MAX_PAGE_SIZE=void 0;P.retrieveOrganizationResources=P.getUCIEntityRecordEditUrl=P.getUCIEntityRecordBaseUrl=P.getBusinessRuleDesignerUri=P.retrieveUnpublishedSuffix=P.getSavePowerSettingUri=P.getPowerSettingUri=P.getPowerSettingsUri=P.RetrievePlatform=P.getAppSettingOverrideUri=P.AppSettingOverrideName=P.getOrgSettingOverrideUri=P.OrgSettingOverrideName=P.getSettingDefinitionsUri=P.retrieveFeatureControlSettingsByNamespaceUrl=P.retrieveDeploymentPipelineConfigAppUrl=P.SPNPrincipalIdUrl=P.retrieveDeploymentEnvironmentInfoUrl=P.devSolutionInfoUrl=P.deployOperationStatusUrl=P.getAIGeneratedDeploymentNotesUrl=P.deploymentStageRunUrl=P.validatePackageAsyncUrl=P.deployPackageAsyncUrl=P.updateDeploymentStageRunUrl=P.createDeploymentStageRunUrl=P.retrieveDeploymentStagesUrl=P.retrievePipelinesUrl=P.retrieveDeploymentPipelineInfoUrl=P.getDeploymentStageRunsUrl=P.appDeploymentUrls=P.getProvisionLanguageUrl=P.getSolutionQueryUrl=P.getSolutionsByUniqueNameQueryUrl=P.solutionsQueryUrl=P.getDependentComponentsWithMetadataQueryUrl=void 0;var OD=TD();P.ODATA_MAX_PAGE_SIZE="odata.maxpagesize";P.ODATA_NEXT_LINK="@odata.nextLink";P.cdsServiceUrl="https://cds-org/";var Nf;(function(e){e.AllSolutions="11",e.AllPublishers="10",e.DevResources="05"})(Nf||(Nf={}));function F7(e,t,n,r){return`${e}tools/dependency/dependencyviewdialog.aspx?appSolutionId=%7b${t}%7d&dType=1&objectid=%7b${n}%7d&objecttype=${r}&operationtype=showdependency`}P.getShowComponentDependenciesUrl=F7;function U7(e,t){let n=`dType=1&isproactivecheck=true&objecttype=7100&operationtype=dependenciesforuninstall&objectid=${t}`;return`${e}tools/dependency/dependencyviewdialog.aspx?${n}`}P.getShowSolutionDependenciesUrl=U7;function q7(e,t){return`${e}tools/muiProvisioning/Dialogs/LangTranslationsImport.aspx?dType=1&appSolutionId=${t}`}P.getImportSolutionTranslationUrl=q7;function B7(e,t){return`${e}_grid/cmds/dlg_exportsolution.aspx?command=exporttranslation&appSolutionId=${t}`}P.getExportSolutionTranslationUrl=B7;function V7(e,t){return e!==void 0&&t!==void 0&&`CrmTranslations_${e}_${t.replace(/[.]/g,"_")}.zip`||""}P.getExportTranslationFileName=V7;function G7(e,t,n){return n?`${e}tools/publisher/edit.aspx?appSolutionId=%7b${n}%7d&id=%7b${t}%7d`:`${e}tools/publisher/edit.aspx?id=%7b${t}%7d`}P.getSolutionPublisherUrl=G7;function Hv(e,t){return`${e}tools/systemcustomization/systemCustomization.aspx?pid=${t}`}function j7(e){return Hv(e,Nf.AllSolutions)}P.getCrmAllSolutionsUrl=j7;function W7(e){return Hv(e,Nf.AllPublishers)}P.getCrmAllPublishersUrl=W7;function z7(e){return Hv(e,Nf.DevResources)}P.getCrmDevResourcesUrl=z7;function H7(e,t=OD.crmBapSolutionId){return`${e}designer/app/${t}#/CreateNewApp`}P.getCrmAppDesignerUrl=H7;function K7(e){return`${e}apps`}P.getCrmMyAppsUrl=K7;function J7(e){return DD(e,"role")+"&forceUCI=0"}P.getCrmAdminSecurityRolesUrl=J7;function Y7(e){return`${DD(e,"systemuser")}&forceclassic=1`}P.getCrmAdminSecurityUsersUrl=Y7;function DD(e,t){return`${e}main.aspx?pagetype=entitylist&etn=${t}`}function Q7(e,t){return`${e}main.aspx?appid=${t}`}P.getPlayAppModuleUrl=Q7;P.xrmApiUrl="api/data/v9.0";P.privilegesQueryUrls={systemUserInfo:e=>`${e}${P.xrmApiUrl}/WhoAmI`,userPrivileges:(e,t)=>`${e}${P.xrmApiUrl}/systemusers(${t})/Microsoft.Dynamics.CRM.RetrieveUserPrivileges`,systemPrivileges:e=>`${e}${P.xrmApiUrl}/privileges/Microsoft.Dynamics.CRM.RetrievePrivilegeSet`};function X7(e,t,n=OD.crmBapSolutionId){return`${e}designer/app/${n}/${t}/AppDesignerCanvas/${t}`}P.getAppModuleDesignerUrl=X7;function Z7(e,t,n,r){return`${e}main.aspx?appSolutionId=%7b${n}%7d&extraqs=%26formId%3d%7b${t}%7d%26dashboardType%3d1030&pagetype=${`${r?"ic":""}dashboardeditor`}`}P.getDashboardDesignerUrl=Z7;function eK(e,t,n){return`/e/${e}/s/${t}/dashboard/${n}`}P.getOpenModernDashboardUrl=eK;function tK(e,t,n){let r=n!==void 0?n.toString():void 0;return`/e/${e}/s/${t}/dashboard/new${r?`/${r}`:""}`}P.getNewModernDashboardUrl=tK;function nK(e,t,n,r){let i=r!==void 0?r.toString():void 0;return`/e/${e}/s/${t}/n/${n}/dashboard/new${i?`/${i}`:""}`}P.getNewModernEntityDashboardUrl=nK;function rK(e,t,n,r){return`/e/${e}/s/${t}/n/${n}/dashboard/${r}`}P.getOpenModernEntityDashboardUrl=rK;function iK(e,t,n,r){return`${e}main.aspx?appSolutionId=%7b${t}%7d&extraqs=etc=${n||""}`+(r?`%26id=${r}`:"")+"&pagetype=vizdesigner"}P.getChartDesignerUrl=iK;function oK(e,t,n){return`${e}sfa/workflow/edit.aspx?_CreateFromId=%7b${n}%7d&_CreateFromType=7100&appSolutionId=%7b${n}%7d&id=%7b${t}%7d`}P.getProcessDesignerUrl=oK;function aK(e,t,n){return`${e}sfa/workflow/edit.aspx?_CreateFromId=%7b${n}%7d&_CreateFromType=7100&appSolutionId=%7b${n}%7d&id=%7b${t}%7d`}P.getProcessShareUrl=aK;function sK(e,t){return`${e}Tools/ProcessControl/UnifiedProcessDesigner.aspx?id=${t}`}P.getBusinessProcessFlowDesignerUrl=sK;function uK(e,t,n){return`${e}CRMReports/reportproperty.aspx?appSolutionId=%7b${n}%7d&disablePersonal=true&id=%7b${t}%7d`}P.getReportDesignerUrl=uK;function lK(e,t,n){return`${e}main.aspx?_CreateFromId=%7b${n}%7d&_CreateFromType=7100&appSolutionId=%7b${n}%7d&etc=9333&id=%7b${t}%7d&pagetype=webresourceedit`}P.getWebResourceDesignerUrl=lK;function cK(e,t){return`${e}WebResources/${t}`}P.getWebResourceFileUrl=cK;function dK(e,t,n){return`${e}designer/sitemap/${n}/${t}/SiteMapHome/${t}`}P.getSiteMapDesignerUrl=dK;function fK(e,t,n){return`${e}connections/connectionroles/edit.aspx?_CreateFromId=%7b${n}%7d&_CreateFromType=7100&appSolutionId=%7b${n}%7d&id=%7b${t}%7d`}P.getConnectionRoleDesignerUrl=fK;function pK(e,t,n){return`${e}tools/emailtemplateeditor/emailtemplateeditor.aspx?_CreateFromId=%7b${n}%7d&_CreateFromType=7100&appSolutionId=%7b${n}%7d&id=%7b${t}%7d`}P.getEmailTemplateDesignerUrl=pK;function mK(e,t,n){return`${e}tools/mailmerge/edit.aspx?_CreateFromId=%7b${n}%7d&_CreateFromType=7100&appSolutionId=%7b${n}%7d&id=%7b${t}%7d`}P.getMailMergeTemplateDesignerUrl=mK;function hK(e,t,n){return`${e}biz/roles/edit.aspx?_CreateFromId=%7b${n}%7d&_CreateFromType=7100&appSolutionId=%7b${n}%7d&id=%7b${t}%7d`}P.getSecurityRoleDesignerUrl=hK;function gK(e,t,n){return`${e}biz/fieldsecurityprofiles/edit.aspx?_CreateFromId=%7b${n}%7d&_CreateFromType=7100&appSolutionId=%7b${n}%7d&id=%7b${t}%7d`}P.getFieldSecurityProfileDesignerUrl=gK;function yK(e,t,n){return`${e}tools/kbtemplateeditor/kbtemplateeditor.aspx?_CreateFromId=%7b${t}%7d&_CreateFromType=7100&appSolutionId=%7b${t}%7d&id=%7b${n}%7d`}P.getArticleTemplateUrl=yK;function bK(e,t,n,r){return`${e}tools/FormEditor/Dialogs/FormRoleAssignment.aspx?appSolutionId=%7b${t}%7d&dType=1&formId=%7b${n}%7d&objectTypeCode=0&type=${r}`}P.getEnableSecurityRolesUrl=bK;function vK(e){return`${e}tools/publisher/edit.aspx`}P.getCreateNewPublisherUrl=vK;function wK(e,t){return`${e}tools/kbtemplateeditor/kbtemplateeditor.aspx?appSolutionId=${t}`}P.getCreateNewArticleTemplateUrl=wK;P.solutionComponentDefinitionsQueryUrl="api/data/v9.0/solutioncomponentdefinitions";P.entityDefinitionsQueryUrl="api/data/v9.0/EntityDefinitions?$select=EntitySetName,DisplayName,LogicalName&$filter=";P.workflowsQueryUrl="api/data/v9.0/workflows";P.chartsQueryUrl="/api/data/v9.0/savedqueryvisualizations";P.solutionComponentConfigurationsQueryUrl="/api/data/v9.1/solutioncomponentconfigurations?$filter=isdisplayable eq true&$select=name";P.solutionComponentSummariesQueryUrl="/api/data/v9.0/msdyn_solutioncomponentsummaries";P.solutionComponentCountSummariesQueryUrl="/api/data/v9.0/msdyn_solutioncomponentcountsummaries";function EK(e,t){return`${P.xrmApiUrl}/RetrieveRequiredComponents(ObjectId=${e},ComponentType=${t})`}P.getRequiredComponentsQueryUrl=EK;function AK(e,t){return`${P.cdsServiceUrl}${P.xrmApiUrl}/RetrieveDependentComponentsWithMetadata(ObjectId=${e},ComponentType=${t})`}P.getDependentComponentsWithMetadataQueryUrl=AK;P.solutionsQueryUrl="/api/data/v9.0/solutions?$expand=publisherid&$filter=(isvisible eq true)";function CK(e){return`/api/data/v9.0/solutions?$expand=publisherid&$filter=(uniquename eq '${e}')`}P.getSolutionsByUniqueNameQueryUrl=CK;function SK(e){return`/api/data/v9.0/solutions(${e})?$expand=publisherid`}P.getSolutionQueryUrl=SK;function NK(e){return`${e}api/data/v9.1/ProvisionLanguageForUser`}P.getProvisionLanguageUrl=NK;P.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 _K(e,t,n,r=!1,i=!1,o=!1,a=!1,s=!1,u=!1,l=!1){return`/api/data/v9.1/deploymentstageruns+ ?$select=artifactname,artifactversion,deploymentstagerunid,devenvironmentid,endtime,errormessage,${s?"_artifactid_value,isredeployment,":""}${r?"deploymentnotes,":""}operation,operationdetails,operationstatus,${u?"retrycount,":""}${i?"scheduledtime,":""}${l?"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)${u?",RetryUser($select=azureactivedirectoryobjectid,fullname,ownerid,systemuserid)":""}+ &$filter=deploymentstageid/_deploymentpipelineid_value eq ${e} and devenvironmentid eq '${t}' and artifactname eq '${n}' and ((operation ne 200000201) or (operation eq 200000201 and operationstatus eq 200000003))+ &$orderby=starttime desc`}P.getDeploymentStageRunsUrl=_K;function IK(e,t,n){return`/api/data/v9.1/RetrieveDeploymentPipelineInfo(DeploymentPipelineId=${e},SourceEnvironmentId='${t}',ArtifactName='${n}')`}P.retrieveDeploymentPipelineInfoUrl=IK;function TK(e){return`/api/data/v9.0/deploymentenvironments?$select=deploymentenvironmentid,environmentid,environmenttype,name&$expand=deploymentpipeline_deploymentenvironment($select=name,description,deploymentpipelineid;$orderby=name asc)- &$filter=(environmentid eq '${e}')`}A.retrievePipelinesUrl=G3;function W3(e){return`/api/data/v9.0/deploymentstages+ &$filter=(environmentid eq '${e}')`}P.retrievePipelinesUrl=TK;function OK(e){return`/api/data/v9.0/deploymentstages?$filter=(_deploymentpipelineid_value eq ${e})&$select=name,description,deploymentstageid,_previousdeploymentstageid_value- &$expand=targetdeploymentenvironmentid($select=deploymentenvironmentid,environmentid,name)`}A.retrieveDeploymentStagesUrl=W3;function z3(){return"/api/data/v9.0/deploymentstageruns?$select=deploymentstagerunid"}A.createDeploymentStageRunUrl=z3;function j3(e){return`/api/data/v9.0/deploymentstageruns(${e})`}A.updateDeploymentStageRunUrl=j3;function H3(){return"/api/data/v9.0/DeployPackageAsync"}A.deployPackageAsyncUrl=H3;function K3(){return"/api/data/v9.0/ValidatePackageAsync"}A.validatePackageAsyncUrl=K3;function J3(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=J3;function Y3(e){return`/api/data/v9.0/deploymentstageruns(${e})- ?$select=aigenerateddeploymentnotes,deploymentstagerunid`}A.getAIGeneratedDeploymentNotesUrl=Y3;function Q3(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)`}P.retrieveDeploymentStagesUrl=OK;function DK(){return"/api/data/v9.0/deploymentstageruns?$select=deploymentstagerunid"}P.createDeploymentStageRunUrl=DK;function PK(e){return`/api/data/v9.0/deploymentstageruns(${e})`}P.updateDeploymentStageRunUrl=PK;function RK(){return"/api/data/v9.0/DeployPackageAsync"}P.deployPackageAsyncUrl=RK;function kK(){return"/api/data/v9.0/ValidatePackageAsync"}P.validatePackageAsyncUrl=kK;function $K(e,t=!1,n=!1){return`/api/data/v9.0/deploymentstageruns(${e})+ ?$select=deploymentstagerunid,stagerunstatus,errormessage,operation,operationdetails,operationstatus,${t?"scheduledtime,":""}targetenvironmentid,validationresults,artifactname,deploymentsettingsjson${n?"&$expand=createdby($select=azureactivedirectoryobjectid,fullname,ownerid,systemuserid)":""}`}P.deploymentStageRunUrl=$K;function LK(e){return`/api/data/v9.0/deploymentstageruns(${e})+ ?$select=aigenerateddeploymentnotes,deploymentstagerunid`}P.getAIGeneratedDeploymentNotesUrl=LK;function MK(e){let t="";for(let n=0;n<e.length;n++)n===e.length-1?t=t.concat(`deploymentstagerunid eq ${e[n]}`):t=t.concat(`deploymentstagerunid eq ${e[n]} or `);return`/api/data/v9.0/deploymentstageruns?$filter=(${t})- &$select=_deploymentstageid_value,deploymentstagerunid,stagerunstatus,operation,operationstatus,suboperation,artifactname`}A.deployOperationStatusUrl=Q3;function X3(e){return`/api/data/v9.0/solutions(${e})- ?$select=solutionid,uniquename,version`}A.devSolutionInfoUrl=X3;function Z3(e){return`/api/data/v9.0/deploymentenvironments+ &$select=_deploymentstageid_value,deploymentstagerunid,stagerunstatus,operation,operationstatus,suboperation,artifactname`}P.deployOperationStatusUrl=MK;function xK(e){return`/api/data/v9.0/solutions(${e})+ ?$select=solutionid,uniquename,version`}P.devSolutionInfoUrl=xK;function FK(e){return`/api/data/v9.0/deploymentenvironments?$select=deploymentenvironmentid,environmentid,environmenttype,name- &$filter=(environmentid eq '${e}')`}A.retrieveDeploymentEnvironmentInfoUrl=Z3;var eV=e=>`/api/data/v9.0/systemusers+ &$filter=(environmentid eq '${e}')`}P.retrieveDeploymentEnvironmentInfoUrl=FK;var UK=e=>`/api/data/v9.0/systemusers?$select=azureactivedirectoryobjectid- &$filter=(applicationid eq '${e}')`;A.SPNPrincipalIdUrl=eV;function tV(){return"/api/data/v9.0/appmodules?$filter=(uniquename eq 'AppDeploymentConfiguration')"}A.retrieveDeploymentPipelineConfigAppUrl=tV;A.retrieveFeatureControlSettingsByNamespaceUrl="/api/data/v9.1/RetrieveFeatureControlSettingsByNamespace";function rV(e){return`/api/data/v9.0/settingdefinitions${e}`}A.getSettingDefinitionsUri=rV;A.OrgSettingOverrideName="organizationsettings";function nV(e,t=!1){let r=`/api/data/v9.0/${A.OrgSettingOverrideName}${e}`;return t?`${A.cdsServiceUrl}${r}`:r}A.getOrgSettingOverrideUri=nV;A.AppSettingOverrideName="appsettings";function iV(e,t=!1){let r=`/api/data/v9.0/${A.AppSettingOverrideName}${e}`;return t?`${A.cdsServiceUrl.replace("/$","")}${r}`:r}A.getAppSettingOverrideUri=iV;var Sl;(function(e){e[e.All=0]="All",e[e.IsPlatformOnly=1]="IsPlatformOnly",e[e.NotPlatformOnly=2]="NotPlatformOnly"})(Sl||(A.RetrievePlatform=Sl={}));function oV(e,t,r,n=Sl.All,i=!1){let o=[];e&&o.push(`AppUniqueName='${e}'`),t!=null&&o.push(`ReleaseLevel=${t}`),r&&o.push(`RetrieveHiddenSettings=${r}`),n!==Sl.All&&o.push(`RetrievePlatformSettings=${n===Sl.IsPlatformOnly?1:0}`);let a="/api/data/v9.0/RetrieveUnpublishedOverridableSettingsInfo";return o.length&&(a=`${a}(${o.join(",")})`),i?`${A.cdsServiceUrl}${a}`:a}A.getPowerSettingsUri=oV;function aV(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=aV;function sV(e=!1){let t="/api/data/v9.0/SaveSettingValue()";return e?`${A.cdsServiceUrl}${t}`:t}A.getSavePowerSettingUri=sV;A.retrieveUnpublishedSuffix="Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()";function lV(e){return`tools/systemcustomization/businessrules/businessRulesDesigner.aspx?BRlaunchpoint=BRGrid&appSolutionId={${e}}`}A.getBusinessRuleDesignerUri=lV;function hE({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=hE;function uV({baseUrl:e,environmentInstanceUrl:t,entityLogicalName:r,recordId:n}){let i=e||hE({environmentInstanceUrl:t,entityLogicalName:r});return i&&n?`${i}&id=${n}`:void 0}A.getUCIEntityRecordEditUrl=uV;A.retrieveOrganizationResources=`${A.cdsServiceUrl}api/data/v9.0/RetrieveOrganizationResources`});var bE=v(Mc=>{"use strict";Object.defineProperty(Mc,"__esModule",{value:!0});Mc.DataverseClient=void 0;var cV=Km(),Fo=Q(),gE=ye(),dV=new Set(["entitydefinitions","relationshipdefinitions","globaloptionsetdefinitions"]);function fV(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 dV.has(s)}function pV(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 yE(e,t){var r;if(!fV(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 Ym=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}/${cV.xrmApiUrl}${n}`}async send(t,r){try{return await r()}catch(n){throw n instanceof Fo.SdkError?n:new Fo.ConnectionError(t,0,n instanceof Error?n.message:String(n),n)}}get(t,r){let n=this.apiUrl(t),i=yE(t,r);return(0,gE.resendDeadlockVictim)(()=>this.send(n,()=>this.httpClient.get(n,i)))}getAbsolute(t,r){this.assertSameOrigin(t);let n=yE(pV(t),r);return(0,gE.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 Fo.InvalidArgumentError(`Refusing to follow a malformed absolute URL: '${t}'`)}if(r.protocol!==n.protocol||r.host!==n.host)throw new Fo.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 Fo.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 Fo.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 Fo.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)))}};Mc.DataverseClient=Ym});var CE=v(or=>{"use strict";Object.defineProperty(or,"__esModule",{value:!0});or.findColumns=or.findTables=or.readCheckColumns=or.readColumnHints=or.fetchEntityMetadataFromApi=or.COLUMN_DETAIL_VERSION=void 0;var qc=ye(),br=le();function Xr(e){var t,r;return(r=(t=e?.UserLocalizedLabel)===null||t===void 0?void 0:t.Label)!==null&&r!==void 0?r:""}or.COLUMN_DETAIL_VERSION=2;function Qm(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 Mo(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 Uc(e,t){return(await Vc(e,t)).rows}async function Vc(e,t){var r,n;let i=await e.get(t);return i.status<200||i.status>=300?{rows:[],ok:!1}:{rows:(n=(r=i.body)===null||r===void 0?void 0:r.value)!==null&&n!==void 0?n:[],ok:!0}}function Gr(e){return`/EntityDefinitions(LogicalName='${(0,br.odataPathLiteral)(e)}')`}async function mV(e,t,r){let n=await Uc(e,`${Gr(t)}/Attributes/Microsoft.Dynamics.CRM.StringAttributeMetadata${(0,br.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 hV(e){return`${Gr(e)}/Attributes/Microsoft.Dynamics.CRM.PicklistAttributeMetadata${(0,br.odataQuery)([["$select","LogicalName"],["$expand","OptionSet($select=Options)"]])}`}async function gV(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:Xr(a.Label),...Mo(a.Label)?{localizedLabel:Mo(a.Label)}:{}}}))}}function Xm(e){var t;return{value:(t=e.Value)!==null&&t!==void 0?t:0,label:Xr(e.Label),...e.InvariantName?{invariantName:e.InvariantName}:{},...e.Color?{color:e.Color}:{}}}async function yV(e,t,r){var n;let i=c=>Vc(e,c).catch(()=>({rows:[],ok:!1})),o=["MultiSelectPicklistAttributeMetadata","StateAttributeMetadata","StatusAttributeMetadata"],a=await Promise.all([r.catch(()=>({rows:[],ok:!1})),...o.map(c=>i(`${Gr(t)}/Attributes/Microsoft.Dynamics.CRM.${c}${(0,br.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=>Qm(f.Label)),s.set(d.LogicalName,d.OptionSet.Options.map(Xm)));let u=await i(`${Gr(t)}/Attributes/Microsoft.Dynamics.CRM.BooleanAttributeMetadata${(0,br.odataQuery)([["$select","LogicalName"],["$expand","OptionSet($select=TrueOption,FalseOption)"]])}`);for(let c of u.rows){let d=c.OptionSet;d?.TrueOption&&d.FalseOption&&(l=l&&Qm(d.TrueOption.Label)&&Qm(d.FalseOption.Label),s.set(c.LogicalName,[Xm(d.FalseOption),Xm(d.TrueOption)]))}return{byColumn:s,complete:l&&u.ok&&a.every(c=>c.ok)}}async function bV(e,t,r){let{rows:n,ok:i}=await Vc(e,`${Gr(t)}/Attributes/Microsoft.Dynamics.CRM.LookupAttributeMetadata${(0,br.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 Bc(e,t){return e<t?-1:e>t?1:0}var vE={OneToMany:0,ManyToOne:1,ManyToMany:2};function vV(e,t){return vE[e.type]-vE[t.type]||Bc(e.schemaName,t.schemaName)||Bc(e.relatedEntity,t.relatedEntity)||Bc(e.relatedAttribute,t.relatedAttribute)}async function wV(e,t){var r,n,i,o;let a=[],s=await Uc(e,`${Gr(t)}/OneToManyRelationships${(0,br.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 Uc(e,`${Gr(t)}/ManyToOneRelationships${(0,br.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 Uc(e,`${Gr(t)}/ManyToManyRelationships${(0,br.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(vV)}async function CV(e,t){var r,n,i,o,a;let s=`${Gr(t)}`+(0,br.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,qc.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:Xr(g.DisplayName),...Mo(g.DisplayName)?{localizedDisplayName:Mo(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}:{},...Xr(g.Description)?{description:Xr(g.Description)}:{}}}).sort((g,b)=>Bc(g.logicalName,b.logicalName)),d=new Map(c.map(g=>[g.logicalName,g])),f=Vc(e,hV(t)),[,,m,p,h]=await Promise.all([mV(e,t,d),gV(f,d),yV(e,t,f),bV(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:Xr(u.DisplayName),...Mo(u.DisplayName)?{localizedDisplayName:Mo(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,...Xr(u.Description)?{description:Xr(u.Description)}:{},columnDetailComplete:m.complete&&p,columnDetailVersion:or.COLUMN_DETAIL_VERSION,attributes:c,relationships:h}}or.fetchEntityMetadataFromApi=CV;var wE=40;async function Zm(e,t,r,n){var i,o;let a=[...new Set(n.filter(l=>l!==""))],s=[];for(let l=0;l<a.length;l+=wE){let u=a.slice(l,l+wE).map(f=>`LogicalName eq '${(0,br.odataLiteral)(f)}'`).join(" or "),c=t+(0,br.odataQuery)([["$select",r],["$filter",u]]),d=(0,qc.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 EV(e,t,r){return(await Zm(e,`${Gr(t)}/Attributes`,"LogicalName,AttributeType,DisplayName",r)).map(i=>{var o;let a=Mo(i.DisplayName);return{logicalName:i.LogicalName,displayName:Xr(i.DisplayName),...a?{localizedDisplayName:a}:{},attributeType:(o=i.AttributeType)!==null&&o!==void 0?o:"Unknown"}})}or.readColumnHints=EV;async function AV(e,t,r){let i=(await Zm(e,`${Gr(t)}/Attributes`,"LogicalName,AttributeType,DisplayName,IsCustomAttribute",r)).map(s=>{var l;return{logicalName:s.LogicalName,displayName:Xr(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 Zm(e,`${Gr(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}or.readCheckColumns=AV;async function SV(e,t,r){var n,i;let o=`/EntityDefinitions${(0,br.odataQuery)([["$select","LogicalName,SchemaName,EntitySetName,DisplayName,IsCustomEntity"]])}`,s=(i=(n=(0,qc.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:Xr(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}or.findTables=SV;async function NV(e,t,r,n){var i,o;let a=`${Gr(t)}/Attributes`+(0,br.odataQuery)([["$select","LogicalName,SchemaName,DisplayName,AttributeType,IsCustomAttribute"]]),l=(o=(i=(0,qc.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:Xr(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}or.findColumns=NV});var rh=v(vr=>{"use strict";Object.defineProperty(vr,"__esModule",{value:!0});vr.renderTypeRegistrations=vr.buildGenPageLegacyEnums=vr.renderGenPageAuthoringTypes=vr.buildGenPageRuntimeTypes=vr.toDesignerEntity=vr.TABLE_LOGICAL_NAME=void 0;vr.TABLE_LOGICAL_NAME=/^[a-z_][a-z0-9_]*$/;function eh(e){return e.replace(/[\r\n\u2028\u2029]+/g," ")}var _V=new Set(["createdby","createdon","createdonbehalfby","importsequencenumber","modifiedby","modifiedon","modifiedonbehalfby","overriddencreatedon","ownerid","owningbusinessunit","owningteam","owninguser","timezoneruleversionnumber","utcconversiontimezonecode","versionnumber"]);function Gc(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=Gc(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 EE(e,t){return e.logicalName<t.logicalName?-1:e.logicalName>t.logicalName?1:0}function NE(e){return!_V.has(e.logicalName)&&(!e.attributeOf||Gc(e)==="image")&&e.isValidForRead!==!1}var AE=new Set(["boolean","picklist","multiselectpicklist","state","status"]);function _E(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(EE),i=e.attributes.filter(o=>!r.has(o.logicalName)).sort(EE);return[...n,...i]}function th(e){var t;let r=[],n=new Set,i=_E(e);for(let o of i){let a=Gc(o),s=a==="image";NE(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))}}vr.toDesignerEntity=th;function TE(e,t="None"){let r={};for(let n of e)r[n.logicalName]=th(n);return OE(r,t)}vr.buildGenPageRuntimeTypes=TE;var DE=`export interface TableRegistrations extends BaseTableRegistrations {-`,IE=`export interface EnumRegistrations extends BaseEnumRegistrations {-`;function TV(e,t){return e.length>0?TE(e,t).text:RE(`${DE}}-`,`${IE}}-`,"","")}vr.renderGenPageAuthoringTypes=TV;function DV(e){let t=new Set;for(let n of e)for(let i of th(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 _E(n)){let o=`${n.logicalName}_${i.logicalName}`,a=SE(i);if(NE(i)||!AE.has(Gc(i))||!a||t.has(o)||r.has(o))continue;let s={name:o,runtime:{},labels:new Map};r.set(o,{declaration:PE(o,a,!1,s),model:s})}return r}vr.buildGenPageLegacyEnums=DV;function OE(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=IE,c="",d="";for(let f of o){s&&f.Description&&(c+=`// ${eh(f.Description)}+ &$filter=(applicationid eq '${e}')`;P.SPNPrincipalIdUrl=UK;function qK(){return"/api/data/v9.0/appmodules?$filter=(uniquename eq 'AppDeploymentConfiguration')"}P.retrieveDeploymentPipelineConfigAppUrl=qK;P.retrieveFeatureControlSettingsByNamespaceUrl="/api/data/v9.1/RetrieveFeatureControlSettingsByNamespace";function BK(e){return`/api/data/v9.0/settingdefinitions${e}`}P.getSettingDefinitionsUri=BK;P.OrgSettingOverrideName="organizationsettings";function VK(e,t=!1){let n=`/api/data/v9.0/${P.OrgSettingOverrideName}${e}`;return t?`${P.cdsServiceUrl}${n}`:n}P.getOrgSettingOverrideUri=VK;P.AppSettingOverrideName="appsettings";function GK(e,t=!1){let n=`/api/data/v9.0/${P.AppSettingOverrideName}${e}`;return t?`${P.cdsServiceUrl.replace("/$","")}${n}`:n}P.getAppSettingOverrideUri=GK;var Sf;(function(e){e[e.All=0]="All",e[e.IsPlatformOnly=1]="IsPlatformOnly",e[e.NotPlatformOnly=2]="NotPlatformOnly"})(Sf||(P.RetrievePlatform=Sf={}));function jK(e,t,n,r=Sf.All,i=!1){let o=[];e&&o.push(`AppUniqueName='${e}'`),t!=null&&o.push(`ReleaseLevel=${t}`),n&&o.push(`RetrieveHiddenSettings=${n}`),r!==Sf.All&&o.push(`RetrievePlatformSettings=${r===Sf.IsPlatformOnly?1:0}`);let a="/api/data/v9.0/RetrieveUnpublishedOverridableSettingsInfo";return o.length&&(a=`${a}(${o.join(",")})`),i?`${P.cdsServiceUrl}${a}`:a}P.getPowerSettingsUri=jK;function WK(e,t,n,r=!1){let i=[`SettingName='${e}'`];t!==void 0&&i.push(`SolutionName='${t}'`),n!==void 0&&i.push(`AppUniqueName='${n}'`);let o="/api/data/v9.0/RetrieveUnpublishedSettingInfo";return i.length&&(o=`${o}(${i.join(",")})`),r?`${P.cdsServiceUrl}${o}`:o}P.getPowerSettingUri=WK;function zK(e=!1){let t="/api/data/v9.0/SaveSettingValue()";return e?`${P.cdsServiceUrl}${t}`:t}P.getSavePowerSettingUri=zK;P.retrieveUnpublishedSuffix="Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()";function HK(e){return`tools/systemcustomization/businessrules/businessRulesDesigner.aspx?BRlaunchpoint=BRGrid&appSolutionId={${e}}`}P.getBusinessRuleDesignerUri=HK;function PD({environmentInstanceUrl:e,entityLogicalName:t}){return e&&t?`${e}main.aspx?cmdbar=true&forceUCI=1&navbar=off&newWindow=true&pageType=entityRecord&etn=${t}`:void 0}P.getUCIEntityRecordBaseUrl=PD;function KK({baseUrl:e,environmentInstanceUrl:t,entityLogicalName:n,recordId:r}){let i=e||PD({environmentInstanceUrl:t,entityLogicalName:n});return i&&r?`${i}&id=${r}`:void 0}P.getUCIEntityRecordEditUrl=KK;P.retrieveOrganizationResources=`${P.cdsServiceUrl}api/data/v9.0/RetrieveOrganizationResources`});var $D=C(oc=>{"use strict";Object.defineProperty(oc,"__esModule",{value:!0});oc.readOnlyDataverse=oc.DataverseClient=void 0;var JK=zv(),$s=Y(),RD=pe(),YK=new Set(["entitydefinitions","relationshipdefinitions","globaloptionsetdefinitions"]);function QK(e){var t,n,r,i;let o=e.split("?")[0].split("/").filter(u=>u!==""),a=((t=o[0])===null||t===void 0?void 0:t.toLowerCase())==="api"&&((n=o[1])===null||n===void 0?void 0:n.toLowerCase())==="data"&&/^v\d/i.test((r=o[2])!==null&&r!==void 0?r:""),s=((i=o[a?3:0])!==null&&i!==void 0?i:"").split("(")[0].toLowerCase();return YK.has(s)}function XK(e){let t=e.indexOf("://"),n=t===-1?"":e.slice(t+3),r=n.search(/[/?#]/),i=r===-1?"":n.slice(r),o=i.search(/[?#]/);return o===-1?i:i.slice(0,o)}function kD(e,t){var n;if(!QK(e))return t;let r=(n=t?.headers)!==null&&n!==void 0?n:{};return Object.keys(r).some(i=>i.toLowerCase()==="consistency")?t:{...t,headers:{...r,Consistency:"Strong"}}}var Kv=class e{constructor(t,n,r,i=1){this.instanceUrl=t,this.httpClient=n,this.solutionUniqueName=r,this.readConcurrency=i}withSolution(t){return this.solutionUniqueName?{...t,headers:{...t?.headers,"MSCRM.SolutionUniqueName":this.solutionUniqueName}}:t}withoutSolution(){return this.solutionUniqueName===void 0?this:new e(this.instanceUrl,this.httpClient,void 0,this.readConcurrency)}withTransport(t){return new e(this.instanceUrl,t(this.httpClient),this.solutionUniqueName,this.readConcurrency)}apiUrl(t){let n=this.instanceUrl.replace(/\/+$/,""),r=t.startsWith("/")?t:`/${t}`;return`${n}/${JK.xrmApiUrl}${r}`}async send(t,n){try{return await n()}catch(r){throw r instanceof $s.SdkError?r:new $s.ConnectionError(t,0,r instanceof Error?r.message:String(r),r)}}get(t,n){let r=this.apiUrl(t),i=kD(t,n);return(0,RD.resendDeadlockVictim)(()=>this.send(r,()=>this.httpClient.get(r,i)))}getAbsolute(t,n){this.assertSameOrigin(t);let r=kD(XK(t),n);return(0,RD.resendDeadlockVictim)(()=>this.send(t,()=>this.httpClient.get(t,r)))}assertSameOrigin(t){let n,r;try{n=new URL(t),r=new URL(this.instanceUrl)}catch{throw new $s.InvalidArgumentError(`Refusing to follow a malformed absolute URL: '${t}'`)}if(n.protocol!==r.protocol||n.host!==r.host)throw new $s.InvalidArgumentError(`Refusing to follow a cross-origin link ('${n.origin}' is not the configured instance '${r.origin}'); server-driven pagination must stay on-instance.`)}post(t,n,r){let i=this.apiUrl(t);return this.send(i,()=>this.httpClient.post(i,n,this.withSolution(r)))}get supportsAtomicBatch(){return typeof this.httpClient.postRaw=="function"}get supportsPut(){return typeof this.httpClient.put=="function"}get solutionName(){return this.solutionUniqueName}postBatch(t,n,r){if(!this.httpClient.postRaw)throw new $s.InvalidArgumentError("The injected HttpClient does not implement postRaw(), required for atomic $batch change sets");let i=this.apiUrl("/$batch"),o={...r,headers:{...r?.headers,"Content-Type":`multipart/mixed;boundary=${n}`}};return this.send(i,()=>this.httpClient.postRaw(i,t,o))}patch(t,n,r){let i=this.apiUrl(t);return this.send(i,()=>this.httpClient.patch(i,n,this.withSolution(r)))}get supportsBinaryPatch(){return typeof this.httpClient.patchRaw=="function"}patchRaw(t,n,r){if(!this.httpClient.patchRaw)throw new $s.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,n,this.withSolution(r)))}put(t,n,r){if(!this.httpClient.put)throw new $s.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,n,this.withSolution(r)))}delete(t,n){let r=this.apiUrl(t);return this.send(r,()=>this.httpClient.delete(r,this.withSolution(n)))}readOnly(){let t={gets:0,refusedWrites:[]},n=this.httpClient,r=o=>a=>(t.refusedWrites.push(`${o} ${a}`),Promise.reject(new $s.SdkError("PREVIEW_WRITE_REFUSED",`A pre-push check attempted a write (${o} ${a}); it may only read. This is a defect in the SDK.`))),i={get:(o,a)=>(t.gets+=1,n.get(o,a)),post:r("POST"),patch:r("PATCH"),delete:r("DELETE")};return typeof n.put=="function"&&(i.put=r("PUT")),typeof n.postRaw=="function"&&(i.postRaw=r("POST")),typeof n.patchRaw=="function"&&(i.patchRaw=r("PATCH")),{client:new e(this.instanceUrl,i,this.solutionUniqueName,this.readConcurrency),guard:t}}};oc.DataverseClient=Kv;function ZK(e){return{apiUrl:t=>e.apiUrl(t),get:(t,n)=>e.get(t,n),getAbsolute:(t,n)=>e.getAbsolute(t,n),readConcurrency:e.readConcurrency}}oc.readOnlyDataverse=ZK});var Xv=C(dt=>{"use strict";Object.defineProperty(dt,"__esModule",{value:!0});dt.assertOneWritePerRow=dt.commandApi=dt.readCommandBarRows=dt.fetchEntityMetadataId=dt.isStorableLocation=dt.COMMAND_PARENT_LOCATION_UNREADABLE_CODE=dt.COMMAND_DUPLICATE_ROW_CODE=dt.COMMAND_ROW_NOT_IN_BAR_CODE=dt.COMMAND_TABLE_MISMATCH_CODE=void 0;var Yv=Ke(),UD=qi(),Qr=pe(),Ho=Y(),Xr=ae();dt.COMMAND_TABLE_MISMATCH_CODE="COMMAND_TABLE_MISMATCH";dt.COMMAND_ROW_NOT_IN_BAR_CODE="COMMAND_ROW_NOT_IN_BAR";dt.COMMAND_DUPLICATE_ROW_CODE="COMMAND_DUPLICATE_ROW";dt.COMMAND_PARENT_LOCATION_UNREADABLE_CODE="COMMAND_PARENT_LOCATION_UNREADABLE";function qD(e){return typeof e=="number"&&Number.isInteger(e)&&e>=0&&e<=6}dt.isStorableLocation=qD;var eJ="OnClickEventJavaScriptWebResourceId($select=name,webresourceid),IconWebResourceId($select=name,webresourceid)";async function _h(e,t){let n=`/EntityDefinitions(LogicalName='${(0,Xr.odataPathLiteral)(t)}')${(0,Xr.odataQuery)([["$select","MetadataId"]])}`,i=(0,Qr.ensureSuccess)(await e.get(n),e.apiUrl(n)).body,o=i?.MetadataId;return o?(0,Xr.normalizeGuid)(o,"entityMetadataId"):""}dt.fetchEntityMetadataId=_h;function Qv(e,t){return t?`_contextentity_value eq ${t}`:`contextvalue eq '${(0,Xr.odataLiteral)(e)}'`}function ac(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 LD(e,t){let n=e.entityLogicalName;if(t===void 0)return n;if(typeof n!="string"||n.toLowerCase()!==t.toLowerCase())throw new Ho.SdkError(dt.COMMAND_TABLE_MISMATCH_CODE,`Refusing to push command '${t}': its JSON names table '${String(n)}'. 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 MD(e,t,n){let r=await _h(e,t);if(n){let i=(0,Xr.normalizeGuid)(n,"entityMetadataId");if(i!==r)throw new Ho.SdkError(dt.COMMAND_TABLE_MISMATCH_CODE,`Refusing to push command '${t}': it was fetched for table id ${i}, but table '${t}' is ${r||"not resolvable"} on the server \u2014 the table was re-created, or the local copy edited. `+ac(t))}return r}function BD(e,t,n,r,i){let o=`/appactions${(0,Xr.odataQuery)([["$expand",eJ],["$filter",Qv(t,n)]])}`;return(0,Yv.collectPages)(e,o,r,i)}dt.readCommandBarRows=BD;dt.commandApi={async get(e,t){let n=t,r=await _h(e,n),i,o=await BD(e,n,r,"fetchArtifact('command')",u=>{i=u}),a={entityLogicalName:n,entityMetadataId:r,appActions:o},s={};for(let u of o){let l=typeof u.appactionid=="string"?u.appactionid:void 0;if(l){let c=u["@odata.etag"];s[(0,Xr.normalizeGuid)(l,"appactionid")]=typeof c=="string"?c:null}}return{raw:a,etag:i?(0,Qr.readEtag)(i):null,memberEtags:s}},async list(e,t){let n=t?.entityLogicalName;return n?[{type:"command",id:n,name:`${n} commands`,entityLogicalName:n,isDirty:!1}]:[]},async create(e,t,n,r=void 0){let i=t,o=LD(i,n),a=await MD(e,o,i.entityMetadataId);return xD(e,o,{...i,entityMetadataId:a},!1,void 0,r)},async update(e,t,n,r,i,o=void 0,a){let s=n,u=LD(s,t),l=await MD(e,u,s.entityMetadataId);return xD(e,u,{...s,entityMetadataId:l},!0,i,a)},planPush(e,t,n){return(0,UD.planPushThrough)(dt.commandApi,e,t,n)},async delete(e,t){let n=await _h(e,t),r=`/appactions${(0,Xr.odataQuery)([["$select","appactionid"],["$filter",Qv(t,n)]])}`,i=await(0,Yv.collectPages)(e,r,"deleteArtifact('command')");for(let o of i)o.appactionid&&await(0,Qr.deleteRecord)(e,"appactions",o.appactionid)}};async function xD(e,t,n,r,i,o){let a=n.entityMetadataId?(0,Xr.normalizeGuid)(n.entityMetadataId,"entityMetadataId"):"",s=await rJ(e,t,n,a,r,i,o);if(o)return o.reached({effects:tJ(s),attemptsWrite:s.writes.length+s.deletes.length>0});let u={};try{await aJ(e,s,a,u)}catch(l){throw(0,Ho.withPartialTokens)(l,{memberEtags:u})}return{id:n.entityLogicalName,etag:null,memberEtags:u}}function tJ(e){return[...e.writes.map(n=>{if(n.kind==="patch")return{componentName:"appaction",componentId:n.id,identity:"known",operation:"update"};let r=n.row.body.appactionid;return typeof r=="string"&&r!==""?{componentName:"appaction",componentId:_f(r),identity:"known",operation:"create"}:{componentName:"appaction",identity:"assignedAtWrite",operation:"create"}}),...e.deletes.map(n=>({componentName:"appaction",componentId:n.id,identity:"known",operation:"delete"}))]}function _f(e){return e.replace(/[{}]/g,"").toLowerCase()}function VD(e,t){var n;let r=new Map,i=[...t.rows.map(o=>[o.appactionid,"written"]),...((n=t.deletedRowIds)!==null&&n!==void 0?n:[]).map(o=>[o,"deleted"])];for(let[o,a]of i){let s=_f(o),u=r.get(s);if(u===void 0){r.set(s,a);continue}throw new Ho.SdkError(dt.COMMAND_DUPLICATE_ROW_CODE,u===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.`)}}dt.assertOneWritePerRow=VD;var nJ={entities:/^\/entities\(([^()]+)\)$/,appactions:/^\/appactions\(([^()]+)\)$/};function Jv(e,t){let n=nJ[t].exec(e);return n?_f(n[1]):void 0}async function rJ(e,t,n,r,i,o,a){var s,u,l,c;let d=(y,b)=>a?.observe({guard:"ifMatch",componentName:"appaction",componentId:y,held:typeof b=="string"?b:null,status:"missingHeld"});VD(t,n);let f=sJ(n.rows),p=new Set(f.map(y=>_f(y.appactionid))),m={writes:[],deletes:[]};for(let y of f){let b=y.body["[email protected]"];if(b!==void 0&&!(typeof b=="string"&&r!==""&&Jv(b,"entities")===r))throw new Ho.SdkError(dt.COMMAND_TABLE_MISMATCH_CODE,`Refusing to push command '${t}': app action '${y.appactionid}' binds to ${typeof b=="string"?`'${b}'`:String(b)}, not to table '${t}' (${r?`/entities(${r})`:"whose id is not resolvable"}). `+ac(t));let E=y.body["[email protected]"];if(typeof E=="string"){let w=Jv(E,"appactions");if(w===void 0||!p.has(w))throw new Ho.SdkError(dt.COMMAND_ROW_NOT_IN_BAR_CODE,`Refusing to push command '${t}': app action '${y.appactionid}' would be placed under '${E}', which is not a row of this command. `+ac(t))}if(i&&y.exists){let w=(0,Xr.normalizeGuid)(y.appactionid,"id"),_=(s=o?.[w])!==null&&s!==void 0?s:y.etag;if(!(0,Qr.isVersionToken)(_))throw d(w,_),FD(t,w,"update",_);m.writes.push({kind:"patch",row:y,id:w,token:_})}else{if(b===void 0&&!r)throw new Ho.SdkError("COMMAND_CONTEXT_ENTITY_UNRESOLVED",`Cannot create app action '${y.appactionid}' for entity '${n.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.`);m.writes.push({kind:"post",row:y})}}for(let y of(u=n.deletedRowIds)!==null&&u!==void 0?u:[]){let b=(0,Xr.normalizeGuid)(y,"id"),E=o?.[b];if(!(0,Qr.isVersionToken)(E))throw d(b,E),FD(t,b,"delete",E);m.deletes.push({id:b,token:E})}let h=[...m.writes.flatMap(y=>y.kind==="patch"?[{id:y.id,verb:"update"}]:[]),...m.deletes.map(y=>({id:y.id,verb:"delete"}))],g=m.writes.filter(y=>y.kind==="post"&&y.row.inheritsParentLocation===!0);if(g.length>0&&!i)throw GD(t,g[0].row.appactionid,void 0,void 0);if(h.length>0||g.length>0){let y=await oJ(e,t,r,g.length>0),b=h.find(E=>!y.has(E.id));if(b)throw a?.observe({guard:"membership",componentName:"appaction",componentId:b.id,status:"goneOnServer",detail:"not in the table's command bar on the server"}),new Ho.SdkError(dt.COMMAND_ROW_NOT_IN_BAR_CODE,`Refusing to push command '${t}': it would ${b.verb} app action '${b.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. `+ac(t));if(g.length>0&&iJ(t,m,y),a){let E=[...m.writes.flatMap(w=>w.kind==="patch"?[{id:w.id,token:w.token}]:[]),...m.deletes];for(let{id:w,token:_}of E){let I=(c=(l=y.get(w))===null||l===void 0?void 0:l.token)!==null&&c!==void 0?c:null;a.observe({guard:"ifMatch",componentName:"appaction",componentId:w,held:_,server:I,status:(0,UD.compareTokens)(_,I)})}}}return m}function iJ(e,t,n){let r=new Map;t.writes=t.writes.map(i=>{var o;if(i.kind!=="post")return i;let a=i.row;if(a.inheritsParentLocation===!0){let s=a.body["[email protected]"],u=typeof s=="string"?Jv(s,"appactions"):void 0,l=u===void 0?void 0:r.has(u)?r.get(u):(o=n.get(u))===null||o===void 0?void 0:o.location;if(!qD(l))throw GD(e,a.appactionid,u,l);a={...a,body:{...a.body,location:l}}}return r.set(_f(a.appactionid),a.body.location),{...i,row:a}})}function GD(e,t,n,r){return new Ho.SdkError(dt.COMMAND_PARENT_LOCATION_UNREADABLE_CODE,`Refusing to push command '${e}': app action '${t}' is new and must be created at the Location its parent ${n?`'${n}' `:""}actually holds \u2014 the runtime shows a command only under a parent at the same Location \u2014 but the server's answer gives that parent ${r===void 0?"no Location":`the Location ${JSON.stringify(r)}`}. `+ac(e))}function FD(e,t,n,r){return new Ho.SdkError(Qr.UPDATE_NO_ETAG_CODE,`Refusing to push command '${e}': ${typeof r=="string"&&r!==""?`the token held for app action '${t}' ('${r}') is not a version`:`no token is held for app action '${t}'`}, so its ${n} could not be made conditional and would overwrite or remove a concurrent edit. `+ac(e))}async function oJ(e,t,n,r){let i=`/appactions${(0,Xr.odataQuery)([["$select",r?"appactionid,location":"appactionid"],["$filter",Qv(t,n)]])}`,o=await(0,Yv.collectPages)(e,i,"pushArtifact('command') bar membership"),a=new Map;for(let s of o)if(typeof s.appactionid=="string"){let u=s["@odata.etag"];a.set((0,Xr.normalizeGuid)(s.appactionid,"appactionid"),{token:typeof u=="string"?u:null,location:s.location})}return a}async function aJ(e,t,n,r){for(let i of t.writes)if(i.kind==="patch"){let o=(0,Qr.echoWrite)("appactionid",{"If-Match":i.token}),a=`/appactions(${i.id})${o.query}`,s=(0,Qr.ensureSuccess)(await e.patch(a,i.row.body,o.options),e.apiUrl(a));r[i.id]=(0,Qr.readEtag)(s)}else{let o=(0,Qr.echoWrite)("appactionid"),a=`/appactions${o.query}`,s={...i.row.body};s["[email protected]"]===void 0&&(s["[email protected]"]=`/entities(${n})`);let u=(0,Qr.ensureSuccess)(await e.post(a,s,o.options),e.apiUrl(a)),l=(0,Qr.readCreatedId)(u,"appactionid");l&&(r[(0,Xr.normalizeGuid)(l,"appactionid")]=(0,Qr.readEtag)(u))}for(let{id:i,token:o}of[...t.deletes].reverse())await(0,Qr.deleteRecord)(e,"appactions",i,o),delete r[i]}function sJ(e){let t=new Map(e.map(o=>[o.appactionid,o])),n=new Set,r=[],i=o=>{if(n.has(o.appactionid))return;let a=o.body["[email protected]"];if(typeof a=="string"){let s=/\(([^)]+)\)/.exec(a),u=s?t.get(s[1]):void 0;u&&i(u)}n.add(o.appactionid),r.push(o)};return e.forEach(i),r}});var aw=C(Ko=>{"use strict";Object.defineProperty(Ko,"__esModule",{value:!0});Ko.classifyCommandBar=Ko.inspectCommandBar=Ko.inspectionUnreadable=Ko.validateCommandInspectOptions=void 0;var jD=Xv(),Sn=Y(),uJ=pe(),Ih=ae(),lJ={0:"button",1:"flyout",2:"split",3:"group"},cJ={0:"form",1:"homeGrid",2:"subGrid",3:"associatedGrid"},rw=["form","homeGrid","subGrid","associatedGrid"],WD=["button","flyout","split"],dJ=new Set(["rowId","surface","label","menuPath","kind"]),fJ=new Set(["find","appModuleId"]),qu="inspectArtifact('command')";function YD(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function QD(e,t){if(typeof e!="string"||e.trim()==="")throw new Sn.InvalidArgumentError(`${qu}: the id must be the table's logical name (got ${JSON.stringify(e)}).`);if(t===void 0)return{appModuleId:null};if(!YD(t))throw new Sn.InvalidArgumentError(`${qu}: options must be an object when given.`);let n=Object.keys(t).find(o=>!fJ.has(o));if(n!==void 0)throw new Sn.InvalidArgumentError(`${qu}: '${n}' is not a command inspection option (only 'find' and 'appModuleId'${n==="expected"?"; 'expected' is the dashboard witness's":""}).`);let r=t.appModuleId===void 0?null:(0,Ih.normalizeGuid)(String(t.appModuleId),`${qu} appModuleId`);if(t.find===void 0)return{appModuleId:r};if(!Array.isArray(t.find))throw new Sn.InvalidArgumentError(`${qu}: 'find' must be an array of control queries.`);return{queries:t.find.map((o,a)=>pJ(o,a)),appModuleId:r}}Ko.validateCommandInspectOptions=QD;function pJ(e,t){var n;let r=`${qu} find[${t}]`;if(!YD(e))throw new Sn.InvalidArgumentError(`${r} must be an object.`);let i=Object.keys(e).find(a=>!dJ.has(a));if(i!==void 0)throw new Sn.InvalidArgumentError(`${r}: '${i}' is not a query field.`);if(typeof e.surface!="string"||!rw.includes(e.surface))throw new Sn.InvalidArgumentError(`${r}: surface must be one of ${rw.join(", ")} (got ${JSON.stringify(e.surface)}).`);if(e.label!==void 0&&(typeof e.label!="string"||e.label===""))throw new Sn.InvalidArgumentError(`${r}: label must be a non-empty string when given.`);if(e.rowId===void 0&&e.label===void 0)throw new Sn.InvalidArgumentError(`${r}: give the rowId recorded at creation (verification) or a label (discovery) \u2014 a query with neither would match every control.`);let o=e.rowId===void 0?void 0:(0,Ih.normalizeGuid)(String(e.rowId),`${r} rowId`);if(e.menuPath!==void 0&&(!Array.isArray(e.menuPath)||e.menuPath.some(a=>typeof a!="string")))throw new Sn.InvalidArgumentError(`${r}: menuPath must be an array of captions.`);if(e.kind!==void 0&&!WD.includes(e.kind))throw new Sn.InvalidArgumentError(`${r}: kind must be one of ${WD.join(", ")} (got ${JSON.stringify(e.kind)}).`);return{original:e,rowId:o,surface:e.surface,label:e.label,menuPath:(n=e.menuPath)!==null&&n!==void 0?n:[],kind:e.kind}}function iw(e,t){if(t instanceof Sn.InspectionUnreadableError)return t;let n=t instanceof Sn.ConnectionError&&t.statusCode>0?t.statusCode:void 0,r=t instanceof Error?t.message:String(t);return(0,Sn.attachCause)(new Sn.InspectionUnreadableError("command",e,n,`${r}.`),t)}Ko.inspectionUnreadable=iw;async function mJ(e,t,n,r){let i=QD(t,n),o,a;try{if(o=await(0,jD.fetchEntityMetadataId)(e,t),!o)throw new Sn.InspectionUnreadableError("command",t,void 0,"the table's MetadataId could not be read, so its command bar cannot be selected.");a=await(0,jD.readCommandBarRows)(e,t,o,qu)}catch(u){throw iw(t,u)}let s=(0,uJ.nowIso)();try{return XD(t,o,a,r,i,s)}catch(u){throw iw(t,u)}}Ko.inspectCommandBar=mJ;function hJ(e){var t;let n=typeof e=="string"?`'${e}'`:(t=JSON.stringify(e))!==null&&t!==void 0?t:String(e);return n.length>60?`${n.slice(0,60)}\u2026`:n}function ow(e,t,n,r){throw new Sn.InvalidArgumentError(`the row ${e} answered ${t} as ${hJ(n)}, not ${r}, so it is not one well-formed bar`)}function zD(e,t,n){let r=e[t];if(r==null)return null;if(typeof r=="string")try{return(0,Ih.normalizeGuid)(r,t)}catch{}return ow(n,t,r,"a GUID or null")}function Zv(e,t,n){let r=e[t];return r==null?!1:typeof r=="boolean"?r:ow(n,t,r,"a boolean or null")}function ew(e,t,n){let r=e[t];return r==null?"":typeof r=="string"?r:ow(n,t,r,"text or null")}function HD(e){return typeof e=="number"&&Number.isInteger(e)?e:null}function XD(e,t,n,r,i,o){var a,s;let u=new Map;for(let p of n){let m=p?.appactionid;if(typeof m!="string"||m==="")throw new Sn.InvalidArgumentError(`the row '${String((a=p?.name)!==null&&a!==void 0?a:"")}' has no appactionid (its primary key), so it cannot be identified`);let h=(0,Ih.normalizeGuid)(m,"appactionid");if(u.has(h))throw new Sn.InvalidArgumentError(`two rows answered with one appactionid (${h}), so the read is not one bar`);u.set(h,{obs:gJ(h,p,e,r),raw:p,codes:[],audience:null,placed:!1,chainApps:new Set,duplicate:!1,peers:[]})}let l=yJ(u);for(let p of u.values())bJ(p,u);for(let p of u.values())ZD(p,u,l);AJ(u);let c=CJ(r.project(e,t,n));for(let p of u.values())p.obs.pointer=(s=c.get(p.obs.rowId))!==null&&s!==void 0?s:null,p.obs.diagnostics=[...p.codes,...p.duplicate?["DUPLICATE_PROJECTED_ID"]:[],...p.obs.pointer===null?["NOT_PROJECTED"]:[]];let d=eP(u),f={type:"command",id:e,tableId:t,observedAt:o,rows:d.map(p=>p.obs),diagnostics:SJ(d)};return i.queries&&(f.found=i.queries.map(p=>IJ(p,u,i.appModuleId))),f}Ko.classifyCommandBar=XD;function gJ(e,t,n,r){var i,o;let a=HD(t.type),s=(i=a!==null?lJ[a]:void 0)!==null&&i!==void 0?i:"unknown",u=HD(t.location),l=zD(t,"_appmoduleid_value",e),c=ew(t,"name",e),d=ew(t,"buttonlabeltext",e),f=ew(t,"grouptitle",e),p=typeof t.sequence=="number"?t.sequence:typeof t.buttonsequencepriority=="number"?t.buttonsequencepriority:null,m={rowId:e,projectedId:r.projectedId(c,n),name:c,kind:s,label:s==="group"?"":d,groupTitle:s==="group"?f:null,location:u,surface:(o=u!==null?cJ[u]:void 0)!==null&&o!==void 0?o:null,placement:"undetermined",audienceAppId:null,scope:l?"app":"table",appModuleId:l,parentRowId:zD(t,"_parentappactionid_value",e),ancestors:[],menuPath:[],hidden:Zv(t,"hidden",e),ancestorHidden:!1,disabled:Zv(t,"isdisabled",e),managed:Zv(t,"ismanaged",e),sequence:p,pointer:null,diagnostics:[]},h=r.action(t);return h&&(m.action=h),m}function yJ(e){var t,n;let r=new Set,i=new Set;for(let o of e.keys()){let a=[],s=new Set,u=o;for(;u!==null&&e.has(u)&&!i.has(u)&&!s.has(u);)a.push(u),s.add(u),u=(n=(t=e.get(u))===null||t===void 0?void 0:t.obs.parentRowId)!==null&&n!==void 0?n:null;if(u!==null&&s.has(u))for(let l of a.slice(a.indexOf(u)))r.add(l);for(let l of a)i.add(l)}return r}function bJ(e,t){let n=[],r=new Set([e.obs.rowId]),i=e.obs.parentRowId;for(;i!==null&&!r.has(i);){let o=t.get(i);if(!o)break;n.push(o),r.add(i),i=o.obs.parentRowId}n.reverse(),e.obs.ancestors=n.map(o=>o.obs.rowId),e.obs.menuPath=n.filter(o=>o.obs.kind==="flyout"||o.obs.kind==="split").map(o=>o.obs.label),e.obs.ancestorHidden=n.some(o=>o.obs.hidden);for(let o of[e,...n])o.obs.appModuleId&&e.chainApps.add(o.obs.appModuleId)}function vJ(e,t){return e==="group"?t==="flyout"||t==="split":t==="group"}function ZD(e,t,n){if(e.placed)return;e.placed=!0;let r=e.obs,i=r.parentRowId!==null?t.get(r.parentRowId):void 0,o=[];if(r.kind==="unknown"&&o.push("UNKNOWN_KIND"),r.surface===null&&o.push("UNSUPPORTED_LOCATION"),r.kind!=="unknown"&&(r.parentRowId===null&&r.kind==="group"||i&&i.obs.kind!=="unknown"&&!vJ(r.kind,i.obs.kind))&&o.push("INVALID_PARENT_KIND"),n.has(r.rowId)&&o.push("CYCLE"),o.length>0){sc(e,"undetermined",o,i);return}if(i&&ZD(i,t,n),i&&i.obs.placement==="undetermined"){sc(e,"undetermined",["ANCESTOR_UNDETERMINED"],i);return}if(r.disabled){sc(e,"disabled",[],i);return}let a=[];if(r.parentRowId!==null&&!i&&a.push("PARENT_NOT_IN_BAR"),i&&i.obs.location!==r.location&&a.push("LOCATION_MISMATCH"),wJ(e,i)&&a.push("MIXED_APP_SCOPE"),a.length>0){sc(e,"unhosted",a,i);return}if(i&&i.obs.placement!=="served"){sc(e,"unhosted",["ANCESTOR_NOT_SERVED"],i);return}sc(e,"served",[],i)}function wJ(e,t){let n=e.obs.appModuleId;return!n||!t?!1:typeof t.audience=="string"&&t.audience!=="mixed"&&t.audience!==n}function sc(e,t,n,r){e.obs.placement=t,e.codes=n;let i=r&&r.placed?r.audience:null,o=e.obs.appModuleId;i==="mixed"||o&&i&&o!==i?e.audience="mixed":e.audience=o??i,e.obs.audienceAppId=e.audience==="mixed"?null:e.audience}function EJ(e,t){return e===null||t===null||e===t}function AJ(e){var t;let n=new Map;for(let r of e.values())if(r.obs.placement==="served"){let i=`${r.obs.surface}\0${r.obs.projectedId}`;n.set(i,[...(t=n.get(i))!==null&&t!==void 0?t:[],r])}for(let r of n.values())for(let i of r)i.peers=r.filter(o=>o!==i&&EJ(i.obs.audienceAppId,o.obs.audienceAppId)),i.duplicate=i.peers.length>0}function KD(e,t){return e.peers.some(n=>t===null||n.obs.audienceAppId===null||n.obs.audienceAppId===t)}function tw(e){var t;let n=(t=e?.a)===null||t===void 0?void 0:t.find(r=>r[0]==="appactionid");return typeof n?.[1]=="string"&&n[1]!==""?n[1].toLowerCase():void 0}function CJ(e){var t;let n=new Map,r=(o,a)=>{o&&!n.has(o.toLowerCase())&&n.set(o.toLowerCase(),a)},i=(o,a)=>{var s;r(tw(o.bag),a),o.flyoutGroups&&o.flyoutGroups.length>0?o.flyoutGroups.forEach((u,l)=>{var c;r((c=tw(u.bag))!==null&&c!==void 0?c:u.id,`${a}/flyoutGroups/${l}`)}):o.flyoutGroupId&&r(o.flyoutGroupId,`${a}/flyoutGroupId`),((s=o.children)!==null&&s!==void 0?s:[]).forEach((u,l)=>i(u,`${a}/children/${l}`))};return((t=e.commandBars)!==null&&t!==void 0?t:[]).forEach((o,a)=>{var s;((s=o.groups)!==null&&s!==void 0?s:[]).forEach((u,l)=>{var c;r(tw(u.bag),`/commandBars/${a}/groups/${l}`),((c=u.controls)!==null&&c!==void 0?c:[]).forEach((d,f)=>i(d,`/commandBars/${a}/groups/${l}/controls/${f}`))})}),n}function JD(e,t){var n,r;let i=((n=e.obs.sequence)!==null&&n!==void 0?n:0)-((r=t.obs.sequence)!==null&&r!==void 0?r:0);return i!==0?i:e.obs.rowId<t.obs.rowId?-1:e.obs.rowId>t.obs.rowId?1:0}function eP(e){var t;let n=new Map;for(let a of e.values())a.obs.placement==="served"&&a.obs.parentRowId!==null&&n.set(a.obs.parentRowId,[...(t=n.get(a.obs.parentRowId))!==null&&t!==void 0?t:[],a]);let r=[],i=new Set,o=a=>{var s;r.push(a),i.add(a.obs.rowId);for(let u of[...(s=n.get(a.obs.rowId))!==null&&s!==void 0?s:[]].sort(JD))o(u)};for(let a of rw)[...e.values()].filter(s=>s.obs.placement==="served"&&s.obs.parentRowId===null&&s.obs.surface===a).sort(JD).forEach(o);return[...e.values()].filter(a=>!i.has(a.obs.rowId)).sort((a,s)=>a.obs.rowId<s.obs.rowId?-1:a.obs.rowId>s.obs.rowId?1:0).forEach(a=>r.push(a)),r}var nw={UNSUPPORTED_LOCATION:e=>`Row ${e.rowId} has Location ${e.location===null?"(none)":e.location}, not a table command surface (0-3); where the runtime serves it was never measured.`,UNKNOWN_KIND:e=>`Row ${e.rowId} has an unknown type; it is not read as a button, and its serving is unmeasured.`,INVALID_PARENT_KIND:e=>`Row ${e.rowId} (${e.kind}) has a parent kind the platform refuses to store${e.parentRowId===null?" (a group at top level)":""}; its serving is unmeasured.`,CYCLE:e=>`Row ${e.rowId} is on a parent loop; its serving is unmeasured.`,PARENT_NOT_IN_BAR:e=>`Row ${e.rowId}'s parent ${e.parentRowId} is not a row of this table's bar; the runtime does not serve it.`,LOCATION_MISMATCH:e=>`Row ${e.rowId}'s Location ${e.location} differs from its parent's; the runtime serves it in neither tree.`,MIXED_APP_SCOPE:e=>`Row ${e.rowId} is bound to app ${e.appModuleId} under a chain bound to another app; it is served to neither.`,ANCESTOR_NOT_SERVED:e=>`Row ${e.rowId}'s own links are valid, but an ancestor is not served.`,ANCESTOR_UNDETERMINED:e=>`Row ${e.rowId}'s own links are valid, but an ancestor's serving is unmeasured.`,DUPLICATE_PROJECTED_ID:e=>`Served rows on ${e.surface} share the projected id '${e.projectedId}'; which one a client shows is not determined.`,NOT_PROJECTED:e=>`fetchArtifact's projection omits row ${e.rowId}.`};function SJ(e){var t;let n=[];for(let i of e)for(let o of i.codes)n.push({code:o,rowIds:[i.obs.rowId],message:nw[o](i.obs)});let r=new Map;for(let i of e)if(i.duplicate){let o=`${i.obs.surface}\0${i.obs.projectedId}`;r.set(o,[...(t=r.get(o))!==null&&t!==void 0?t:[],i])}for(let i of r.values())n.push({code:"DUPLICATE_PROJECTED_ID",rowIds:i.map(o=>o.obs.rowId),message:nw.DUPLICATE_PROJECTED_ID(i[0].obs)});for(let i of e)i.obs.pointer===null&&n.push({code:"NOT_PROJECTED",rowIds:[i.obs.rowId],message:nw.NOT_PROJECTED(i.obs)});return n}function NJ(e,t){return e.length===t.length&&e.every((n,r)=>n===t[r])}function _J(e,t,n,r){let i=e.obs;return i.surface!==null&&i.surface!==t.surface||[...e.chainApps].some(a=>a!==n)||t.kind!==void 0&&i.kind!=="unknown"&&i.kind!==t.kind||t.rowId!==void 0&&t.label!==void 0&&i.label!==t.label||i.placement==="disabled"||i.placement==="unhosted"?"ELSEWHERE":i.placement==="undetermined"||i.surface===null||t.kind!==void 0&&i.kind==="unknown"?"UNCERTAIN":NJ(i.menuPath,t.menuPath)?KD(e,n)||i.ancestors.some(a=>{let s=r.get(a);return s!==void 0&&KD(s,n)})?"UNCERTAIN":"MATCH":"ELSEWHERE"}function IJ(e,t,n){var r,i;let o=e.rowId!==void 0?"row":"caption",a=e.rowId!==void 0?[t.get(e.rowId)].filter(f=>f!==void 0):eP(t).filter(f=>f.obs.label===e.label),s=[],u=[],l=[];for(let f of a){let p=_J(f,e,n,t);p==="MATCH"?s.push(f):p==="UNCERTAIN"?l.push(f.obs.rowId):u.push(f.obs.rowId)}let c;o==="row"?c=a.length===0?"missing":s.length===1?"present":l.length>0?"indeterminate":"misplaced":l.length>0?c="indeterminate":s.length===1?c="present":s.length>1?c="ambiguous":c=u.length>0?"misplaced":"missing";let d=s.length===1?s[0].obs:void 0;return{query:{...e.original,...e.original.menuPath?{menuPath:[...e.original.menuPath]}:{}},identity:o,verdict:c,rowIds:s.map(f=>f.obs.rowId),elsewhere:u,uncertain:l,hidden:(r=d?.hidden)!==null&&r!==void 0?r:!1,ancestorHidden:(i=d?.ancestorHidden)!==null&&i!==void 0?i:!1}}});var uc=C(xa=>{"use strict";function TJ(e,t,n){if(n===void 0&&(n=Array.prototype),e&&typeof n.find=="function")return n.find.call(e,t);for(var r=0;r<e.length;r++)if(Object.prototype.hasOwnProperty.call(e,r)){var i=e[r];if(t.call(void 0,i,r,e))return i}}function uw(e,t){return t===void 0&&(t=Object),t&&typeof t.freeze=="function"?t.freeze(e):e}function OJ(e,t){if(e===null||typeof e!="object")throw new TypeError("target is not an object");for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n]);return e}var tP=uw({HTML:"text/html",isHTML:function(e){return e===tP.HTML},XML_APPLICATION:"application/xml",XML_TEXT:"text/xml",XML_XHTML_APPLICATION:"application/xhtml+xml",XML_SVG_IMAGE:"image/svg+xml"}),nP=uw({HTML:"http://www.w3.org/1999/xhtml",isHTML:function(e){return e===nP.HTML},SVG:"http://www.w3.org/2000/svg",XML:"http://www.w3.org/XML/1998/namespace",XMLNS:"http://www.w3.org/2000/xmlns/"}),Th=/[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]/,sw=new RegExp("[\\-\\.0-9"+Th.source.slice(1,-1)+"\\u00B7\\u0300-\\u036F\\u203F-\\u2040]"),DJ=new RegExp("^"+Th.source+sw.source+"*(?::"+Th.source+sw.source+"*)?$");xa.assign=OJ;xa.find=TJ;xa.freeze=uw;xa.MIME_TYPE=tP;xa.NAMESPACE=nP;xa.nameStartChar=Th;xa.nameChar=sw;xa.tagNamePattern=DJ});var ww=C(Ba=>{var lw=uc(),Jo=lw.find,Tf=lw.NAMESPACE,lc=lw.tagNamePattern;function PJ(e){return e!==""}function RJ(e){return e?e.split(/[\t\n\f\r ]+/).filter(PJ):[]}function kJ(e,t){return e.hasOwnProperty(t)||(e[t]=!0),e}function rP(e){if(!e)return[];var t=RJ(e);return Object.keys(t.reduce(kJ,{}))}function $J(e){return function(t){return e&&e.indexOf(t)!==-1}}function Df(e,t){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])}function ei(e,t){var n=e.prototype;if(!(n instanceof t)){let i=function(){};var r=i;i.prototype=t.prototype,i=new i,Df(n,i),e.prototype=n=i}n.constructor!=e&&(typeof e!="function"&&console.error("unknown Class:"+e),n.constructor=e)}var ti={},Bi=ti.ELEMENT_NODE=1,cc=ti.ATTRIBUTE_NODE=2,If=ti.TEXT_NODE=3,dP=ti.CDATA_SECTION_NODE=4,fP=ti.ENTITY_REFERENCE_NODE=5,LJ=ti.ENTITY_NODE=6,cw=ti.PROCESSING_INSTRUCTION_NODE=7,dw=ti.COMMENT_NODE=8,pP=ti.DOCUMENT_NODE=9,mP=ti.DOCUMENT_TYPE_NODE=10,Fa=ti.DOCUMENT_FRAGMENT_NODE=11,MJ=ti.NOTATION_NODE=12,mr={},Bn={},CIe=mr.INDEX_SIZE_ERR=(Bn[1]="Index size error",1),SIe=mr.DOMSTRING_SIZE_ERR=(Bn[2]="DOMString size error",2),Zr=mr.HIERARCHY_REQUEST_ERR=(Bn[3]="Hierarchy request error",3),NIe=mr.WRONG_DOCUMENT_ERR=(Bn[4]="Wrong document",4),iP=mr.INVALID_CHARACTER_ERR=(Bn[5]="Invalid character",5),_Ie=mr.NO_DATA_ALLOWED_ERR=(Bn[6]="No data allowed",6),IIe=mr.NO_MODIFICATION_ALLOWED_ERR=(Bn[7]="No modification allowed",7),hP=mr.NOT_FOUND_ERR=(Bn[8]="Not found",8),TIe=mr.NOT_SUPPORTED_ERR=(Bn[9]="Not supported",9),oP=mr.INUSE_ATTRIBUTE_ERR=(Bn[10]="Attribute in use",10),ho=mr.INVALID_STATE_ERR=(Bn[11]="Invalid state",11),OIe=mr.SYNTAX_ERR=(Bn[12]="Syntax error",12),DIe=mr.INVALID_MODIFICATION_ERR=(Bn[13]="Invalid modification",13),PIe=mr.NAMESPACE_ERR=(Bn[14]="Invalid namespace",14),RIe=mr.INVALID_ACCESS_ERR=(Bn[15]="Invalid access",15);function Ge(e,t){if(t instanceof Error)var n=t;else n=this,Error.call(this,Bn[e]),this.message=Bn[e],Error.captureStackTrace&&Error.captureStackTrace(this,Ge);return n.code=e,t&&(this.message=this.message+": "+t),n}Ge.prototype=Error.prototype;Df(mr,Ge);function Ua(){}Ua.prototype={length:0,item:function(e){return e>=0&&e<this.length?this[e]:null},toString:function(e,t,n){for(var r=!!n&&!!n.requireWellFormed,i=[],o=0;o<this.length;o++)vw(this[o],i,e,t,null,r);return i.join("")},filter:function(e){return Array.prototype.filter.call(this,e)},indexOf:function(e){return Array.prototype.indexOf.call(this,e)}};function dc(e,t){this._node=e,this._refresh=t,fw(this)}function fw(e){var t=e._node._inc||e._node.ownerDocument._inc;if(e._inc!==t){var n=e._refresh(e._node);if(TP(e,"length",n.length),!e.$$length||n.length<e.$$length)for(var r=n.length;r in e;r++)Object.prototype.hasOwnProperty.call(e,r)&&delete e[r];Df(n,e),e._inc=t}}dc.prototype.item=function(e){return fw(this),this[e]||null};ei(dc,Ua);function Dh(){this._nameIndex=Object.create(null)}function gP(e,t){for(var n=e.length;n--;)if(e[n]===t)return n}function xJ(e,t){e._nameIndex[t.nodeName]=t}function yP(e,t){e._nameIndex[t.nodeName]===t&&delete e._nameIndex[t.nodeName]}function aP(e,t,n,r){if(r?(t[gP(t,r)]=n,yP(t,r)):t[t.length++]=n,xJ(t,n),e){n.ownerElement=e;var i=e.ownerDocument;i&&(r&&wP(i,e,r),FJ(i,e,n))}}function sP(e,t,n){var r=gP(t,n);if(r>=0){for(var i=t.length-1;r<i;)t[r]=t[++r];if(t.length=i,yP(t,n),e){var o=e.ownerDocument;o&&(wP(o,e,n),n.ownerElement=null)}}else throw new Ge(hP,new Error(e.tagName+"@"+n))}Dh.prototype={length:0,item:Ua.prototype.item,getNamedItem:function(e){for(var t=this.length;t--;){var n=this[t];if(n.nodeName==e)return n}},setNamedItem:function(e){var t=e.ownerElement;if(t&&t!=this._ownerElement)throw new Ge(oP);var n=this._nameIndex[e.nodeName];return aP(this._ownerElement,this,e,n),n},setNamedItemNS:function(e){var t=e.ownerElement,n;if(t&&t!=this._ownerElement)throw new Ge(oP);return n=this.getNamedItemNS(e.namespaceURI,e.localName),aP(this._ownerElement,this,e,n),n},removeNamedItem:function(e){var t=this.getNamedItem(e);return sP(this._ownerElement,this,t),t},removeNamedItemNS:function(e,t){var n=this.getNamedItemNS(e,t);return sP(this._ownerElement,this,n),n},getNamedItemNS:function(e,t){for(var n=this.length;n--;){var r=this[n];if(r.localName==t&&r.namespaceURI==e)return r}return null}};function bP(){}bP.prototype={hasFeature:function(e,t){return!0},createDocument:function(e,t,n){var r=new Pf;if(r.implementation=this,r.childNodes=new Ua,r.doctype=n||null,n&&r.appendChild(n),t){var i=r.createElementNS(e,t);r.appendChild(i)}return r},createDocumentType:function(e,t,n){var r=new Lh;return r.name=e,r.nodeName=e,r.publicId=t||"",r.systemId=n||"",r}};function at(){}at.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 Rh(this,e,t)},replaceChild:function(e,t){Rh(this,e,t,AP),t&&this.removeChild(t)},removeChild:function(e){return EP(this,e)},appendChild:function(e){return this.insertBefore(e,null)},hasChildNodes:function(){return this.firstChild!=null},cloneNode:function(e){return IP(this.ownerDocument||this,this,e)},normalize:function(){qn(this,null,{enter:function(e){for(var t=e.firstChild;t;){var n=t.nextSibling;if(n!==null&&n.nodeType===If&&t.nodeType===If){for(var r=[],i=n;i!==null&&i.nodeType===If;)r.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(r.join("")),$h(e.ownerDocument,e),t=i}else t=n}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 n=t._nsMap;if(n){for(var r in n)if(Object.prototype.hasOwnProperty.call(n,r)&&n[r]===e)return r}t=t.nodeType==cc?t.ownerDocument:t.parentNode}return null},lookupNamespaceURI:function(e){for(var t=this;t;){var n=t._nsMap;if(n&&Object.prototype.hasOwnProperty.call(n,e))return n[e];t=t.nodeType==cc?t.ownerDocument:t.parentNode}return null},isDefaultNamespace:function(e){var t=this.lookupPrefix(e);return t==null}};function vP(e){return e=="<"&&"<"||e==">"&&">"||e=="&"&&"&"||e=='"'&&"""||"&#"+e.charCodeAt()+";"}Df(ti,at);Df(ti,at.prototype);function Ph(e,t){return qn(e,null,{enter:function(n){return t(n)?qn.STOP:!0}})===qn.STOP}function qn(e,t,n){for(var r=[{node:e,context:t,phase:qn.ENTER}];r.length>0;){var i=r.pop();if(i.phase===qn.ENTER){var o=n.enter(i.node,i.context);if(o===qn.STOP)return qn.STOP;if(r.push({node:i.node,context:o,phase:qn.EXIT}),o==null)continue;for(var a=i.node.lastChild;a;)r.push({node:a,context:o,phase:qn.ENTER}),a=a.previousSibling}else n.exit&&n.exit(i.node,i.context)}}qn.STOP=Symbol("walkDOM.STOP");qn.ENTER=0;qn.EXIT=1;function Pf(){this.ownerDocument=this}function FJ(e,t,n){e&&e._inc++;var r=n.namespaceURI;r===Tf.XMLNS&&(t._nsMap[n.prefix?n.localName:""]=n.value)}function wP(e,t,n,r){e&&e._inc++;var i=n.namespaceURI;i===Tf.XMLNS&&delete t._nsMap[n.prefix?n.localName:""]}function $h(e,t,n){if(e&&e._inc){e._inc++;var r=t.childNodes;if(n)r[r.length++]=n;else{for(var i=t.firstChild,o=0;i;)r[o++]=i,i=i.nextSibling;r.length=o,delete r[r.length]}}}function EP(e,t){var n=t.previousSibling,r=t.nextSibling;return n?n.nextSibling=r:e.firstChild=r,r?r.previousSibling=n:e.lastChild=n,t.parentNode=null,t.previousSibling=null,t.nextSibling=null,$h(e.ownerDocument,e),t}function UJ(e){return e&&(e.nodeType===at.DOCUMENT_NODE||e.nodeType===at.DOCUMENT_FRAGMENT_NODE||e.nodeType===at.ELEMENT_NODE)}function qJ(e){return e&&(Yo(e)||pw(e)||qa(e)||e.nodeType===at.DOCUMENT_FRAGMENT_NODE||e.nodeType===at.COMMENT_NODE||e.nodeType===at.PROCESSING_INSTRUCTION_NODE)}function qa(e){return e&&e.nodeType===at.DOCUMENT_TYPE_NODE}function Yo(e){return e&&e.nodeType===at.ELEMENT_NODE}function pw(e){return e&&e.nodeType===at.TEXT_NODE}function uP(e,t){var n=e.childNodes||[];if(Jo(n,Yo)||qa(t))return!1;var r=Jo(n,qa);return!(t&&r&&n.indexOf(r)>n.indexOf(t))}function lP(e,t){var n=e.childNodes||[];function r(o){return Yo(o)&&o!==t}if(Jo(n,r))return!1;var i=Jo(n,qa);return!(t&&i&&n.indexOf(i)>n.indexOf(t))}function BJ(e,t,n){if(!UJ(e))throw new Ge(Zr,"Unexpected parent node type "+e.nodeType);if(n&&n.parentNode!==e)throw new Ge(hP,"child not in parent");if(!qJ(t)||qa(t)&&e.nodeType!==at.DOCUMENT_NODE)throw new Ge(Zr,"Unexpected node type "+t.nodeType+" for parent node type "+e.nodeType)}function VJ(e,t,n){var r=e.childNodes||[],i=t.childNodes||[];if(t.nodeType===at.DOCUMENT_FRAGMENT_NODE){var o=i.filter(Yo);if(o.length>1||Jo(i,pw))throw new Ge(Zr,"More than one element or text in fragment");if(o.length===1&&!uP(e,n))throw new Ge(Zr,"Element in fragment can not be inserted before doctype")}if(Yo(t)&&!uP(e,n))throw new Ge(Zr,"Only one element can be added and only after doctype");if(qa(t)){if(Jo(r,qa))throw new Ge(Zr,"Only one doctype is allowed");var a=Jo(r,Yo);if(n&&r.indexOf(a)<r.indexOf(n))throw new Ge(Zr,"Doctype can only be inserted before an element");if(!n&&a)throw new Ge(Zr,"Doctype can not be appended since element is present")}}function AP(e,t,n){var r=e.childNodes||[],i=t.childNodes||[];if(t.nodeType===at.DOCUMENT_FRAGMENT_NODE){var o=i.filter(Yo);if(o.length>1||Jo(i,pw))throw new Ge(Zr,"More than one element or text in fragment");if(o.length===1&&!lP(e,n))throw new Ge(Zr,"Element in fragment can not be inserted before doctype")}if(Yo(t)&&!lP(e,n))throw new Ge(Zr,"Only one element can be added and only after doctype");if(qa(t)){let u=function(l){return qa(l)&&l!==n};var s=u;if(Jo(r,u))throw new Ge(Zr,"Only one doctype is allowed");var a=Jo(r,Yo);if(n&&r.indexOf(a)<r.indexOf(n))throw new Ge(Zr,"Doctype can only be inserted before an element")}}function Rh(e,t,n,r){BJ(e,t,n),e.nodeType===at.DOCUMENT_NODE&&(r||VJ)(e,t,n);var i=t.parentNode;if(i&&i.removeChild(t),t.nodeType===Fa){var o=t.firstChild;if(o==null)return t;var a=t.lastChild}else o=a=t;var s=n?n.previousSibling:e.lastChild;o.previousSibling=s,a.nextSibling=n,s?s.nextSibling=o:e.firstChild=o,n==null?e.lastChild=a:n.previousSibling=a;do{o.parentNode=e;var u=e.ownerDocument||e;Of(o,u)}while(o!==a&&(o=o.nextSibling));return $h(e.ownerDocument||e,e),t.nodeType==Fa&&(t.firstChild=t.lastChild=null),t}function Of(e,t){if(e.ownerDocument!==t){if(e.ownerDocument=t,e.nodeType===Bi&&e.attributes)for(var n=0;n<e.attributes.length;n++){var r=e.attributes.item(n);r&&(r.ownerDocument=t)}for(var i=e.firstChild;i;)Of(i,t),i=i.nextSibling}}function GJ(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,$h(e.ownerDocument,e,t);var n=e.ownerDocument||e;return Of(t,n),t}Pf.prototype={nodeName:"#document",nodeType:pP,doctype:null,documentElement:null,_inc:1,insertBefore:function(e,t){if(e.nodeType==Fa){for(var n=e.firstChild;n;){var r=n.nextSibling;this.insertBefore(n,t),n=r}return e}return Rh(this,e,t),Of(e,this),this.documentElement===null&&e.nodeType===Bi&&(this.documentElement=e),e},removeChild:function(e){return this.documentElement==e&&(this.documentElement=null),EP(this,e)},replaceChild:function(e,t){Rh(this,e,t,AP),Of(e,this),t&&this.removeChild(t),Yo(e)&&(this.documentElement=e)},importNode:function(e,t){return jJ(this,e,t)},getElementById:function(e){var t=null;return Ph(this.documentElement,function(n){if(n.nodeType==Bi&&n.getAttribute("id")==e)return t=n,!0}),t},getElementsByClassName:function(e){var t=rP(e);return new dc(this,function(n){var r=[];return t.length>0&&Ph(n.documentElement,function(i){if(i!==n&&i.nodeType===Bi){var o=i.getAttribute("class");if(o){var a=e===o;if(!a){var s=rP(o);a=t.every($J(s))}a&&r.push(i)}}}),r})},createElement:function(e){var t=new Bu;t.ownerDocument=this,t.nodeName=e,t.tagName=e,t.localName=e,t.childNodes=new Ua;var n=t.attributes=new Dh;return n._ownerElement=t,t},createDocumentFragment:function(){var e=new Mh;return e.ownerDocument=this,e.childNodes=new Ua,e},createTextNode:function(e){var t=new mw;return t.ownerDocument=this,t.appendData(e),t},createComment:function(e){var t=new hw;return t.ownerDocument=this,t.appendData(e),t},createCDATASection:function(e){if(e.indexOf("]]>")!==-1)throw new Ge(iP,'data contains "]]>"');var t=new gw;return t.ownerDocument=this,t.appendData(e),t},createProcessingInstruction:function(e,t){var n=new bw;return n.ownerDocument=this,n.tagName=n.nodeName=n.target=e,n.nodeValue=n.data=t,n},createAttribute:function(e){var t=new kh;return t.ownerDocument=this,t.name=e,t.nodeName=e,t.localName=e,t.specified=!0,t},createEntityReference:function(e){if(!lc.test(e))throw new Ge(iP,'not a valid xml name "'+e+'"');var t=new yw;return t.ownerDocument=this,t.nodeName=e,t},createElementNS:function(e,t){var n=new Bu,r=t.split(":"),i=n.attributes=new Dh;return n.childNodes=new Ua,n.ownerDocument=this,n.nodeName=t,n.tagName=t,n.namespaceURI=e,r.length==2?(n.prefix=r[0],n.localName=r[1]):n.localName=t,i._ownerElement=n,n},createAttributeNS:function(e,t){var n=new kh,r=t.split(":");return n.ownerDocument=this,n.nodeName=t,n.name=t,n.namespaceURI=e,n.specified=!0,r.length==2?(n.prefix=r[0],n.localName=r[1]):n.localName=t,n}};ei(Pf,at);function Bu(){this._nsMap={}}Bu.prototype={nodeType:Bi,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 n=this.ownerDocument.createAttribute(e);n.value=n.nodeValue=""+t,this.setAttributeNode(n)},removeAttribute:function(e){var t=this.getAttributeNode(e);t&&this.removeAttributeNode(t)},appendChild:function(e){return e.nodeType===Fa?this.insertBefore(e,null):GJ(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 n=this.getAttributeNodeNS(e,t);n&&this.removeAttributeNode(n)},hasAttributeNS:function(e,t){return this.getAttributeNodeNS(e,t)!=null},getAttributeNS:function(e,t){var n=this.getAttributeNodeNS(e,t);return n&&n.value||""},setAttributeNS:function(e,t,n){var r=this.ownerDocument.createAttributeNS(e,t);r.value=r.nodeValue=""+n,this.setAttributeNode(r)},getAttributeNodeNS:function(e,t){return this.attributes.getNamedItemNS(e,t)},getElementsByTagName:function(e){return new dc(this,function(t){var n=[];return Ph(t,function(r){r!==t&&r.nodeType==Bi&&(e==="*"||r.tagName==e)&&n.push(r)}),n})},getElementsByTagNameNS:function(e,t){return new dc(this,function(n){var r=[];return Ph(n,function(i){i!==n&&i.nodeType===Bi&&(e==="*"||i.namespaceURI===e)&&(t==="*"||i.localName==t)&&r.push(i)}),r})}};Pf.prototype.getElementsByTagName=Bu.prototype.getElementsByTagName;Pf.prototype.getElementsByTagNameNS=Bu.prototype.getElementsByTagNameNS;ei(Bu,at);function kh(){}kh.prototype.nodeType=cc;ei(kh,at);function Rf(){}Rf.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(Bn[Zr])},deleteData:function(e,t){this.replaceData(e,t,"")},replaceData:function(e,t,n){var r=this.data.substring(0,e),i=this.data.substring(e+t);n=r+n+i,this.nodeValue=this.data=n,this.length=n.length}};ei(Rf,at);function mw(){}mw.prototype={nodeName:"#text",nodeType:If,splitText:function(e){var t=this.data,n=t.substring(e);t=t.substring(0,e),this.data=this.nodeValue=t,this.length=t.length;var r=this.ownerDocument.createTextNode(n);return this.parentNode&&this.parentNode.insertBefore(r,this.nextSibling),r}};ei(mw,Rf);function hw(){}hw.prototype={nodeName:"#comment",nodeType:dw};ei(hw,Rf);function gw(){}gw.prototype={nodeName:"#cdata-section",nodeType:dP};ei(gw,Rf);function Lh(){}Lh.prototype.nodeType=mP;ei(Lh,at);function CP(){}CP.prototype.nodeType=MJ;ei(CP,at);function SP(){}SP.prototype.nodeType=LJ;ei(SP,at);function yw(){}yw.prototype.nodeType=fP;ei(yw,at);function Mh(){}Mh.prototype.nodeName="#document-fragment";Mh.prototype.nodeType=Fa;ei(Mh,at);function bw(){}bw.prototype.nodeType=cw;ei(bw,at);function NP(){}NP.prototype.serializeToString=function(e,t,n,r){return _P.call(e,t,n,r)};at.prototype.toString=_P;function _P(e,t,n){var r=!!n&&!!n.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 u=[{namespace:s,prefix:null}]}return vw(this,i,e,t,u,r),i.join("")}function cP(e,t,n){var r=e.prefix||"",i=e.namespaceURI;if(!i||r==="xml"&&i===Tf.XML||i===Tf.XMLNS)return!1;for(var o=n.length;o--;){var a=n[o];if(a.prefix===r)return a.namespace!==i}return!0}function Oh(e,t,n,r){if(r&&!lc.test(t))throw new Ge(ho,'The attribute name "'+t+'" is not a valid XML QName');e.push(" ",t,'="',n.replace(/[<>&"\t\n\r]/g,vP),'"')}function vw(e,t,n,r,i,o){i||(i=[]),qn(e,{ns:i,isHTML:n},{enter:function(a,s){var u=s.ns,l=s.isHTML;if(r)if(a=r(a),a){if(typeof a=="string")return t.push(a),null}else return null;switch(a.nodeType){case Bi:var c=a.attributes,d=c.length,f=a.tagName;l=Tf.isHTML(a.namespaceURI)||l;var p=f;if(!l&&!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=u.length-1;g>=0;g--){var y=u[g];if(y.prefix===""&&y.namespace===a.namespaceURI){m=y.namespace;break}}if(m!==a.namespaceURI)for(var g=u.length-1;g>=0;g--){var y=u[g];if(y.namespace===a.namespaceURI){y.prefix&&(p=y.prefix+":"+f);break}}}if(o&&!lc.test(p))throw new Ge(ho,'The element name "'+p+'" is not a valid XML QName');t.push("<",p);for(var b=u.slice(),E=0;E<d;E++){var w=c.item(E);w.prefix=="xmlns"?b.push({prefix:w.localName,namespace:w.value}):w.nodeName=="xmlns"&&b.push({prefix:"",namespace:w.value})}for(var E=0;E<d;E++){var w=c.item(E);if(cP(w,l,b)){var _=w.prefix||"",I=w.namespaceURI;Oh(t,_?"xmlns:"+_:"xmlns",I,o),b.push({prefix:_,namespace:I})}var T=r?r(w):w;T&&(typeof T=="string"?t.push(T):Oh(t,T.name,T.value,o))}if(f===p&&cP(a,l,b)){var O=a.prefix||"",I=a.namespaceURI;Oh(t,O?"xmlns:"+O:"xmlns",I,o),b.push({prefix:O,namespace:I})}var v=a.firstChild;if(v||l&&!/^(?:meta|link|img|br|hr|input)$/i.test(f)){if(t.push(">"),l&&/^script$/i.test(f)){for(;v;)v.data?t.push(v.data):vw(v,t,l,r,b.slice(),o),v=v.nextSibling;return t.push("</",f,">"),null}return{ns:b,isHTML:l,tag:p}}else return t.push("/>"),null;case pP:case Fa:return{ns:u.slice(),isHTML:l,tag:null};case cc:return Oh(t,a.name,a.value,o),null;case If:return t.push(a.data.replace(/[<&>]/g,vP)),null;case dP:if(o&&a.data.indexOf("]]>")!==-1)throw new Ge(ho,'The CDATASection data contains "]]>"');return t.push("<![CDATA[",a.data.replace(/]]>/g,"]]]]><![CDATA[>"),"]]>"),null;case dw:if(o&&a.data.indexOf("-->")!==-1)throw new Ge(ho,'The comment node data contains "-->"');return t.push("<!--",a.data,"-->"),null;case mP:if(o){if(!lc.test(a.name))throw new Ge(ho,'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 Ge(ho,"DocumentType publicId is not a valid PubidLiteral");if(a.systemId&&!/^("[^"]*"|'[^']*')$/.test(a.systemId))throw new Ge(ho,"DocumentType systemId is not a valid SystemLiteral");if(a.internalSubset&&a.internalSubset.indexOf("]>")!==-1)throw new Ge(ho,'DocumentType internalSubset contains "]>"')}var N=a.publicId,S=a.systemId;if(t.push("<!DOCTYPE ",a.name),N)t.push(" PUBLIC ",N),S&&S!="."&&t.push(" ",S),t.push(">");else if(S&&S!=".")t.push(" SYSTEM ",S,">");else{var R=a.internalSubset;R&&t.push(" [",R,"]"),t.push(">")}return null;case cw:if(o){if(!lc.test(a.target)||a.target.indexOf(":")!==-1||a.target.toLowerCase()==="xml")throw new Ge(ho,'The processing instruction target "'+a.target+'" is not a valid XML NCName or is reserved');if(a.data.indexOf("?>")!==-1)throw new Ge(ho,'The ProcessingInstruction data contains "?>"')}return t.push("<?",a.target," ",a.data,"?>"),null;case fP:if(o&&!lc.test(a.nodeName))throw new Ge(ho,'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 jJ(e,t,n){var r;return qn(t,null,{enter:function(i,o){var a=i.cloneNode(!1);a.ownerDocument=e,a.parentNode=null,o===null?r=a:o.appendChild(a);var s=i.nodeType===cc||n;return s?a:null}}),r}function IP(e,t,n){var r;return qn(t,null,{enter:function(i,o){var a=new i.constructor;for(var s in i)if(Object.prototype.hasOwnProperty.call(i,s)){var u=i[s];typeof u!="object"&&u!=a[s]&&(a[s]=u)}i.childNodes&&(a.childNodes=new Ua),a.ownerDocument=e;var l=n;switch(a.nodeType){case Bi:var c=i.attributes,d=a.attributes=new Dh,f=c.length;d._ownerElement=a;for(var p=0;p<f;p++)a.setAttributeNode(IP(e,c.item(p),!0));break;case cc:l=!0}return o!==null?o.appendChild(a):r=a,l?a:null}}),r}function TP(e,t,n){e[t]=n}try{Object.defineProperty&&(Object.defineProperty(dc.prototype,"length",{get:function(){return fw(this),this.$$length}}),Object.defineProperty(at.prototype,"textContent",{get:function(){if(this.nodeType===Bi||this.nodeType===Fa){var e=[];return qn(this,null,{enter:function(t){if(t.nodeType===Bi||t.nodeType===Fa)return!0;if(t.nodeType===cw||t.nodeType===dw)return null;e.push(t.nodeValue)}}),e.join("")}return this.nodeValue},set:function(e){switch(this.nodeType){case Bi:case Fa: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}}}),TP=function(e,t,n){e["$$"+t]=n})}catch{}Ba.DocumentType=Lh;Ba.DOMException=Ge;Ba.DOMImplementation=bP;Ba.Element=Bu;Ba.Node=at;Ba.NodeList=Ua;Ba.walkDOM=qn;Ba.XMLSerializer=NP});var DP=C(kf=>{"use strict";var OP=uc().freeze;kf.XML_ENTITIES=OP({amp:"&",apos:"'",gt:">",lt:"<",quot:'"'});kf.HTML_ENTITIES=OP({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"});kf.entityMap=kf.HTML_ENTITIES});var LP=C(Aw=>{var Mf=uc().NAMESPACE,Ew=uc().tagNamePattern,fc=0,Ls=1,pc=2,$f=3,mc=4,hc=5,Lf=6,xh=7;function gc(e,t){this.message=e,this.locator=t,Error.captureStackTrace&&Error.captureStackTrace(this,gc)}gc.prototype=new Error;gc.prototype.name=gc.name;function kP(){}kP.prototype={parse:function(e,t,n){var r=this.domBuilder;r.startDocument(),JJ(t,t={}),WJ(e,t,n,r,this.errorHandler),r.endDocument()}};function WJ(e,t,n,r,i){function o(M){if(M>65535){M-=65536;var q=55296+(M>>10),X=56320+(M&1023);return String.fromCharCode(q,X)}else return String.fromCharCode(M)}function a(M){var q=M.slice(1,-1);return Object.hasOwnProperty.call(n,q)?n[q]:q.charAt(0)==="#"?o(parseInt(q.substr(1).replace("x","0x"))):(i.error("entity not found:"+M),M)}function s(M){if(M>h){var q=e.substring(h,M).replace(/&#?\w+;/g,a);f&&u(h),r.characters(q,0,M-h),h=M}}function u(M,q){for(;M>=c&&(q=d.exec(e));)l=q.index,c=l+q[0].length,f.lineNumber++;f.columnNumber=M-l+1}for(var l=0,c=0,d=/.*(?:\r\n?|\n)|.*$/g,f=r.locator,p=[{currentNSMap:t}],m={},h=0;;){try{var g=e.indexOf("<",h);if(g<0){if(!e.substr(h).match(/^\s*$/)){var y=r.doc,b=y.createTextNode(e.substr(h));y.appendChild(b),r.currentElement=b}return}switch(g>h&&s(g),e.charAt(g+1)){case"/":var S=e.indexOf(">",g+3),E=e.substring(g+2,S).replace(/^([\s\S]*?[^ \t\n\r])?[ \t\n\r]*$/,"$1"),w=p.pop();S<0?(E=e.substring(g+2).replace(/[\s<].*/,""),i.error("end tag name: "+E+" is not complete:"+w.tagName),S=g+1+E.length):E.match(/\s</)?(E=E.replace(/[\s<].*/,""),i.error("end tag name: "+E+" maybe not complete"),S=g+1+E.length):/[ \t\n\r]/.test(E)&&Ew.test(E.split(/[ \t\n\r]/)[0])&&i.error('end tag name is followed by whitespace and trailing content: "'+E+'"');var _=w.localNSMap,I=w.tagName==E,T=I||w.tagName&&w.tagName.toLowerCase()==E.toLowerCase();if(T){if(r.endElement(w.uri,w.localName,E),_)for(var O in _)Object.prototype.hasOwnProperty.call(_,O)&&r.endPrefixMapping(O);I||i.fatalError("end tag name: "+E+" is not match the current start tagName:"+w.tagName)}else p.push(w);S++;break;case"?":f&&u(g),S=QJ(e,g,r);break;case"!":f&&u(g),S=YJ(e,g,r,i);break;default:f&&u(g);var v=new $P,N=p[p.length-1].currentNSMap,S=zJ(e,g,v,N,a,i),R=v.length;if(!v.closed&&KJ(e,S,v.tagName,m)&&(v.closed=!0,n.nbsp||i.warning("unclosed xml attribute")),f&&R){for(var x=PP(f,{}),G=0;G<R;G++){var U=v[G];u(U.offset),U.locator=PP(f,{})}r.locator=x,RP(v,r,N)&&p.push(v),r.locator=f}else RP(v,r,N)&&p.push(v);Mf.isHTML(v.uri)&&!v.closed?S=HJ(e,S,v.tagName,a,r):S++}}catch(M){if(M instanceof gc)throw M;i.error("element parse error: "+M),S=-1}S>h?h=S:s(Math.max(g,h)+1)}}function PP(e,t){return t.lineNumber=e.lineNumber,t.columnNumber=e.columnNumber,t}function zJ(e,t,n,r,i,o){function a(p,m,h){n.attributeNames.hasOwnProperty(p)&&o.fatalError("Attribute "+p+" redefined"),n.addValue(p,m.replace(/[\t\n\r]/g," ").replace(/&#?\w+;/g,i),h)}for(var s,u,l=++t,c=fc;;){var d=e.charAt(l);if(c===fc&&d==="<")throw new Error("unexpected < in tag name: "+e.slice(t,l));switch(d){case"=":if(c===Ls)s=e.slice(t,l),c=$f;else if(c===pc)c=$f;else throw new Error("attribute equal must after attrName");break;case"'":case'"':if(c===$f||c===Ls)if(c===Ls&&(o.warning('attribute value must after "="'),s=e.slice(t,l)),t=l+1,l=e.indexOf(d,t),l>0)u=e.slice(t,l),a(s,u,t-1),c=hc;else throw new Error("attribute value no end '"+d+"' match");else if(c==mc)u=e.slice(t,l),a(s,u,t),o.warning('attribute "'+s+'" missed start quot('+d+")!!"),t=l+1,c=hc;else throw new Error('attribute value must after "="');break;case"/":switch(c){case fc:n.setTagName(e.slice(t,l));case hc:case Lf:case xh:c=xh,n.closed=!0;case mc:case Ls:break;case pc:n.closed=!0;break;default:throw new Error("attribute invalid close char('/')")}break;case"":return o.error("unexpected end of input"),c==fc&&n.setTagName(e.slice(t,l)),l;case">":switch(c){case fc:n.setTagName(e.slice(t,l));case hc:case Lf:case xh:break;case mc:case Ls:u=e.slice(t,l),u.slice(-1)==="/"&&(n.closed=!0,u=u.slice(0,-1));case pc:c===pc&&(u=s),c==mc?(o.warning('attribute "'+u+'" missed quot(")!'),a(s,u,t)):((!Mf.isHTML(r[""])||!u.match(/^(?:disabled|checked|selected)$/i))&&o.warning('attribute "'+u+'" missed value!! "'+u+'" instead!!'),a(u,u,t));break;case $f:throw new Error("attribute value missed!!")}return l;case"\x80":d=" ";default:if(d<=" ")switch(c){case fc:n.setTagName(e.slice(t,l)),c=Lf;break;case Ls:s=e.slice(t,l),c=pc;break;case mc:var u=e.slice(t,l);o.warning('attribute "'+u+'" missed quot(")!!'),a(s,u,t);case hc:c=Lf;break}else switch(c){case pc:var f=n.tagName;(!Mf.isHTML(r[""])||!s.match(/^(?:disabled|checked|selected)$/i))&&o.warning('attribute "'+s+'" missed value!! "'+s+'" instead2!!'),a(s,s,t),t=l,c=Ls;break;case hc:o.warning('attribute space is required"'+s+'"!!');case Lf:c=Ls,t=l;break;case $f:c=mc,t=l;break;case xh:throw new Error("elements closed character '/' and '>' must be connected to")}}l++}}function RP(e,t,n){for(var r=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 u=o.prefix=a.slice(0,f),l=a.slice(f+1),c=u==="xmlns"&&l;else l=a,u=null,c=a==="xmlns"&&"";o.localName=l,c!==!1&&(i==null&&(i={},n=Object.create(n)),n[c]=i[c]=s,o.uri=Mf.XMLNS,t.startPrefixMapping(c,s))}for(var d=e.length;d--;){o=e[d];var u=o.prefix;u&&(u==="xml"&&(o.uri=Mf.XML),u!=="xmlns"&&(o.uri=n[u||""]))}var f=r.indexOf(":");f>0?(u=e.prefix=r.slice(0,f),l=e.localName=r.slice(f+1)):(u=null,l=e.localName=r);var p=e.uri=n[u||""];if(t.startElement(p,l,r,e),e.closed){if(t.endElement(p,l,r),i)for(u in i)Object.prototype.hasOwnProperty.call(i,u)&&t.endPrefixMapping(u)}else return e.currentNSMap=n,e.localNSMap=i,!0}function HJ(e,t,n,r,i){if(/^(?:script|textarea)$/i.test(n)){var o=e.indexOf("</"+n+">",t),a=e.substring(t+1,o);if(/[&<]/.test(a))return/^script$/i.test(n)?(i.characters(a,0,a.length),o):(a=a.replace(/&#?\w+;/g,r),i.characters(a,0,a.length),o)}return t+1}function KJ(e,t,n,r){var i=r[n];return i==null&&(i=e.lastIndexOf("</"+n+">"),i<t&&(i=e.lastIndexOf("</"+n)),r[n]=i),i<t}function JJ(e,t){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])}function YJ(e,t,n,r){var i=e.charAt(t+2);switch(i){case"-":if(e.charAt(t+3)==="-"){var o=e.indexOf("-->",t+4);return o>t?(n.comment(e,t+4,o-t-4),o+3):(r.error("Unclosed comment"),-1)}else return-1;default:if(e.substr(t+3,6)=="CDATA["){var o=e.indexOf("]]>",t+9);return n.startCDATA(),n.characters(e,t+9,o-t-9),n.endCDATA(),o+3}var a=XJ(e,t),s=a.length;if(s>1&&/!doctype/i.test(a[0][0])){var u=a[1][0],l=!1,c=!1;s>3&&(/^public$/i.test(a[2][0])?(l=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 n.startDTD(u,l,c),n.endDTD(),d.index+d[0].length}}return-1}function QJ(e,t,n){var r=e.indexOf("?>",t);if(r){var i=e.substring(t,r).match(/^<\?(\S*)\s*([\s\S]*?)$/);if(i){var o=i[0].length;return n.processingInstruction(i[1],i[2]),r+2}else return-1}return-1}function $P(){this.attributeNames={}}$P.prototype={setTagName:function(e){if(!Ew.test(e))throw new Error("invalid tagName:"+e);this.tagName=e},addValue:function(e,t,n){if(!Ew.test(e))throw new Error("invalid attribute:"+e);this.attributeNames[e]=this.length,this[this.length++]={qName:e,value:t,offset:n}},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 XJ(e,t){var n,r=[],i=/'[^']+'|"[^"]+"|[^\s<>\/=]+=?|(\/?\s*>|<)/g;for(i.lastIndex=t,i.exec(e);n=i.exec(e);)if(r.push(n),n[1])return r}Aw.XMLReader=kP;Aw.ParseError=gc});var VP=C(Uh=>{var ZJ=uc(),eY=ww(),MP=DP(),UP=LP(),tY=eY.DOMImplementation,xP=ZJ.NAMESPACE,nY=UP.ParseError,rY=UP.XMLReader;function qP(e){return e.replace(/\r[\n\u0085]/g,`+`).replace(/[\r\u0085\u2028]/g,`+`)}function BP(e){this.options=e||{locator:{}}}BP.prototype.parseFromString=function(e,t){var n=this.options,r=new rY,i=n.domBuilder||new xf,o=n.errorHandler,a=n.locator,s=n.xmlns||{},u=/\/x?html?$/.test(t),l=u?MP.HTML_ENTITIES:MP.XML_ENTITIES;a&&i.setDocumentLocator(a),r.errorHandler=iY(o,i,a),r.domBuilder=n.domBuilder||i,u&&(s[""]=xP.HTML),s.xml=s.xml||xP.XML;var c=n.normalizeLineEndings||qP;return e&&typeof e=="string"?r.parse(c(e),s,l):r.errorHandler.error("invalid doc source"),i.doc};function iY(e,t,n){if(!e){if(t instanceof xf)return t;e=t}var r={},i=e instanceof Function;n=n||{};function o(a){var s=e[a];!s&&i&&(s=e.length==2?function(u){e(a,u)}:e),r[a]=s&&function(u){s("[xmldom "+a+"] "+u+Cw(n))}||function(){}}return o("warning"),o("error"),o("fatalError"),r}function xf(){this.cdata=!1}function yc(e,t){t.lineNumber=e.lineNumber,t.columnNumber=e.columnNumber}xf.prototype={startDocument:function(){this.doc=new tY().createDocument(null,null,null),this.locator&&(this.doc.documentURI=this.locator.systemId)},startElement:function(e,t,n,r){var i=this.doc,o=i.createElementNS(e,n||t),a=r.length;Fh(this,o),this.currentElement=o,this.locator&&yc(this.locator,o);for(var s=0;s<a;s++){var e=r.getURI(s),u=r.getValue(s),n=r.getQName(s),l=i.createAttributeNS(e,n);this.locator&&yc(r.getLocator(s),l),l.value=l.nodeValue=u,o.setAttributeNode(l)}},endElement:function(e,t,n){var r=this.currentElement,i=r.tagName;this.currentElement=r.parentNode},startPrefixMapping:function(e,t){},endPrefixMapping:function(e){},processingInstruction:function(e,t){var n=this.doc.createProcessingInstruction(e,t);this.locator&&yc(this.locator,n),Fh(this,n)},ignorableWhitespace:function(e,t,n){},characters:function(e,t,n){if(e=FP.apply(this,arguments),e){if(this.cdata)var r=this.doc.createCDATASection(e);else var r=this.doc.createTextNode(e);this.currentElement?this.currentElement.appendChild(r):/^\s*$/.test(e)&&this.doc.appendChild(r),this.locator&&yc(this.locator,r)}},skippedEntity:function(e){},endDocument:function(){this.doc.normalize()},setDocumentLocator:function(e){(this.locator=e)&&(e.lineNumber=0)},comment:function(e,t,n){e=FP.apply(this,arguments);var r=this.doc.createComment(e);this.locator&&yc(this.locator,r),Fh(this,r)},startCDATA:function(){this.cdata=!0},endCDATA:function(){this.cdata=!1},startDTD:function(e,t,n){var r=this.doc.implementation;if(r&&r.createDocumentType){var i=r.createDocumentType(e,t,n);this.locator&&yc(this.locator,i),Fh(this,i),this.doc.doctype=i}},warning:function(e){console.warn("[xmldom warning] "+e,Cw(this.locator))},error:function(e){console.error("[xmldom error] "+e,Cw(this.locator))},fatalError:function(e){throw new nY(e,this.locator)}};function Cw(e){if(e)return`+@`+(e.systemId||"")+"#[line:"+e.lineNumber+",col:"+e.columnNumber+"]"}function FP(e,t,n){return typeof e=="string"?e.substr(t,n):e.length>=t+n||t?new java.lang.String(e,t,n)+"":e}"endDTD,startEntity,endEntity,attributeDecl,elementDecl,externalEntityDecl,internalEntityDecl,resolveEntity,getExternalSubset,notationDecl,unparsedEntityDecl".replace(/\w+/g,function(e){xf.prototype[e]=function(){return null}});function Fh(e,t){e.currentElement?e.currentElement.appendChild(t):e.doc.appendChild(t)}Uh.__DOMHandler=xf;Uh.normalizeLineEndings=qP;Uh.DOMParser=BP});var Ms=C(qh=>{var GP=ww();qh.DOMImplementation=GP.DOMImplementation;qh.XMLSerializer=GP.XMLSerializer;qh.DOMParser=VP().DOMParser});var Nw=C(bc=>{"use strict";Object.defineProperty(bc,"__esModule",{value:!0});bc.deleteAppCascade=bc.collectGenPageIds=void 0;var oY=vc(),aY=Y(),Sw=ae(),sY=Ms();function jP(e){let t=[],n=s=>u=>t.push(`${s}: ${u}`),r=new sY.DOMParser({errorHandler:{warning:n("warning"),error:n("error"),fatalError:n("fatalError")}}).parseFromString(e,"text/xml"),i=r?.documentElement;if(!i||t.length>0)throw new aY.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 l=s.getAttribute("GenPageId");l&&o.push((0,Sw.normalizeGuid)(l,"GenPageId"))}let u=s.childNodes;for(let l=0;l<u.length;l+=1){let c=u[l];c.nodeType===1&&a(c)}};return a(i),o}bc.collectGenPageIds=jP;async function uY(e,t,n){let r=(0,Sw.normalizeGuid)(t,"appModuleId");(0,Sw.normalizeGuid)(n,"appModuleIdUnique");let i=[],o=[],a=[];await(0,oY.deleteAppResolvingOnce)(e,r,u=>{u!==void 0&&a.push(...jP(u))}),i.push({type:"app",id:r});let s=[...new Set(a)].map(u=>({type:"genPage",id:u}));return{success:o.length===0,deleted:i,failures:o,retained:s}}bc.deleteAppCascade=uY});var Vh=C(Oi=>{"use strict";Object.defineProperty(Oi,"__esModule",{value:!0});Oi.observeGenPageTargets=Oi.findMissingGenPages=Oi.GENPAGE_LOOKUP_CHUNK=Oi.GENPAGE_COMPONENT_NAME=void 0;var lY=Ke(),Bh=ae();Oi.GENPAGE_COMPONENT_NAME="uxagentproject";Oi.GENPAGE_LOOKUP_CHUNK=50;async function cY(e,t,n){let r=[...new Set(t.map(o=>(0,Bh.normalizeGuid)(o,"uxagentprojectid")))],i=new Set;for(let o=0;o<r.length;o+=Oi.GENPAGE_LOOKUP_CHUNK){let a=r.slice(o,o+Oi.GENPAGE_LOOKUP_CHUNK),s="/uxagentprojects/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,Bh.odataQuery)([["$select","uxagentprojectid"],["$filter",a.map(l=>`uxagentprojectid eq ${l}`).join(" or ")]]),u=await(0,lY.collectPages)(e,s,n);for(let l of u){let c=l.uxagentprojectid;typeof c=="string"&&c.trim()!==""&&i.add((0,Bh.normalizeGuid)(c,"uxagentprojectid"))}}return r.filter(o=>!i.has(o))}Oi.findMissingGenPages=cY;function dY(e,t,n){if(!e)return;let r=new Set(n);for(let i of new Set(t.map(o=>(0,Bh.normalizeGuid)(o,"uxagentprojectid"))))e.observe({guard:"dependency",componentName:Oi.GENPAGE_COMPONENT_NAME,componentId:i,status:r.has(i)?"absent":"present"})}Oi.observeGenPageTargets=dY});var Ff=C(Vn=>{"use strict";Object.defineProperty(Vn,"__esModule",{value:!0});Vn.applyAppSettings=Vn.setAppSetting=Vn.readAppSettings=Vn.resolveSettingDefinitions=Vn.APP_SETTING_UNSET=Vn.APP_SETTING_OFF=Vn.APP_SETTING_ON=Vn.HEADER_AND_NAVIGATION_REFRESH=void 0;var Gh=Ke(),HP=pe(),Va=ae();Vn.HEADER_AND_NAVIGATION_REFRESH="HeaderAndNavigationRefresh";Vn.APP_SETTING_ON="2";Vn.APP_SETTING_OFF="1";Vn.APP_SETTING_UNSET="0";function KP(e,t){return"/appsettings/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,Va.odataQuery)([["$select",e],["$filter",t]])}async function JP(e,t){let n=[...new Set(t.filter(Boolean))],r=new Map;if(n.length===0)return r;let i=n.map(s=>`uniquename eq '${(0,Va.odataLiteral)(s)}'`).join(" or "),o=`/settingdefinitions${(0,Va.odataQuery)([["$select","settingdefinitionid,uniquename,displayname"],["$filter",i]])}`,a=(await(0,Gh.collectPages)(e,o,"the setting definitions")).filter(Boolean);for(let s of a)s.uniquename&&r.set(s.uniquename,s);return r}Vn.resolveSettingDefinitions=JP;async function fY(e,t){let n=(0,Va.normalizeGuid)(t,"App id"),r=KP("appsettingid,value,_settingdefinitionid_value",`_parentappmoduleid_value eq ${n}`),i=(await(0,Gh.collectPages)(e,r,"readAppSettings")).filter(Boolean);if(i.length===0)return[];let o=[...new Set(i.map(s=>s._settingdefinitionid_value).filter(Boolean))],a=new Map;if(o.length>0){let s=o.map(c=>`settingdefinitionid eq ${(0,Va.normalizeGuid)(c,"Setting definition id")}`).join(" or "),u=`/settingdefinitions${(0,Va.odataQuery)([["$select","settingdefinitionid,uniquename,displayname"],["$filter",s]])}`,l=await(0,Gh.collectPages)(e,u,"the setting definitions");for(let c of l.filter(Boolean))c.settingdefinitionid&&a.set(c.settingdefinitionid.toLowerCase(),c)}return i.map(s=>{var u,l,c,d,f;let p=a.get(((u=s._settingdefinitionid_value)!==null&&u!==void 0?u:"").toLowerCase());return{id:(l=s.appsettingid)!==null&&l!==void 0?l:"",name:(d=(c=p?.uniquename)!==null&&c!==void 0?c:s._settingdefinitionid_value)!==null&&d!==void 0?d:"",value:(f=s.value)!==null&&f!==void 0?f:"",...p?.displayname?{displayName:p.displayname}:{}}})}Vn.readAppSettings=fY;async function WP(e,t,n){var r;let i=KP("appsettingid,value",`_parentappmoduleid_value eq ${t} and _settingdefinitionid_value eq ${n}`),o=(await(0,Gh.collectPages)(e,i,"the app setting read")).filter(Boolean)[0];return o?.appsettingid?{id:o.appsettingid,value:(r=o.value)!==null&&r!==void 0?r:""}:void 0}async function YP(e,t,n,r){let i=(0,Va.normalizeGuid)(t,"App id"),a=(await JP(e,[n])).get(n),s=a?.settingdefinitionid;if(!s)throw new Error(`App setting '${n}' 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 u=(0,Va.normalizeGuid)(s,"Setting definition id"),l=await WP(e,i,u);if(l)return zP(e,l,r);let c="/appsettings",d={"[email protected]":`/appmodules(${i})`,"[email protected]":`/settingdefinitions(${u})`,value:r},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 WP(e,i,u)}catch{m=void 0}if(m)return zP(e,m,r);throw f&&(0,HP.ensureSuccess)(f,e.apiUrl(c)),p}Vn.setAppSetting=YP;async function zP(e,t,n){if(t.value===n)return"unchanged";let r=`/appsettings(${(0,Va.normalizeGuid)(t.id,"App setting id")})`;return(0,HP.ensureSuccess)(await e.patch(r,{value:n}),e.apiUrl(r)),"updated"}async function pY(e,t,n){var r;let i=[];for(let[o,a]of Object.entries(n??{}))try{await YP(e,t,o,a)}catch(s){i.push(`App setting '${o}' was not applied: ${(r=s?.message)!==null&&r!==void 0?r:String(s)} The app was created; set it later with setAppSetting().`)}return i}Vn.applyAppSettings=pY});var _w=C(wc=>{"use strict";Object.defineProperty(wc,"__esModule",{value:!0});wc.isFailureAfterPrimaryWrite=wc.failedAfterPrimaryWrite=void 0;var QP=Symbol.for("cds-maker-sdk.createFailedAfterPrimaryWrite");function mY(e){return typeof e=="object"&&e!==null&&(e[QP]=!0),e}wc.failedAfterPrimaryWrite=mY;function hY(e){return typeof e=="object"&&e!==null&&e[QP]===!0}wc.isFailureAfterPrimaryWrite=hY});var ft=C(Qo=>{"use strict";Object.defineProperty(Qo,"__esModule",{value:!0});Qo.assignMissingIds=Qo.pointerTouchesValueMap=Qo.isValueMapKey=Qo.newId=void 0;var gY=ec();function XP(){return globalThis.crypto.randomUUID().toLowerCase()}Qo.newId=XP;function yY(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}var Tw=new Set(["parameters","bag","expression","rawExpression","lookupValue","stepLabels","genPage","inputData","customControl"]);function bY(e){return Tw.has(e)}Qo.isValueMapKey=bY;function vY(e){return gY.JsonPointer.parse(e).some(t=>Tw.has(t))}Qo.pointerTouchesValueMap=vY;function wY(e){return Iw(e),e}Qo.assignMissingIds=wY;function Iw(e){if(Array.isArray(e)){e.forEach(t=>Iw(t));return}if(yY(e)){(typeof e.id!="string"||e.id.length===0)&&(e.id=XP());for(let t of Object.keys(e))t==="id"||Tw.has(t)||Iw(e[t])}}});var Zo=C(Dt=>{"use strict";Object.defineProperty(Dt,"__esModule",{value:!0});Dt.parseChangeSetsParts=Dt.renderChangeSets=Dt.MAX_BATCH_PARTS=Dt.sendChangeSet=Dt.isChangeSetLockRefusal=Dt.partResponse=Dt.postChangeSet=Dt.parseChangeSetParts=Dt.parseChangeSetStatuses=Dt.renderChangeSet=void 0;var Xo=Y(),Vu=pe(),jh=ft(),Uf=ae();function Ow(e,t){let n=`batch_${(0,jh.newId)()}`,r=`changeset_${(0,jh.newId)()}`,i=t.map((s,u)=>String(u+1)),o=t.map((s,u)=>eR(e,s,i[u],r,n));return{body:[`--${n}`,`Content-Type: multipart/mixed;boundary=${r}`,"",...o,`--${r}--`,`--${n}--`,""].join(`\r+`),batchId:n,contentIds:i}}Dt.renderChangeSet=Ow;function eR(e,t,n,r,i){var o,a;if(t.rawBody!==void 0&&t.contentType===void 0)throw new Xo.InvalidArgumentError(`batch operation ${t.method} ${t.path} has a raw body but no Content-Type`);let s=(o=t.rawBody)!==null&&o!==void 0?o:t.body===void 0?void 0:JSON.stringify(t.body);if(s!==void 0&&(s.includes(`--${r}`)||s.includes(`--${i}`)))throw new Xo.InvalidArgumentError(`batch operation ${t.method} ${t.path} has a body containing the batch boundary`);(0,Uf.assertNoControlChars)(t.path,"batch operation path"),t.etag&&(0,Uf.assertNoControlChars)(t.etag,"batch operation etag");let u=Object.entries((a=t.headers)!==null&&a!==void 0?a:{});for(let[l,c]of u)if((0,Uf.assertNoControlChars)(l,"batch operation header name"),(0,Uf.assertNoControlChars)(c,"batch operation header value"),!/^[A-Za-z0-9!#$%&'*+.^_`|~-]+$/.test(l))throw new Xo.InvalidArgumentError(`batch operation header name '${l}' is not a valid HTTP token`);return t.contentType!==void 0&&(0,Uf.assertNoControlChars)(t.contentType,"batch operation content type"),[`--${r}`,"Content-Type: application/http","Content-Transfer-Encoding: binary",`Content-ID: ${n}`,"",`${t.method} ${e.apiUrl(t.path)} HTTP/1.1`,...s===void 0?[]:[`Content-Type: ${t.rawBody!==void 0?t.contentType:"application/json;type=entry"}`],...e.solutionName?[`MSCRM.SolutionUniqueName: ${e.solutionName}`]:[],...t.etag?[`If-Match: ${t.etag}`]:[],...u.map(([l,c])=>`${l}: ${c}`),"",...s===void 0?[]:[s]].join(`\r+`)}function tR(e,t){var n;return(n=Wh(e,t))===null||n===void 0?void 0:n.map(r=>r.status)}Dt.parseChangeSetStatuses=tR;function Wh(e,t){var n,r;if(typeof e!="string"||e.length===0)return;let i=(n=/^--(\S+)\r?\n/.exec(e))===null||n===void 0?void 0:n[1];if(i===void 0||!e.trimEnd().endsWith(`--${i}--`))return;let o=(r=/Content-Type:\s*multipart\/mixed;\s*boundary=(\S+)/i.exec(e))===null||r===void 0?void 0:r[1];if(o===void 0||o===i)return;let a=e.split(`--${o}`);if(a.length<2||!/^--(\r?\n|$)/.test(a[a.length-1]))return;let s=new Set(t),u=[],l=new Set;for(let c of a.slice(1)){if(c.startsWith("--"))break;let d=nR(c,s,l);if(d===void 0)return;u.push(d)}return u.length===0?void 0:u}Dt.parseChangeSetParts=Wh;function nR(e,t,n){var r,i;let o=e.indexOf(`\r+\r+`);if(o===-1)return;let a=e.slice(0,o),s=e.slice(o+4);if(!/^Content-Type:\s*application\/http\b/im.test(a))return;let u=/^HTTP\/1\.[01] (\d{3})\b/.exec(s);if(!u||((r=s.match(/^HTTP\/1\.[01] \d{3}\b/gm))!==null&&r!==void 0?r:[]).length!==1)return;let l=(i=/^Content-ID:\s*(\S+)/im.exec(a))===null||i===void 0?void 0:i[1];if(!(l===void 0||n.has(l)||!t.has(l)))return n.add(l),{status:Number(u[1]),text:s,contentId:l}}async function EY(e,t,n){if(t.length===0)return;let{body:r,batchId:i,contentIds:o}=Ow(e,t),a=await e.postBatch(r,i),s=e.apiUrl("/$batch");if((0,Vu.ensureSuccess)(a,s),typeof a.body!="string"||a.body.length===0)throw new Xo.ConnectionError(s,a.status,`atomic write of ${n} cannot be confirmed: the $batch response had no readable body, so the change set's outcome is unknown`);let u=tR(a.body,o);if(u===void 0)throw new Xo.ConnectionError(s,a.status,`atomic write of ${n} cannot be confirmed: the $batch response could not be parsed as a change set, so the outcome is unknown`);if(u.length!==t.length)throw new Xo.ConnectionError(s,a.status,`atomic write of ${n} cannot be confirmed: the change set reported ${u.length} result(s) for ${t.length} operation(s)`);let l=u.find(c=>c<200||c>=300);if(l!==void 0)throw new Xo.ConnectionError(s,l,`atomic write of ${n} was rolled back: the change set reported HTTP ${l}`)}Dt.postChangeSet=EY;function Dw(e){let t=e.text.replace(/\r\n/g,`+`),n=t.indexOf(`++`),r=n===-1?t:t.slice(0,n),i=(n===-1?"":t.slice(n+2)).trim(),o={};for(let s of r.split(`+`).slice(1)){let u=s.indexOf(":");u>0&&(o[s.slice(0,u).trim()]=s.slice(u+1).trim())}let a=i===""?void 0:i;if(i!=="")try{a=JSON.parse(i)}catch{}return{status:e.status,headers:o,body:a}}Dt.partResponse=Dw;function ZP(e){let t=e.path.indexOf("?");return t===-1?e.path:e.path.slice(0,t)}function AY(e,t){let n=e.find(r=>(0,Vu.isVersionToken)(r.etag));if(!n||e.some(r=>ZP(r)!==ZP(n)))throw new Xo.InvalidArgumentError(`the change set writing ${t} cannot be re-sent under the customization lock: it needs an operation conditioned on a version token and every operation writing that operation's row`)}function rR(e,t){var n;if(e.status!==429&&(e.status<200||e.status>=300))return!1;let r=(n=Wh(e.body,t))===null||n===void 0?void 0:n.filter(i=>i.status<200||i.status>=300);return r!==void 0&&r.length>0&&r.every(i=>(0,Vu.isConcurrencyLockRefusal)(Dw(i)))}Dt.isChangeSetLockRefusal=rR;async function CY(e,t,n,r={}){r.resendWhileLockRefused&&AY(t,n);let{body:i,batchId:o,contentIds:a}=Ow(e,t),s=()=>e.postBatch(i,o),u=r.resendWhileLockRefused?await(0,Vu.resendWhile)(f=>rR(f,a),s,Vu.LOCK_BACKOFF_MS):await s(),l=e.apiUrl("/$batch"),c=Wh(u.body,a),d=c?.find(f=>f.status<200||f.status>=300);if(d&&(0,Vu.ensureSuccess)(Dw(d),e.apiUrl(t[a.indexOf(d.contentId)].path)),(0,Vu.ensureSuccess)(u,l),!c||c.length!==t.length)throw new Xo.ConnectionError(l,u.status,`atomic write of ${n} cannot be confirmed: the $batch response ${c?`reported ${c.length} result(s) for ${t.length} operation(s)`:"could not be parsed"}, so the outcome is unknown`);return a.map(f=>c.find(p=>p.contentId===f))}Dt.sendChangeSet=CY;Dt.MAX_BATCH_PARTS=1e3;function SY(e,t){if(t.length>Dt.MAX_BATCH_PARTS)throw new Xo.InvalidArgumentError(`a $batch holds at most ${Dt.MAX_BATCH_PARTS} change sets \u2014 the platform refuses the 1001st part; got ${t.length}`);let n=`batch_${(0,jh.newId)()}`,r=t.map((a,s)=>String(s+1)),i=[];return t.forEach((a,s)=>{let u=`changeset_${(0,jh.newId)()}`;i.push(`--${n}`,`Content-Type: multipart/mixed;boundary=${u}`,"",eR(e,a,r[s],u,n),`--${u}--`)}),{body:[...i,`--${n}--`,""].join(`\r+`),batchId:n,contentIds:r}}Dt.renderChangeSets=SY;function NY(e,t){var n,r;if(typeof e!="string"||e.length===0)return;let i=(n=/^--(\S+)\r?\n/.exec(e))===null||n===void 0?void 0:n[1];if(i===void 0||!e.trimEnd().endsWith(`--${i}--`))return;let o=e.split(`--${i}`);if(!/^--(\r?\n|$)/.test(o[o.length-1]))return;let a=new Set(t),s=new Set,u=[];for(let l of o.slice(1)){if(l.startsWith("--"))break;let c=l.indexOf(`\r+\r+`);if(c===-1)return;let d=(r=/^Content-Type:\s*multipart\/mixed;\s*boundary=(\S+)/im.exec(l.slice(0,c)))===null||r===void 0?void 0:r[1];if(d===void 0||d===i)return;let f=l.slice(c+4).split(`--${d}`);if(f.length<3||f[0].trim()!==""||!/^--(\r?\n|$)/.test(f[f.length-1]))return;for(let p of f.slice(1,-1)){let m=nR(p,a,s);if(m===void 0)return;u.push(m)}}return u.length===0?void 0:u}Dt.parseChangeSetsParts=NY});var vc=C(Yt=>{"use strict";Object.defineProperty(Yt,"__esModule",{value:!0});Yt.appApi=Yt.SITEMAP_TARGET_NOT_FOUND_CODE=Yt.deleteAppResolvingOnce=Yt.publishApp=Yt.assertAppPublicationCombinable=Yt.assertAppPublicationProvable=Yt.mainFormModeIssues=Yt.mainFormSetShapeIssues=Yt.unpublishedAppModulesQuery=void 0;var kr=Ke(),_Y=Nw(),iR=Vh(),Fw=mo(),IY=Ff(),TY=_w(),ea=qi(),ce=pe(),De=ae(),Pw=ft(),ju=Zo(),fe=Y(),OY=(0,De.odataQuery)([["$select","appmoduleid,name,uniquename,description,aiappdescription"]]),zh="appmoduleid,name,uniquename,description,aiappdescription";function Vf(e,t,n){return"/appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,De.odataQuery)([["$select",e],["$filter",t],["$top",n]])}Yt.unpublishedAppModulesQuery=Vf;function Rw(e,t){return Vf(e,t?`appmoduleid eq ${t}`:void 0,t?1:void 0)}function Zh(e,t){return"/sitemaps/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,De.odataQuery)([["$select",t],["$filter",`sitemapid eq ${e}`],["$top",1]])}function qf(e){var t;let n=(t=e.body)===null||t===void 0?void 0:t.value;if(Array.isArray(n))return n[0]}function DY(e){let t=e?.["@odata.etag"];return typeof t=="string"?t:null}function Gf(e,t){if(typeof e!="string")return!1;try{return(0,De.normalizeGuid)(e,"sitemapid")===t}catch{return!1}}function Gu(e){let t=new Set,n=[];for(let r of e??[])r&&!t.has(r)&&(t.add(r),n.push(r));return n}function PY(e){return`cdsapp_${(e||"").replace(/[^a-zA-Z0-9]/g,"")||"app"}`}async function RY(e,t){var n,r;let i=l=>{throw new fe.SdkError("APP_SITEMAP_UNRESOLVED",`The sitemap lookup for app uniquename '${t??""}' ${l}, 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,De.odataQuery)([["$select","sitemapid"],["$filter",`sitemapnameunique eq '${(0,De.odataLiteral)(t)}'`],["$top",1]])}`,a;try{a=await e.get(o)}catch(l){return i(`failed (${l.message})`)}if(a.status<200||a.status>=300)return i(`returned HTTP ${a.status}`);let s=(n=a.body)===null||n===void 0?void 0:n.value;if(!Array.isArray(s))return i("returned a malformed body");if(!(0,kr.boundedPageComplete)(a.body,s.length))return i("returned no row but says more rows exist (or links to them)");let u=(r=s[0])===null||r===void 0?void 0:r.sitemapid;return s.length>0&&!u?i("returned a row with no sitemapid"):u}async function kY(e){let t=s=>`/webresourceset${(0,De.odataQuery)([["$select","webresourceid"],["$top",1],["$filter",s]])}`,n=async s=>{var u,l;let c=t(s),d=await e.get(c),f=(u=d.body)===null||u===void 0?void 0:u.value;if(Array.isArray(f)&&!(0,kr.boundedPageComplete)(d.body,f.length))throw new fe.ConnectionError(e.apiUrl(c),d.status,"the app icon lookup answered no web resource but says more rows exist (or links to them); refusing to choose a less suitable icon from an incomplete answer. Nothing was written.");return(l=f?.[0])===null||l===void 0?void 0:l.webresourceid},r="(webresourcetype eq 5 or webresourcetype eq 6 or webresourcetype eq 7 or webresourcetype eq 10 or webresourcetype eq 11)",i=await n("webresourcetype eq 5 and ismanaged eq false and contains(name,'icon')");if(i)return{id:i,managed:!1};let o=await n(`${r} and ismanaged eq false`);if(o)return{id:o,managed:!1};let a=await n(r);return a?{id:a,managed:!0}:void 0}var oR="627090ff-40a3-4053-8790-584edc5be201";function Gn(e){return e instanceof Error?e.message:String(e)}async function $Y(e,t){var n;try{let r=`/roles${(0,De.odataQuery)([["$select","roleid,_parentrootroleid_value"],["$filter",`_roletemplateid_value eq ${oR}`]])}`,i=await(0,kr.collectPages)(e,r,"the System Administrator role"),o=i.find(u=>typeof u.roleid=="string"&&typeof u._parentrootroleid_value=="string"&&u.roleid.toLowerCase()===u._parentrootroleid_value.toLowerCase()),a=(n=o??i.find(u=>typeof u.roleid=="string"))===null||n===void 0?void 0:n.roleid;if(!a)return`App roles: no 'System Administrator' role (template ${oR}) 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,ce.ensureSuccess)(await e.post(s,{"@odata.id":e.apiUrl(`/roles(${a})`)}),e.apiUrl(s)),null}catch(r){return`App roles: could not associate the 'System Administrator' role with the app (${Gn(r)}); it will not be visible or playable until a role is granted access to it.`}}async function LY(e,t,n=!0){let r=[];async function i(u,l,c){try{return(await(0,kr.collectPages)(e,u,`app assets (${c} for '${t}')`)).map(f=>String(f[l])).filter(f=>f&&f!=="undefined")}catch(d){return r.push(`App components: could not enumerate ${c} for table '${t}' (${Gn(d)}); they were NOT added to the app.`),[]}}let[o,a,s]=await Promise.all([n?i(`/systemforms${(0,De.odataQuery)([["$select","formid"],["$filter",`objecttypecode eq '${(0,De.odataLiteral)(t)}' and type eq 2 and formactivationstate eq 1`]])}`,"formid","forms"):Promise.resolve([]),i(`/savedqueries${(0,De.odataQuery)([["$select","savedqueryid"],["$filter",`returnedtypecode eq '${(0,De.odataLiteral)(t)}' and querytype eq 0 and statecode eq 0`]])}`,"savedqueryid","views"),i(`/savedqueryvisualizations${(0,De.odataQuery)([["$select","savedqueryvisualizationid"],["$filter",`primaryentitytypecode eq '${(0,De.odataLiteral)(t)}'`]])}`,"savedqueryvisualizationid","charts")]);return{forms:o,views:a,charts:s,warnings:r}}var aR=new WeakMap;async function MY(e,t){let n=aR.get(e);n||(n=new Map,aR.set(e,n));let r=n.get(t);if(r!==void 0)return r;let i=await xY(e,t);return i&&n.set(t,i),i}async function sR(e,t,n){let r=new Array(e.length),i=0;async function o(){for(let a=i;a<e.length;a=i)i=a+1,r[a]=await n(e[a])}return await Promise.all(Array.from({length:Math.min(t,e.length)},()=>o())),r}async function xY(e,t){let n=`/EntityDefinitions(LogicalName='${(0,De.odataPathLiteral)(t)}')${(0,De.odataQuery)([["$select","MetadataId,EntitySetName"]])}`,r=await e.get(n);if(r.status>=200&&r.status<300){let i=r.body;if(i?.MetadataId&&i.EntitySetName)return{logicalName:t,metadataId:i.MetadataId,entitySetName:i.EntitySetName}}}async function uR(e,t,n){let r=[],i=Gu(t.entities),o=4,a=await sR(i,o,g=>MY(e,g)),s=i.filter((g,y)=>!a[y]);if(s.length>0)throw new fe.SdkError("APP_ENTITY_COMPONENT_UNRESOLVED",`Refusing to build app components: table(s) ${s.map(g=>`'${g}'`).join(", ")} could not be resolved to an EntityDefinitions MetadataId + EntitySetName. Pinning the rest would produce an app whose navigation references a table the app does not contain. Verify the table name(s) exist in this environment and retry.`);let u=a.filter(g=>!!g);for(let g of u)r.push({"@odata.id":`${g.entitySetName}(${g.metadataId})`});for(let g of Gu(t.components.forms))r.push({"@odata.type":"Microsoft.Dynamics.CRM.systemform",formid:g});for(let g of Gu(t.components.views))r.push({"@odata.type":"Microsoft.Dynamics.CRM.savedquery",savedqueryid:g});for(let g of Gu(t.components.charts))r.push({"@odata.type":"Microsoft.Dynamics.CRM.savedqueryvisualization",savedqueryvisualizationid:g});for(let g of Gu(t.components.dashboards))r.push({"@odata.type":"Microsoft.Dynamics.CRM.systemform",formid:g});let l=new Set(t.components.forms),c=new Set(t.components.views),d=new Set(t.components.charts),f=new Map((n??[]).map(g=>[g.table,g])),p=await sR(i,o,g=>LY(e,g,!f.has(g.toLowerCase()))),m=p.flatMap(g=>g.warnings),h=new Set([...Gu(t.components.forms),...Gu(t.components.dashboards)].map(Ze));return p.forEach((g,y)=>{let b=f.get(i[y].toLowerCase());if(b)for(let E of b.allowed)h.has(E)||(h.add(E),l.add(E),r.push({"@odata.type":"Microsoft.Dynamics.CRM.systemform",formid:E}));else for(let E of g.forms)l.has(E)||(l.add(E),r.push({"@odata.type":"Microsoft.Dynamics.CRM.systemform",formid:E}));for(let E of g.views)c.has(E)||(c.add(E),r.push({"@odata.type":"Microsoft.Dynamics.CRM.savedquery",savedqueryid:E}));for(let E of g.charts)d.has(E)||(d.add(E),r.push({"@odata.type":"Microsoft.Dynamics.CRM.savedqueryvisualization",savedqueryvisualizationid:E}))}),{components:r,tables:u,warnings:m}}function Ze(e){let t=String(e).trim();return(t.startsWith("{")&&t.endsWith("}")?t.slice(1,-1):t).toLowerCase()}var ta=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,kw="/components/mainFormsByTable",lR=50;function gR(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}function yR(e,t){if(e===void 0)return[];if(e===null||typeof e!="object"||Array.isArray(e))return[{pointer:kw,rule:"app-main-form-set-shape",message:"must be an object mapping a table logical name to its Main form ids"}];let n=[],r=new Set(t.map(o=>o.toLowerCase())),i=new Set;for(let[o,a]of Object.entries(e)){let s=o.toLowerCase(),u=`${kw}/${gR(o)}`;if(i.has(s)){n.push({pointer:u,rule:"app-main-form-set-shape",message:`table '${o}' is listed twice (logical names compare case-insensitively)`});continue}if(i.add(s),r.has(s)||n.push({pointer:u,rule:"app-main-form-set-table",message:`'${o}' is not a table this app's sitemap navigates to (Entity subareas: ${[...r].join(", ")||"none"})`}),!Array.isArray(a)){n.push({pointer:u,rule:"app-main-form-set-shape",message:"must be an array of Main form ids"});continue}if(a.length===0){n.push({pointer:u,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 l=new Set;a.forEach((c,d)=>{let f=`${u}/${d}`;typeof c!="string"||!ta.test(Ze(c))?n.push({pointer:f,rule:"app-main-form-set-shape",message:`'${String(c)}' is not a form id`}):l.has(Ze(c))?n.push({pointer:f,rule:"app-main-form-set-shape",message:`form '${c}' is listed twice`}):l.add(Ze(c))})}return n}Yt.mainFormSetShapeIssues=yR;var cR="/components/mainFormsOnUpdate";function bR(e,t){if(e===void 0)return[];if(e!=="addOnly"&&e!=="exact")return[{pointer:cR,rule:"app-main-form-mode-shape",message:`must be 'addOnly' or 'exact', not ${JSON.stringify(e)}`}];let n=t!==null&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length>0;return e==="exact"&&!n?[{pointer:cR,rule:"app-main-form-mode-without-list",message:"'exact' needs a non-empty components.mainFormsByTable: it removes only the Main forms of a LISTED table that the list does not name, so without one it would remove nothing"}]:[]}Yt.mainFormModeIssues=bR;async function dR(e,t,n){let r=t.components.mainFormsByTable,i=bR(t.components.mainFormsOnUpdate,r);if(i.length>0)throw new fe.ValidationError("app",n,i);if(r===void 0)return;let o=yR(r,t.entities);if(o.length>0)throw new fe.ValidationError("app",n,o);if(Object.keys(r).length===0)return;let a=[],s=[];for(let[l,c]of Object.entries(r)){let d=l.toLowerCase(),f=await(0,kr.collectPages)(e,`/systemforms${(0,De.odataQuery)([["$select","formid,formactivationstate"],["$filter",`objecttypecode eq '${(0,De.odataLiteral)(d)}' and type eq 2`]])}`,`app Main-form allow-list ('${d}')`),p=new Set,m=new Set;for(let g of f)typeof g.formid=="string"&&(p.add(Ze(g.formid)),Number(g.formactivationstate)===1&&m.add(Ze(g.formid)));let h=c.map(Ze);h.forEach((g,y)=>{let b=`${kw}/${gR(l)}/${y}`;p.has(g)?m.has(g)||a.push({pointer:b,rule:"app-main-form-set-inactive",message:`Main form '${c[y]}' of '${d}' is inactive, so no app can offer it`}):a.push({pointer:b,rule:"app-main-form-set-not-main-form",message:`'${c[y]}' is not a Main form of '${d}'`})}),s.push({table:d,allowed:h,catalog:p})}let u=[...t.components.forms.map((l,c)=>({id:l,pointer:`/components/forms/${c}`})),...t.components.dashboards.map((l,c)=>({id:l,pointer:`/components/dashboards/${c}`}))];for(let l of u){let c=Ze(l.id);for(let d of s)d.catalog.has(c)&&!d.allowed.includes(c)&&a.push({pointer:l.pointer,rule:"app-main-form-set-conflict",message:`'${l.id}' is a Main form of '${d.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(a.length>0)throw new fe.ValidationError("app",n,a);return s}function eg(e,t=new Map){return e.tables.map(n=>{var r;return{table:n.table,membership:n.extras.length===0&&n.missing.length===0?"exact":"notExact",removed:((r=t.get(n.table))!==null&&r!==void 0?r:[]).filter(i=>!n.members.includes(i)),retained:n.extras,missing:n.missing}})}function $w(e,t){return e.map(n=>({table:n.table,membership:"inconclusive",removed:[],retained:[],missing:[],reason:t}))}async function tg(e,t){var n,r;let i=l=>({kind:"inconclusive",reason:l}),o=await e.get(Vf("appmoduleid,appmoduleidunique,componentstate",`appmoduleid eq ${t}`));if(o.status<200||o.status>=300)return i(`reading the app returned HTTP ${o.status}`);let a=(n=o.body)===null||n===void 0?void 0:n.value;if(!Array.isArray(a)||a.length===0)return i("reading the app returned no row");if((0,kr.pageEnd)(o.body).kind!=="end")return i("reading the app returned a page that says more rows exist (or links to them)");let s=a.length===1?a:a.filter(l=>Number(l?.componentstate)===1),u=s.length===1?(r=s[0])===null||r===void 0?void 0:r.appmoduleidunique:"";return typeof u!="string"||!ta.test(Ze(u))?i(`no single current layer among ${a.length} app row(s)`):{kind:"read",unique:Ze(u)}}function xs(e,t){let n;return()=>n??(n=tg(e,t))}var vR=62;function FY(e,t,n,r,i){let o=i.map(a=>`'${a}'`).join(", ");return t==="delete"?new fe.SdkError("APP_SITEMAP_SHARED",`Refusing to delete app '${e}': its sitemap '${n.sitemapId}' is also the navigation of app ${o}. The delete removes an app's sitemap with it, and the platform does not stop that for a sitemap another app uses, so those apps would be left without navigation. Nothing was deleted. Remove the sitemap from the other app first, then retry.`):new fe.SdkError("APP_SITEMAP_SHARED",`Refusing to ${t} app '${e}': it has no SiteMap component, and the sitemap named like it ('${r??""}', '${n.sitemapId}') is the navigation of app ${o}, so it is not this app's. Nothing was ${t==="fetch"?"saved":"modified"}.`)}async function Bf(e,t,n,r,i=!1){var o;let a=c=>{throw new fe.SdkError("APP_SITEMAP_UNRESOLVED",`Refusing to ${r} app '${t}': ${c}, so it cannot be determined which sitemap is this app's. Nothing was ${r==="fetch"?"saved":r==="delete"?"deleted":"modified"}. Retry.`)},s;try{s=await tg(e,t)}catch(c){return a(`reading its current layer failed (${Gn(c)})`)}if(s.kind==="inconclusive")return a(`its current layer could not be read (${s.reason})`);let u;try{u=await(0,kr.collectPages)(e,`/appmodulecomponents${(0,De.odataQuery)([["$select","objectid"],["$filter",`_appmoduleidunique_value eq ${s.unique} and componenttype eq ${vR}`]])}`,`app SiteMap component ('${t}')`)}catch(c){return a(`reading its SiteMap component failed (${Gn(c)})`)}let l;if(u.length>1)return a(`its current layer carries ${u.length} SiteMap components, where an app can hold one`);if(u.length===1){let c=(o=u[0])===null||o===void 0?void 0:o.objectid;if(typeof c!="string"||!ta.test(Ze(c)))return a(`its SiteMap component carries an object id that is not a GUID ('${String(c)}')`);l={sitemapId:Ze(c),by:"component"}}else{let c=await RY(e,n);if(!c)return;let d;try{d=(0,De.normalizeGuid)(c,"sitemapId")}catch{return a(`the sitemap lookup by unique name returned a sitemapid that is not a GUID ('${String(c)}')`)}l={sitemapId:d,by:"name"}}if(i||l.by==="name"){let c=await UY(e,l.sitemapId,t,a);if(c.length>0)throw FY(t,r,l,n,c)}return l}async function UY(e,t,n,r){var i;let o;try{o=await(0,kr.collectPages)(e,`/appmodulecomponents${(0,De.odataQuery)([["$select","_appmoduleidunique_value"],["$filter",`componenttype eq ${vR} and objectid eq ${t}`]])}`,`apps using sitemap '${t}'`)}catch(l){return r(`reading which apps use sitemap '${t}' failed (${Gn(l)})`)}let a=new Set;for(let l of o){let c=l?._appmoduleidunique_value;if(typeof c!="string"||!ta.test(Ze(c)))return r(`a SiteMap component naming sitemap '${t}' carries no app layer id`);a.add(Ze(c))}let s=Ze(n),u=[];for(let l of a){let c;try{c=await e.get(Vf("appmoduleid",`appmoduleidunique eq ${l}`))}catch(f){return r(`resolving app layer '${l}' failed (${Gn(f)})`)}if(c.status<200||c.status>=300)return r(`resolving app layer '${l}' returned HTTP ${c.status}`);let d=(i=c.body)===null||i===void 0?void 0:i.value;if(!Array.isArray(d))return r(`resolving app layer '${l}' returned a malformed body`);if((0,kr.pageEnd)(c.body).kind!=="end")return r(`resolving app layer '${l}' returned a page that says more rows exist (or links to them)`);for(let f of d){let p=f?.appmoduleid;if(typeof p!="string"||!ta.test(Ze(p)))return r(`app layer '${l}' resolved to a row with no app id`);let m=Ze(p);if(m===s||u.includes(m))continue;let h;try{h=await tg(e,m)}catch(g){return r(`reading the current layer of app '${m}' failed (${Gn(g)})`)}if(h.kind==="inconclusive")return r(`the current layer of app '${m}' could not be read (${h.reason})`);h.unique===l&&u.push(m)}}return u}async function Wu(e,t,n,r=xs(e,t)){let i=p=>({kind:"inconclusive",reason:p}),o=await r();if(o.kind==="inconclusive")return o;let a=o.unique,s;try{let p=await(0,kr.collectPages)(e,`/appmodulecomponents${(0,De.odataQuery)([["$select","objectid"],["$filter",`_appmoduleidunique_value eq ${Ze(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=>Ze(String(m.objectid)))}catch(p){return i(`reading its form components failed (${Gn(p)})`)}let u=new Map,l=[];for(let p of new Set(s)){let m=n.find(h=>h.catalog.has(p));m?u.set(p,m.table):l.push(p)}if(l.some(p=>!ta.test(p)))return i("a form component carries an object id that is not a GUID");let c=new Set(n.map(p=>p.table)),d=new Set;for(let p=0;p<l.length;p+=lR){let m=l.slice(p,p+lR);try{let h=await(0,kr.collectPages)(e,`/systemforms${(0,De.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 y=Ze(g.formid);d.add(y);let b=g.type===2?String(g.objecttypecode).toLowerCase():"";c.has(b)&&u.set(y,b)}}catch(h){return i(`classifying its form components failed (${Gn(h)})`)}}let f=l.filter(p=>!d.has(p));return f.length>0?i(`form component(s) ${f.join(", ")} could not be classified`):{kind:"read",tables:n.map(p=>{let m=[...u].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 qY(e,t,n,r){let i=await Wu(e,t,n,r);if(i.kind==="inconclusive")throw new fe.SdkError("APP_MAIN_FORM_SET_UNVERIFIED",`App '${t}': its Main-form allow-list was written but could not be verified \u2014 ${i.reason}.`);let o=i.tables.filter(a=>a.extras.length>0||a.missing.length>0);if(o.length>0)throw new fe.SdkError("APP_MAIN_FORM_SET_NOT_APPLIED",`App '${t}': its Main forms do not match the allow-list after the write \u2014 ${o.map(a=>`'${a.table}': unexpected [${a.extras.join(", ")}], missing [${a.missing.join(", ")}]`).join("; ")}.`);return i}async function BY(e,t,n,r){let i;try{i=await Wu(e,t,n,r)}catch(a){i={kind:"inconclusive",reason:Gn(a)}}if(i.kind==="inconclusive")return{warnings:[`Main-form membership of app '${t}' could not be verified (${i.reason}).`],tables:$w(n,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{warnings:o,tables:eg(i)}}function VY(e){return{"@odata.type":"Microsoft.Dynamics.CRM.systemform",formid:e}}async function Uw(e,t){let{body:n,batchId:r,contentIds:i}=(0,ju.renderChangeSet)(e,t),o;try{o=await e.postBatch(n,r)}catch(u){return{kind:"unknown",reason:`its answer was lost (${Gn(u)})`}}let a=(0,ju.parseChangeSetParts)(o.body,i);if(!a)return{kind:"unknown",reason:`its answer (HTTP ${o.status}) could not be read as a change set`};let s=a.find(u=>u.status<200||u.status>=300);return s?{kind:"refused",op:t[i.indexOf(s.contentId)],answer:(0,ju.partResponse)(s)}:a.length!==t.length?{kind:"unknown",reason:`its answer reported ${a.length} result(s) for ${t.length} operation(s)`}:{kind:"committed",answers:i.map(u=>(0,ju.partResponse)(a.find(l=>l.contentId===u)))}}function Lw(e,t,n,r){var i;let o=(i=n.answer.body)===null||i===void 0?void 0:i.error,a=typeof o?.code=="string"?` ${o.code}`:"",s=typeof o?.message=="string"?`: ${o.message}`:"",u=`${n.op.method} ${n.op.path.split("?")[0]}`;return n.answer.status===412?new fe.SdkError(ce.VERSION_CONFLICT_CODE,`${r} of app '${t}' was refused: ${u} answered 412${a} \u2014 the row moved since this copy (another writer changed the app's header, its components or its sitemap). Nothing was committed: the change set is atomic. Re-fetch the app, re-apply BOTH components.mainFormsByTable and components.mainFormsOnUpdate (a fetch carries neither), and push again.`):new fe.ConnectionError(e.apiUrl("/$batch"),n.answer.status,`${r} of app '${t}' was refused and rolled back: ${u} answered HTTP ${n.answer.status}${a}${s}. Nothing was committed: the change set is atomic.`,n.answer.body)}async function Kh(e,t){try{let n=await e.get(`/appmodules(${t})?$select=appmoduleid`);return n.status>=200&&n.status<300?(0,ce.readEtag)(n):null}catch{return null}}async function GY(e,t,n){return t.observe({guard:"ifMatch",componentName:"AppModule",componentId:n.appId,held:n.appToken,server:n.serverAppToken,status:(0,ea.compareTokens)(n.appToken,n.serverAppToken)}),await(0,ea.observeIfMatch)(e,t,{entitySet:"sitemaps",idColumn:"sitemapid",id:n.sitemapId,componentName:"SiteMap",held:n.sitemapToken}),t.reached({effects:[{componentName:"AppModule",componentId:n.appId,identity:"known",operation:"update"},{componentName:"SiteMap",componentId:n.sitemapId,identity:"known",operation:"update"}],attemptsWrite:!0})}async function jY(e){var t,n,r,i;let{client:o,appId:a,body:s,sets:u}=e,l=X=>new fe.SdkError("APP_MAIN_FORM_REMOVAL_UNSUPPORTED",`Refusing exact Main-form reconciliation of app '${a}': ${X}. Nothing was modified.`);if(!o.supportsAtomicBatch)throw l("the HttpClient has no postRaw(), and the removal is bound to this copy only inside ONE $batch change set");if(!e.currentHeader)throw l(e.headerProblem?`its header read is ambiguous \u2014 ${e.headerProblem} \u2014 so neither its managed state nor the header edit can be judged`:"the app's header could not be read, so whether it is managed is unknown");if(e.currentHeader.ismanaged!==!1)throw l(`it is not affirmatively unmanaged (ismanaged: ${JSON.stringify(e.currentHeader.ismanaged)}); removal from a managed app has not been verified`);let c=`/appmodules(${a})?$select=appmoduleid`,d={guard:"rowToken",componentName:"AppModule",componentId:a,held:e.appToken},f;try{f=await o.get(c)}catch(X){throw(t=e.preview)===null||t===void 0||t.observe({...d,status:(0,ea.failedReadStatus)(X),detail:(0,ea.failureDetail)(X)}),X}if(f.status===404)throw l("it is a draft (never published), and a draft app row cannot carry the condition that binds the removal to this copy. Publish it first (published: true in the default mode), then push exact");if(e.preview&&(f.status<200||f.status>=300)&&e.preview.observe({...d,status:"readFailed",detail:`HTTP ${f.status}`}),(0,ce.ensureSuccess)(f,o.apiUrl(c)),!(0,ce.isVersionToken)(e.appToken))throw(n=e.preview)===null||n===void 0||n.observe({...d,status:"missingHeld"}),new fe.SdkError("APP_UPDATE_NO_ETAG",`Refusing to push app '${a}' in exact Main-form mode: ${e.appToken?`the concurrency token held for its appmodule row ('${e.appToken}') is not a version`:"no concurrency token is held for its appmodule row"}, so the removal could not be bound to this copy. Nothing was modified. Re-fetch the app (fetchArtifact('app', '${a}', { overwrite: true })), re-apply BOTH components.mainFormsByTable and components.mainFormsOnUpdate, and push again.`);let p=(0,ce.readEtag)(f);if((r=e.preview)===null||r===void 0||r.observe({...d,server:p,status:(0,ea.compareTokens)(e.appToken,p)}),p!==e.appToken)throw new fe.SdkError(ce.VERSION_CONFLICT_CODE,`Version conflict for app '${a}': its appmodule row moved since this copy (held ${e.appToken}, now ${p??"(none)"}) \u2014 another writer changed its header or its components. Nothing was modified.`);let m=await Wu(o,a,u,xs(o,a));if(m.kind==="inconclusive")throw new fe.SdkError("APP_MAIN_FORM_SET_UNVERIFIED",`App '${a}': its Main-form membership could not be read before the exact write (${m.reason}). Nothing was modified.`);let h=new Map(m.tables.map(X=>[X.table,X.extras])),g=m.tables.flatMap(X=>X.extras);if(e.preview)return GY(o,e.preview,{appId:a,sitemapId:e.sitemapId,sitemapToken:e.sitemapToken,appToken:e.appToken,serverAppToken:p});let y={Prefer:"return=representation"},b=[{method:"PATCH",path:`/appmodules(${a})`,body:e.headerWrite,etag:e.appToken},{method:"PATCH",path:`/sitemaps(${e.sitemapId})${(0,ce.echoWrite)("sitemapid").query}`,body:{...Xh(s)},etag:e.sitemapToken,headers:y},...e.plan.components.length>0?[{method:"POST",path:"/AddAppComponents",body:{AppId:a,Components:e.plan.components}}]:[],...g.length>0?[{method:"POST",path:"/RemoveAppComponents",body:{AppId:a,Components:g.map(VY)}}]:[],{method:"PATCH",path:`/appmodules(${a})?$select=appmoduleid`,body:{},headers:y}],E=await Uw(o,b);if(E.kind==="refused")throw Lw(o,a,E,"The exact write");let w=HY(o,a,u);if(E.kind==="unknown")throw await WY(e,E.reason);let _=(0,ce.readEtag)(E.answers[1]),I=(0,ce.readEtag)(E.answers[E.answers.length-1]),T=[...e.plan.warnings],O=xs(o,a);try{await Mw(o,a,e.plan.tables,O)}catch(X){T.push(`App '${a}': one or more components were not pinned (${X.message}). Navigation may reference content not included in the app; re-push to retry.`)}let v;try{v=await Wu(o,a,w,O)}catch(X){v={kind:"inconclusive",reason:Gn(X)}}let N=I?await Kh(o,a):null,S=new Set(u.map(X=>X.table)),R,x=[];if(v.kind==="inconclusive")R=$w(u,v.reason);else if(I&&N!==I)R=$w(u,"another writer changed the app after this push's write");else{let X=eg(v,h);R=X.filter(ye=>S.has(ye.table)),x=X.filter(ye=>!S.has(ye.table)&&ye.membership!=="exact").map(ye=>ye.table)}for(let X of R)X.membership==="inconclusive"?T.push(`Main-form membership of app '${a}' could not be proven after the exact write for table '${X.table}' (${X.reason}); nothing is claimed about it.`):X.membership==="notExact"&&T.push(`Main forms of table '${X.table}' are not exact in app '${a}' after the exact write: retained [${X.retained.join(", ")}], missing [${X.missing.join(", ")}]. Nothing was re-sent.`);I||T.push(`App '${a}': the exact write returned no app token, so none is held \u2014 the next header edit is refused (APP_UPDATE_NO_ETAG) until a re-fetch, after which re-apply BOTH components.mainFormsByTable and components.mainFormsOnUpdate (a fetch carries neither).`);let G={kind:"notRequested"},U="notRead",M=I,q=_;if(s.published===!0)if(!(R.every(ye=>ye.membership==="exact")&&x.length===0)||!I){let ye=x.map(_e=>`'${_e}'`).join(", "),Ve=I?x.length>0&&R.every(_e=>_e.membership==="exact")?`the Main forms of table(s) ${ye} \u2014 listed by an earlier exact push of this app in this SDK instance and not yet seen published \u2014 are not exactly that list`:"the proof after the write is not exact or not readable":"the exact write returned no app token to bind the publish to";G={kind:"failed",error:new fe.SdkError("APP_MAIN_FORM_PUBLISH_WITHHELD",`App '${a}': the requested publish was WITHHELD \u2014 no publish request was sent \u2014 because ${Ve}. The saved change stays on the app's pending layer. ${Jh}`)},T.push(G.error.message)}else{let ye=await ER(o,a,I);if(ye.kind==="refused"&&ye.answer.status===412)G={kind:"failed",error:new fe.SdkError("APP_MAIN_FORM_PUBLISH_CONFLICT",`App '${a}': the publish change set WAS sent, and its guard refused it (412): another writer changed the app after this push's write. Nothing was published. ${Jh}`)},T.push(G.error.message);else if(ye.kind==="refused")G={kind:"failed",error:Lw(o,a,ye,"The publish")},T.push(`App '${a}': saved, but publishing failed (${G.error.message}).`);else{G=ye.kind==="committed"?{kind:"submitted"}:{kind:"unverifiable",reason:`the publish change set was sent, but ${ye.reason}`},ye.kind==="unknown"&&T.push(`App '${a}': the publish change set was sent, but ${ye.reason}; it may have published.`);let Ve=await wR(o,a,w,v);U=zY(Ve,u),qw(o,a,Ve.kind==="read"?Ve.matching:[]),U!=="matches"&&T.push(U==="differs"?`App '${a}': its published layer does not hold the Main forms the current layer was proven to hold.`:`App '${a}': its published layer could not be read, so the published Main forms are unverified.`),M=ye.kind==="committed"?await Kh(o,a):null,q=(i=await Hh(o,e.sitemapId,Xh(s),e.expectedUniqueName))!==null&&i!==void 0?i:_}}else R.some(X=>X.removed.length>0)&&T.push(`App '${a}': the exact write changed the app's pending (unpublished) layer, and this push did not publish \u2014 what users get was not read. To publish it, push again in exact mode with published: true \u2014 the guarded publish re-proves the membership first; a plain publishArtifact would publish whatever is pending by then.`);return{id:a,etag:q,siblingEtags:{[a]:M},publish:G,...T.length>0?{warnings:T}:{},appMainForms:{mode:"exact",tables:R,published:U}}}async function WY(e,t){let{client:n,appId:r}=e,i;try{let o=await n.get(`/sitemaps(${e.sitemapId})?$select=sitemapid`),a=o.status>=200&&o.status<300?(0,ce.readEtag)(o):null;if(!(0,ce.isVersionToken)(a))i=`the outcome cannot be observed (the sitemap token could not be read: HTTP ${o.status})`;else if(a===e.sitemapToken)i="commit not observed at this read; the request may still complete";else{i="a write occurred (the sitemap token moved); it cannot be attributed to this push";try{let s=await Wu(n,r,e.sets,xs(n,r));s.kind==="read"&&(i+=` \u2014 the current layer now holds ${s.tables.map(u=>`'${u.table}': [${u.members.join(", ")}]`).join("; ")}`)}catch{}}}catch(o){i=`the outcome cannot be observed (${Gn(o)})`}return new fe.SdkError("APP_UPDATE_OUTCOME_UNKNOWN",`The exact write of app '${r}' was sent, but ${t}: whether it committed is NOT CONFIRMED. Observed: ${i}. Nothing was re-sent and the held tokens are kept. Re-pushing this same copy is safe \u2014 it is conditioned on the same tokens, so at most one of the two writes can commit; a re-fetch does not prove that this write settled.`)}async function wR(e,t,n,r){var i;let o={kind:"unreadable"};if(r.kind==="inconclusive")return o;let a;try{let l=await e.get(`/appmodules(${t})?$select=appmoduleidunique`),c=(i=l.body)===null||i===void 0?void 0:i.appmoduleidunique;if(l.status<200||l.status>=300||typeof c!="string"||!ta.test(Ze(c)))return o;a=Ze(c)}catch{return o}let s;try{s=await Wu(e,t,n,()=>Promise.resolve({kind:"read",unique:a}))}catch{return o}return s.kind==="inconclusive"?o:{kind:"read",matching:r.tables.filter(l=>{let c=s.kind==="read"?s.tables.find(d=>d.table===l.table):void 0;return c!==void 0&&c.members.length===l.members.length&&c.members.every(d=>l.members.includes(d))}).map(l=>l.table)}}function zY(e,t){return e.kind==="unreadable"?"unreadable":t.every(n=>e.matching.includes(n.table))?"matches":"differs"}var Jh="Do NOT publish it plainly: from this SDK instance, publishArtifact and setAppTheme with publish: true now prove the membership again and publish only in a guarded change set, but a publish from another instance, process or tool repeats neither the proof nor the guard and would publish whatever is pending (a listed table left with no Main form makes the app offer every form). Review the app, re-fetch it (keeping any edits of your own aside), re-apply BOTH components.mainFormsByTable and components.mainFormsOnUpdate, and push again in exact mode with published: true.",Yh=new WeakMap;function HY(e,t,n){var r;let i=Yh.get(e);i||(i=new Map,Yh.set(e,i));let o=Ze(t),a=(r=i.get(o))!==null&&r!==void 0?r:new Map;i.set(o,a);for(let u of n)a.set(u.table,u);let s=new Set(n.map(u=>u.table));return[...n,...[...a.values()].filter(u=>!s.has(u.table))]}function qw(e,t,n){let r=Yh.get(e),i=Ze(t),o=r?.get(i);if(!(!r||!o)){for(let a of n??[...o.keys()])o.delete(a);o.size===0&&r.delete(i)}}function Bw(e,t){var n;let r=(n=Yh.get(e))===null||n===void 0?void 0:n.get(Ze(String(t)));return r&&r.size>0?[...r.values()]:void 0}function ER(e,t,n){return Uw(e,[{method:"PATCH",path:`/appmodules(${t})`,body:{},etag:n},{method:"POST",path:"/PublishXml",body:{ParameterXml:(0,Fw.appModulePublishParameterXml)(t)}}])}async function AR(e,t,n){let r=await Kh(e,t);if(!(0,ce.isVersionToken)(r))return{why:"the app row's version could not be read, so a publish could not be bound to the membership"};let i;try{i=await Wu(e,t,n,xs(e,t))}catch(a){i={kind:"inconclusive",reason:Gn(a)}}if(i.kind==="inconclusive")return{why:`its Main-form membership could not be read (${i.reason})`};let o=eg(i).filter(a=>a.membership!=="exact");return o.length>0?{why:`its Main forms are not exactly the listed ones (${o.map(a=>`'${a.table}': outside the list [${a.retained.join(", ")}], missing [${a.missing.join(", ")}]`).join("; ")})`}:{token:r,membership:i}}function Vw(e,t,n="the requested publish"){return new fe.SdkError("APP_MAIN_FORM_PUBLISH_WITHHELD",`App '${e}': ${n} was WITHHELD \u2014 no publish request was sent \u2014 because this SDK instance's exact Main-form push of the app left a membership no published layer was seen to hold, and ${t}. `+Jh)}async function KY(e,t){let n=Bw(e,t);if(!n)return;let r=(0,De.normalizeGuid)(t,"appId"),i=await AR(e,r,n);if("why"in i)throw Vw(r,i.why)}Yt.assertAppPublicationProvable=KY;function JY(e,t){if(Bw(e,t))throw Vw((0,De.normalizeGuid)(t,"appId"),"its publication must be proven and guarded on its own, which one combined PublishXml envelope cannot carry \u2014 publish it with publishArtifact","publishing it in publishArtifacts")}Yt.assertAppPublicationCombinable=JY;async function CR(e,t){let n=Bw(e,t);if(!n)return(0,Fw.publishAppModule)(e,t);let r=(0,De.normalizeGuid)(t,"appId"),i=await AR(e,r,n);if("why"in i)throw Vw(r,i.why);let o=await ER(e,r,i.token);if(o.kind==="refused")throw o.answer.status===412?new fe.SdkError("APP_MAIN_FORM_PUBLISH_CONFLICT",`App '${r}': the guarded publish change set WAS sent, and its guard refused it (412): the app changed after its Main forms were proven. Nothing was published. ${Jh}`):Lw(e,r,o,"The guarded publish");let a=await wR(e,r,n,i.membership);if(qw(e,r,a.kind==="read"?a.matching:[]),o.kind==="unknown")throw new fe.ConnectionError(e.apiUrl("/$batch"),0,`the guarded publish change set of app '${r}' was sent, but ${o.reason}; it may have published`)}Yt.publishApp=CR;async function SR(e,t,n){if(n.length===0)return;let r="/AddAppComponents";(0,ce.ensureSuccess)(await e.post(r,{AppId:t,Components:n}),e.apiUrl(r))}function YY(e,t){let n=Object.keys(e),r=e["@odata.id"];if(n.length===1&&typeof r=="string"){let s=t.find(u=>`${u.entitySetName}(${u.metadataId})`===r);return s&&ta.test(Ze(s.metadataId))?`1:${Ze(s.metadataId)}`:void 0}let i={"Microsoft.Dynamics.CRM.systemform":["formid",60],"Microsoft.Dynamics.CRM.savedquery":["savedqueryid",26],"Microsoft.Dynamics.CRM.savedqueryvisualization":["savedqueryvisualizationid",59]},o=typeof e["@odata.type"]=="string"?i[e["@odata.type"]]:void 0,a=o?e[o[0]]:void 0;if(!(!o||n.length!==2||typeof a!="string"||!ta.test(Ze(a))))return`${o[1]}:${Ze(a)}`}async function QY(e,t,n,r){let i=[];for(let o of n.components){let a=YY(o,n.tables);if(a===void 0)return"legacy";i.push(a)}try{if(await Kh(e,t)!==r)return"legacy";let o=await tg(e,t);if(o.kind!=="read")return"legacy";let a=await(0,kr.collectPages)(e,`/appmodulecomponents${(0,De.odataQuery)([["$select","objectid,componenttype"],["$filter",`_appmoduleidunique_value eq ${o.unique}`]])}`,`app components ('${t}')`),s=new Set;for(let u of a){if(typeof u.objectid!="string"||!ta.test(Ze(u.objectid))||!Number.isInteger(u.componenttype))return"legacy";s.add(`${u.componenttype}:${Ze(u.objectid)}`)}return i.every(u=>s.has(u))?"allPresent":"missingObserved"}catch{return"legacy"}}async function XY(e,t,n,r){let i=async()=>{try{return await SR(e,t,n.components),{warnings:[]}}catch(s){return{warnings:[],error:s}}};if(r===void 0||await QY(e,t,n,r)!=="missingObserved")return i();let o={method:"POST",path:"/AddAppComponents",body:{AppId:t,Components:n.components}},a=await Uw(e,[{method:"PATCH",path:`/appmodules(${t})`,body:{},etag:r},o,{method:"PATCH",path:`/appmodules(${t})${(0,ce.echoWrite)("appmoduleid").query}`,body:{},headers:{Prefer:"return=representation"}}]);if(a.kind==="committed"){let s=(0,ce.readEtag)(a.answers[a.answers.length-1]);return(0,ce.isVersionToken)(s)?{appToken:s,warnings:[]}:{warnings:[`App '${t}': its components were added, but the change set returned no app token, so the one held is kept \u2014 the next header edit may answer VERSION_CONFLICT until a re-fetch.`]}}if(a.kind==="refused"){if(a.op!==o)return i();let s=new Error(`AddAppComponents answered HTTP ${a.answer.status}`);try{(0,ce.ensureSuccess)(a.answer,e.apiUrl(o.path))}catch(u){s=u}return{warnings:[],error:s}}return{warnings:[`App '${t}': the change set adding its components was sent, but ${a.reason}; it may have committed, and nothing was re-sent. The app token held is kept \u2014 the next header edit may answer VERSION_CONFLICT until a re-fetch.`]}}async function Mw(e,t,n,r=xs(e,t)){var i;if(n.length===0)return;let o=await r();if(o.kind==="inconclusive")throw new fe.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,De.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 fe.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 u=(i=s.body)===null||i===void 0?void 0:i.value;if(!Array.isArray(u))throw new fe.SdkError("APP_COMPONENTS_UNVERIFIED",`App '${t}': its table components were written but could not be verified \u2014 the read-back returned no readable result set. Re-push to retry.`);let l=new Set(u.map(d=>d.objectid).filter(d=>typeof d=="string").map(d=>d.toLowerCase())),c=n.filter(d=>!l.has(d.metadataId.toLowerCase()));if(c.length>0)throw new fe.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 ZY(e,t,n){let r=`/appmodules(${t})`,i=`/sitemaps(${n.sitemapId})`,o;try{o=await tQ(e,n.sitemapId,n.sitemapNameUnique)}catch(u){return{outcome:"kept",reason:`whether its sitemap row exists could not be determined (${Gn(u)})`}}let a=o==="foreign",s=u=>u.kind==="deleted"?{outcome:"removed",foreignSitemap:a}:u.kind==="refused"?{outcome:"kept",foreignSitemap:a,reason:`its delete was refused (${Gn(u.error)})`,...u.lock?{lock:!0}:{}}:{outcome:"unconfirmed",foreignSitemap:a,reason:`its delete was sent but its outcome is unknown (${Gn(u.error)})`,...u.lock?{lock:!0}:{}};try{if(o==="absent"||o==="foreign"){if(!n.serverRefusedSitemap)return{outcome:"kept",foreignSitemap:a,reason:"the sitemap write's outcome was never observed, so its row may still appear"};let u=await(0,ce.resendAppSearchIndexRace)(()=>e.delete(r));if(u.status===404)return s({kind:"deleted"});let l=xw(u,e.apiUrl(r));return s(l.kind!=="deleted"&&(0,ce.isConcurrencyLockRefusal)(u)?{...l,lock:!0}:l)}return e.supportsAtomicBatch?n.sitemapWriteToken?s(await _R(e,[{path:r},{path:i,etag:n.sitemapWriteToken}],{reportLock:!0})):{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(u){return s({kind:"unknown",error:u})}}function eQ(e,t,n){if(!(e instanceof Error))return e;let r=t.foreignSitemap?` Sitemap id '${n.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.${r}`,e;let i=t.foreignSitemap?`appmodule '${n.appId}' (unique name '${n.uniqueName}')`:`appmodule '${n.appId}' (unique name '${n.uniqueName}') and, if it was written, sitemap '${n.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', '${n.appId}')`:`deleteRecord('appmodule', '${n.appId}') and deleteRecord('sitemap', '${n.sitemapId}')`}.`,s="Once the lock frees \u2014 another customization operation holds it \u2014 check that the rows exist and are this create's own before removing them.";return t.lock&&t.outcome==="kept"?e.message+=` The partial app this create wrote was KEPT \u2014 its rollback deleted nothing, because the environment's customization lock refused it (another customization operation was running): ${i}. ${s} While it exists, ${a}`:t.lock?e.message+=` Whether the partial app this create wrote was removed could not be confirmed, because the environment's customization lock refused or interrupted its rollback, so it may not have run. Check for ${i}. ${s} While any of it exists, ${a}`: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+=r,e}async function tQ(e,t,n){var r,i,o;let a=Zh(t,"sitemapid,sitemapnameunique"),s=await e.get(a);if(s.status<200||s.status>=300)throw new fe.SdkError("APP_SITEMAP_UNRESOLVED",`The unpublished-aware read of sitemap '${t}' returned HTTP ${s.status}, so it cannot be determined whether the row exists.`);let u=(r=s.body)===null||r===void 0?void 0:r.value;if(!Array.isArray(u))throw new fe.SdkError("APP_SITEMAP_UNRESOLVED",`The unpublished-aware read of sitemap '${t}' returned no readable result set, so it cannot be determined whether the row exists.`);if(!(0,kr.boundedPageComplete)(s.body,u.length))throw new fe.SdkError("APP_SITEMAP_UNRESOLVED",`The unpublished-aware read of sitemap '${t}' returned no row but says more rows exist (or links to them), so it cannot be determined whether the row exists.`);return u.length===0?"absent":String((o=(i=u[0])===null||i===void 0?void 0:i.sitemapnameunique)!==null&&o!==void 0?o:"")===n?"ours":"foreign"}async function nQ(e,t){var n;let r;try{r=await e.get(Vf("appmoduleid,uniquename,componentstate",`appmoduleid eq ${t}`))}catch(s){return{kind:"unsettled",why:`its unpublished read failed (${s.message})`}}if(r.status<200||r.status>=300)return{kind:"unsettled",why:`its unpublished read returned HTTP ${r.status}`};let i=(n=r.body)===null||n===void 0?void 0:n.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`};if((0,kr.pageEnd)(r.body).kind!=="end")return{kind:"unsettled",why:"its unpublished read says more rows exist (or links to them), so its one row is not exactly one"};let o=i[0],a=o?.uniquename;return!Gf(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 NR(e,t){var n;let r=(0,De.normalizeGuid)(t,"id"),i=b=>{throw new fe.SdkError("APP_SITEMAP_UNRESOLVED",`Refusing to delete app '${r}': ${b} Deleting the app would destroy the only pointer to its sitemap, stranding that row and reserving its unique name forever. Retry.`)},o=`/appmodules(${r})${OY}`,a;try{a=await e.get(o)}catch(b){return i(`reading the app failed (${b.message}).`)}let s,u=!1;if(a.status===404){let b=await nQ(e,r);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,u=!0}else{if(a.status<200||a.status>=300)return i(`reading the app returned HTTP ${a.status}.`);s=(n=a.body)===null||n===void 0?void 0:n.uniquename}if(!s)return i("the app record carried no uniquename, so its sitemap cannot be located.");let l=u?{draft:!0}:{appEtag:(0,ce.readEtag)(a)},c=await Bf(e,r,s,"delete");if(!c)return{uniquename:s,...l};let d=c.sitemapId,f=await Qh(e,d),p=Zh(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=qf(m);if(!h)return i(`sitemap '${d}' was not returned by the unpublished-aware read.`);if(c.by==="name"&&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(!Gf(h.sitemapid,d))return i(`sitemap '${d}' was read back as a row carrying sitemapid '${String(h.sitemapid)}'.`);let g=h.sitemapxml;if(typeof g!="string")return i(`sitemap '${d}' returned no sitemapxml.`);let y=await Bf(e,r,s,"delete",!0);return y?.sitemapId!==d||y.by!==c.by?i(`its sitemap link changed while it was read (sitemap '${d}' by ${c.by}, then ${y?`'${y.sitemapId}' by ${y.by}`:"none"}).`):{sitemapId:d,uniquename:s,sitemapXml:g,...l,sitemapEtag:f}}async function rQ(e,t,n){let r=(0,De.normalizeGuid)(t,"id"),i=await NR(e,r);await n?.(i.sitemapXml),await TR(e,r,i)}Yt.deleteAppResolvingOnce=rQ;async function iQ(e,t){let n=await _R(e,t);if(n.kind!=="deleted")throw n.error}function xw(e,t){try{return(0,ce.ensureSuccess)(e,t),{kind:"deleted"}}catch(n){return IR(e.status)?{kind:"refused",error:n}:{kind:"unknown",error:n}}}function oQ(e,t){var n;if(e.status!==400&&(e.status<200||e.status>=300))return!1;let r=(n=(0,ju.parseChangeSetParts)(e.body,t))===null||n===void 0?void 0:n.filter(i=>i.status<200||i.status>=300);return r!==void 0&&r.length>0&&r.every(i=>i.status===400&&(0,ce.namesAppSearchIndexRace)(i.text))}async function _R(e,t,n={}){let r=`batch_${(0,Pw.newId)()}`,i=`changeset_${(0,Pw.newId)()}`,o=t.map((m,h)=>[`--${i}`,"Content-Type: application/http","Content-Transfer-Encoding: binary",`Content-ID: ${h+1}`,"",`DELETE ${e.apiUrl(m.path)} HTTP/1.1`,...m.etag?[`If-Match: ${m.etag}`]:[],""].join(`\r+`)),a=[`--${r}`,`Content-Type: multipart/mixed;boundary=${i}`,"",...o,`--${i}--`,`--${r}--`,""].join(`\r+`),s=e.apiUrl("/$batch"),u=o.map((m,h)=>String(h+1)),l;try{l=await(0,ce.resendWhile)(m=>oQ(m,u),()=>e.postBatch(a,r),ce.DEADLOCK_BACKOFF_MS)}catch(m){return{kind:"unknown",error:m}}if(n.reportLock){if((0,ju.isChangeSetLockRefusal)(l,u))return{kind:"refused",lock:!0,error:new fe.ConnectionError(s,l.status,`atomic delete of app '${t[0].path}' was refused whole by the customization lock, so it deleted nothing`)};if((0,ce.isConcurrencyLockRefusal)(l)){let m=xw(l,s);return m.kind==="deleted"?m:{...m,lock:!0}}}let c=xw(l,s);if(c.kind!=="deleted")return c;let d=`app '${t[0].path}'`;if(typeof l.body!="string"||l.body.length===0)return{kind:"unknown",error:new fe.ConnectionError(s,l.status,`atomic delete of ${d} cannot be confirmed: the $batch response had no readable body, so the change set's outcome is unknown`)};let f=(0,ju.parseChangeSetStatuses)(l.body,u);if(f===void 0)return{kind:"unknown",error:new fe.ConnectionError(s,l.status,`atomic delete of ${d} cannot be confirmed: the $batch response could not be parsed as a change set, so the outcome is unknown`)};let p=f.find(m=>m<200||m>=300);return p!==void 0?{kind:"refused",error:new fe.ConnectionError(s,p,`atomic delete of ${d} was rolled back: the change set reported HTTP ${p}`)}:f.length!==o.length?{kind:"unknown",error:new fe.ConnectionError(s,l.status,`atomic delete of ${d} cannot be confirmed: the $batch response reported ${f.length} operation result(s), expected exactly ${o.length}`)}:{kind:"deleted"}}async function Qh(e,t){try{let n=await e.get(`/sitemaps(${t})?$select=sitemapid`);return n.status<200||n.status>=300?null:(0,ce.readEtag)(n)}catch{return null}}async function fR(e,t){let n=`/appmodules(${t})?$select=appmoduleid`,r=await e.get(n);if(r.status!==404)return(0,ce.ensureSuccess)(r,e.apiUrl(n)),(0,ce.readEtag)(r)}function Xh(e){return{sitemapxml:e.sitemapxml,...e.sitemapname!==void 0?{sitemapname:e.sitemapname}:{}}}async function Hh(e,t,n,r){if(!r)return null;let i=await Qh(e,t);if(!i)return null;try{let o=await e.get(Zh(t,"sitemapid,sitemapname,sitemapnameunique,sitemapxml"));if(o.status<200||o.status>=300)return null;let a=qf(o);return!a||!Gf(a.sitemapid,t)||a.sitemapnameunique!==r||a.sitemapxml!==n.sitemapxml||n.sitemapname!==void 0&&a.sitemapname!==n.sitemapname?null:i}catch{return null}}function IR(e){return e>=400&&e<500&&e!==408&&e!==429}function pR(e,t,n){if(!e)throw new fe.SdkError("APP_SITEMAP_UNRESOLVED",`Refusing to delete app '${t}': the ${n} 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 TR(e,t,n){let r=`/appmodules(${t})`,i=n.draft?void 0:pR(n.appEtag,t,"app");if(!n.sitemapId){if(n.draft){(0,ce.ensureSuccess)(await(0,ce.resendAppSearchIndexRace)(()=>e.delete(r)),e.apiUrl(r));return}await aQ(e,r,i);return}if(!e.supportsAtomicBatch)throw new fe.SdkError("APP_DELETE_NOT_ATOMIC",`Refusing to delete app '${t}': it owns a sitemap, and the injected HttpClient cannot send a raw body, so the two rows would have to be deleted as separate requests. A failure between them strands the sitemap and permanently reserves the app's unique name. Implement HttpClient.postRaw so the SDK can delete them atomically.`);await iQ(e,[{path:r,etag:i},{path:`/sitemaps(${n.sitemapId})`,etag:pR(n.sitemapEtag,t,"sitemap")}])}async function aQ(e,t,n){(0,ce.ensureSuccess)(await(0,ce.resendAppSearchIndexRace)(()=>e.delete(t,{headers:{"If-Match":n}})),e.apiUrl(t))}Yt.SITEMAP_TARGET_NOT_FOUND_CODE="SITEMAP_TARGET_NOT_FOUND";async function mR(e,t,n){if(!/GenPageId/i.test(t))return;let r;try{r=[...new Set((0,_Y.collectGenPageIds)(t))]}catch(o){throw new fe.SdkError("SITEMAP_TARGET_UNVERIFIABLE",`Refusing to push the app: its sitemap xml could not be parsed, so the generative pages it navigates to cannot be verified (${Gn(o)}).`)}if(r.length===0)return;let i=await(0,iR.findMissingGenPages)(e,r,"sitemap generative-page preflight");if((0,iR.observeGenPageTargets)(n,r,i),i.length>0)throw new fe.SdkError(Yt.SITEMAP_TARGET_NOT_FOUND_CODE,`Refusing to push the app: its sitemap navigates to generative page(s) ${i.map(o=>`'${o}'`).join(", ")} that do not exist in this environment. Push the page before the app that links to it.`)}function sQ(e){var t,n;if(e.status!==400)return!1;let r=e.body;return String((n=(t=r?.error)===null||t===void 0?void 0:t.message)!==null&&n!==void 0?n:"").includes("retrieval of version numbers failed")}function OR(e){return new fe.SdkError("APP_DRAFT_HEADER_NOT_WRITABLE",`Refusing to update app '${e}': 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.`)}async function uQ(e,t,n){var r;await(0,ea.observeIfMatch)(e,t,{entitySet:"sitemaps",idColumn:"sitemapid",id:n.sitemapId,componentName:"SiteMap",held:n.sitemapToken});let i=await(0,ea.readRowToken)(e,{entitySet:"appmodules",idColumn:"appmoduleid",id:n.appId});if(n.writesHeader){let o={guard:"ifMatch",componentName:"AppModule",componentId:n.appId,held:n.appToken};if(i.kind==="notFound"&&n.headerRead)throw OR(n.appId);i.kind==="token"?t.observe({...o,server:i.token,status:(0,ea.compareTokens)(n.appToken,i.token)}):t.observe({...o,status:"readFailed",detail:i.kind==="failed"?i.detail:"HTTP 404, and the unpublished header was unreadable"})}else i.kind==="token"&&i.token!==null&&n.appToken!==i.token&&t.warn("PREVIEW_SIBLING_MOVED",`App '${n.appId}': its appmodule header changed on the server since it was read (held ${(r=n.appToken)!==null&&r!==void 0?r:"(none)"}, server ${i.token}), but this push writes no header field \u2014 every header value it supplies equals the server's \u2014 so it is not a conflict for this push. Re-fetch to see the change.`);return n.pinMayGuard&&t.warn("PREVIEW_APP_PIN_GUARD_NOT_EVALUATED",`App '${n.appId}': after the primary save, this push may use a guarded component pin that also writes the app row. That later gate, its token echo and fallback are not evaluated by this preview.`),t.reached({effects:[...n.writesHeader?[{componentName:"AppModule",componentId:n.appId,identity:"known",operation:"update"}]:[],{componentName:"SiteMap",componentId:n.sitemapId,identity:"known",operation:"update"}],attemptsWrite:!0})}function lQ(e,t){var n;let r=[["name",e.appModuleName],["description",e.appModuleDescription],["aiappdescription",e.appModuleAiDescription]],i={};for(let[o,a]of r)a!==void 0&&(t!==void 0&&String((n=t[o])!==null&&n!==void 0?n:"")===String(a??"")||(i[o]=a));return i}async function hR(e,t,n){var r;let i=(0,De.normalizeGuid)(t,"id"),o=n==="tokens-first",a=o?await fR(e,i):null,s=Rw(zh,i),u=(0,ce.ensureSuccess)(await e.get(s),e.apiUrl(s)),l=(r=qf(u))!==null&&r!==void 0?r:{};if(!l.appmoduleid)throw new fe.SdkError("APP_NOT_FOUND",`App '${i}' was not found (checked the unpublished-aware projection, which includes drafts).`);let c=await Bf(e,i,l.uniquename,"fetch"),d=c?.sitemapId,f=null;if(c&&d){o&&(f=await Qh(e,d));let m=Zh(d,"sitemapid,sitemapname,sitemapnameunique,sitemapxml"),h=(0,ce.ensureSuccess)(await e.get(m),e.apiUrl(m)),g=qf(h),y=E=>{throw new fe.SdkError("APP_SITEMAP_UNRESOLVED",`Refusing to fetch app '${i}': its sitemap '${d}' was located by its ${c.by==="component"?"SiteMap component":"unique name"}, but ${E}, 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 y("the by-id read returned no row");if(c.by==="name"&&g.sitemapnameunique!==l.uniquename)throw new fe.SdkError("APP_SITEMAP_UNRESOLVED",`Refusing to fetch app '${i}': sitemap '${d}' now carries sitemapnameunique '${String(g.sitemapnameunique)}', not '${String(l.uniquename)}', so it is no longer this app's sitemap. Retry.`);if(!Gf(g.sitemapid,d))return y(`the by-id read returned a row carrying sitemapid '${String(g.sitemapid)}'`);if(typeof g.sitemapxml!="string")return y("the by-id read returned no sitemapxml");let b=await Bf(e,i,l.uniquename,"fetch");if(b?.sitemapId!==d||b.by!==c.by)throw new fe.SdkError("APP_SITEMAP_UNRESOLVED",`Refusing to fetch app '${i}': its sitemap link changed while it was read (sitemap '${d}' by ${c.by}, then ${b?`'${b.sitemapId}' by ${b.by}`:"none"}). Nothing was saved. Retry.`);l.$sitemap=g,o||(f=await Qh(e,d))}o||(a=await fR(e,i));let p=a??DY(l);return{raw:l,etag:f,...l.appmoduleid?{siblingEtags:{[(0,De.normalizeGuid)(l.appmoduleid,"appmoduleid")]:p}}:{}}}Yt.appApi={get(e,t){return hR(e,t,"tokens-first")},readContentThenToken(e,t){return hR(e,t,"content-first")},async list(e,t){let n=Rw(zh);return(await(0,kr.collectPages)(e,n,"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,n,r=void 0){let i=t;if(typeof i.appModuleName!="string"||i.appModuleName.trim()==="")throw new fe.ValidationError("app",i.appModuleId,[{pointer:"/name",rule:"app-name-required",message:"an app needs a name to be created, and its 'name' is missing or blank \u2014 set it (updateElement('app', id, '/name', \u2026), or addElement when the key was removed) and push again. Nothing was written."}]);await mR(e,i.sitemapxml,r);let o=await dR(e,i,i.appModuleId),a=i.iconWebResourceId?void 0:await kY(e),s=i.iconWebResourceId||a?.id;if(!s)throw new fe.SdkError("APP_ICON_UNRESOLVED",`Cannot create app '${i.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 u=null;a?.managed&&(u=`No unmanaged image web resource was available, so the app icon resolved to a MANAGED one (${a.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=i.appModuleUniqueName||PY(i.appModuleId),c={name:i.appModuleName,uniquename:l,clienttype:4,formfactor:1,navigationtype:0};i.appModuleDescription&&(c.description=i.appModuleDescription),i.appModuleAiDescription&&(c.aiappdescription=i.appModuleAiDescription),s&&(c.webresourceid=s);let d="/appmodules";if(r){let T=n?(0,De.normalizeGuid)(n,"appmoduleid"):void 0,O=i.sitemapId?(0,De.normalizeGuid)(i.sitemapId,"sitemapId"):void 0;return r.reached({effects:[{componentName:"AppModule",componentId:T,identity:"known",operation:"create"},O?{componentName:"SiteMap",componentId:O,identity:"known",operation:"create"}:{componentName:"SiteMap",identity:"assignedAtWrite",operation:"create"}],attemptsWrite:!0},T?()=>(0,ea.existsByKey)(e,r,{collection:"/appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()",key:"appmoduleid",id:T,componentName:"AppModule"}):void 0)}let f=(0,ce.ensureSuccess)(await(0,ce.resendDeadlockVictim)(()=>e.post(d,(0,ce.withClientMintedId)(c,"appmoduleid",n))),e.apiUrl(d)),p=(0,ce.resolveCreatedId)(f,"appmoduleid","app module",n),m=null,h=null,g=[];u&&g.push(u);let y={kind:"notRequested"},b=i.sitemapId?(0,De.normalizeGuid)(i.sitemapId,"sitemapId"):(0,Pw.newId)(),E=!1,w,_=Xh(i);try{let T="/sitemaps",O=(0,ce.echoWrite)("sitemapid"),v=await e.post(`${T}${O.query}`,{sitemapid:b,sitemapnameunique:l,..._},O.options);E=IR(v.status);let N=(0,ce.ensureSuccess)(v,e.apiUrl(T));h=(0,ce.readEtag)(N),m=h??await Hh(e,b,_,l);let S=await uR(e,i,o);g.push(...S.warnings);let R=S.components;R.unshift({"@odata.type":"Microsoft.Dynamics.CRM.sitemap",sitemapid:b}),await SR(e,p,R);let x=xs(e,p);if(await Mw(e,p,S.tables,x),o){let U=await qY(e,p,o,x);w={mode:"create",tables:eg(U),published:"notRead"}}let G=await $Y(e,p);G&&g.push(G),i.appSettings&&Object.keys(i.appSettings).length>0&&g.push(...await(0,IY.applyAppSettings)(e,p,i.appSettings)),i.published!==!1&&(await(0,Fw.publishAppModule)(e,p),y={kind:"submitted"})}catch(T){let O=await ZY(e,p,{sitemapId:b,sitemapNameUnique:l,serverRefusedSitemap:E,sitemapWriteToken:h});throw(0,TY.failedAfterPrimaryWrite)(eQ(T,O,{appId:p,sitemapId:b,uniqueName:l}))}let I=null;if(y.kind==="submitted")try{let T=await e.get(`/appmodules(${p})?$select=appmoduleid`);T.status>=200&&T.status<300&&(I=(0,ce.readEtag)(T))}catch{}return qw(e,p),{id:p,etag:m,serverIdentity:{sitemapId:b},siblingEtags:{[p]:I},publish:y,...g.length>0?{warnings:g}:{},...w?{appMainForms:w}:{}}},async update(e,t,n,r,i,o,a=void 0){var s,u,l,c,d,f;let p=n,m=(0,De.normalizeGuid)(t,"id");if(await mR(e,p.sitemapxml,a),!p.sitemapId)throw new fe.ValidationError("app",m,[{pointer:"/sitemapId",rule:"app-sitemap-identity-missing",message:`missing sitemap identity \u2014 re-fetch the app before pushing edits: fetchArtifact('app', '${m}', { 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', '${m}'), clear the local copy with deleteArtifact('app', '${m}'), then author the app again and push.`}]);let h=(0,De.normalizeGuid)(p.sitemapId,"sitemapId");if(!(0,ce.isVersionToken)(r))throw a?.observe({guard:"ifMatch",componentName:"SiteMap",componentId:h,held:r,status:"missingHeld"}),new fe.SdkError("APP_UPDATE_NO_ETAG",`Refusing to push app '${m}': ${r?`the concurrency token held for its sitemap row ('${r}') 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 g=await dR(e,p,m),y=await uR(e,p,g),b=p.components.mainFormsOnUpdate==="exact"&&g!==void 0,E=`/appmodules(${m})`,w=(s=o?.[m])!==null&&s!==void 0?s:null,_,I,T;try{let xe=Rw(b?`${zh},ismanaged`:zh,m),Et=await e.get(xe),zt=(u=Et.body)===null||u===void 0?void 0:u.value;if(b&&Et.status>=200&&Et.status<300&&(!Array.isArray(zt)||zt.length!==1||!Gf((l=zt[0])===null||l===void 0?void 0:l.appmoduleid,m)))I=Array.isArray(zt)?zt.length===1?"the header read returned one row that is not identified as this app, not exactly one row of this app":`the header read returned ${zt.length} rows, not exactly one row of this app`:"the header read returned no row collection, not exactly one row of this app";else if(Et.status>=200&&Et.status<300){let Ht=qf(Et);if(typeof Ht=="object"&&Ht!==null&&!Array.isArray(Ht)){_=Ht;let W=_.uniquename;T=typeof W=="string"&&W?W:void 0}}}catch{}let O=lQ(p,_),v=await Bf(e,m,T||p.appModuleUniqueName,"push");if(v?.sitemapId!==h)throw new fe.SdkError("APP_SITEMAP_UNRESOLVED",`Refusing to push app '${m}': ${v?`its sitemap is now '${v.sitemapId}'`:"it has no sitemap now"}, not '${h}', the one this copy holds \u2014 the app's sitemap is no longer the one this copy was fetched with. Nothing was modified. Re-fetch the app (fetchArtifact('app', '${m}', { overwrite: true })) and re-apply the change.`);if(b)return jY({client:e,appId:m,body:p,sitemapId:h,sitemapToken:r,appToken:w,headerWrite:O,currentHeader:_,headerProblem:I,plan:y,sets:g,expectedUniqueName:p.sitemapNameUnique||T||p.appModuleUniqueName||void 0,preview:a});let N=w,S=Object.keys(O).length>0;if(S&&!(0,ce.isVersionToken)(w))throw new fe.SdkError("APP_UPDATE_NO_ETAG",`Refusing to push app '${m}': ${w?`the concurrency token held for its appmodule header ('${w}') 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', '${m}', { overwrite: true })) and re-apply the change.`);if(a)return uQ(e,a,{appId:m,sitemapId:h,sitemapToken:r,appToken:w,writesHeader:S,headerRead:_!==void 0,pinMayGuard:p.published!==!0&&y.components.length>0&&e.supportsAtomicBatch&&(0,ce.isVersionToken)(w)});if(S&&(0,ce.isVersionToken)(w)){let xe=(0,ce.echoWrite)("appmoduleid",{"If-Match":w}),Et=await e.patch(`${E}${xe.query}`,O,xe.options);if(sQ(Et))throw OR(m);(0,ce.ensureSuccess)(Et,e.apiUrl(E)),N=(0,ce.readEtag)(Et)}let R=Xh(p),x=p.sitemapNameUnique||T||p.appModuleUniqueName||void 0,G=(0,ce.echoWrite)("sitemapid",{"If-Match":r}),U=`/sitemaps(${h})`,M;try{M=(0,ce.ensureSuccess)(await e.patch(`${U}${G.query}`,{...R},G.options),e.apiUrl(U))}catch(xe){throw(0,fe.withPartialTokens)(xe,{siblingEtags:{[m]:N}})}let q=[...y.warnings],X=await XY(e,m,y,p.published!==!0&&y.components.length>0&&e.supportsAtomicBatch&&(0,ce.isVersionToken)(N)?N:void 0);N=(c=X.appToken)!==null&&c!==void 0?c:N,q.push(...X.warnings);let ye=xs(e,m);try{if(X.error!==void 0)throw X.error;await Mw(e,m,y.tables,ye)}catch(xe){q.push(`App '${m}': one or more components were not pinned (${xe.message}). Navigation may reference content not included in the app; re-push to retry.`)}let Ve;if(g){let xe=await BY(e,m,g,ye);q.push(...xe.warnings),Ve={mode:"addOnly",tables:xe.tables,published:"notRead"}}let _e={kind:"notRequested"},wt=N,Fn=(d=(0,ce.readEtag)(M))!==null&&d!==void 0?d:await Hh(e,h,R,x);if(p.published===!0){try{await CR(e,m),_e={kind:"submitted"}}catch(xe){_e={kind:"failed",error:xe},q.push(`App '${m}': saved, but publishing failed (${xe.message}). The app remains unpublished; re-push to retry.`)}if(_e.kind==="submitted"){wt=null;try{let xe=await e.get(`/appmodules(${m})?$select=appmoduleid`);xe.status>=200&&xe.status<300&&(wt=(0,ce.readEtag)(xe)),Fn=(f=await Hh(e,h,R,x))!==null&&f!==void 0?f:Fn}catch{}}}return{id:m,etag:Fn,siblingEtags:{[m]:wt},publish:_e,...q.length>0?{warnings:q}:{},...Ve?{appMainForms:Ve}:{}}},planPush(e,t,n){return(0,ea.planPushThrough)(Yt.appApi,e,t,n)},async delete(e,t){let n=(0,De.normalizeGuid)(t,"id");await TR(e,n,await NR(e,n))}}});var Us=C(ni=>{"use strict";Object.defineProperty(ni,"__esModule",{value:!0});ni.rebuildRaw=ni.assembleChildren=ni.spliceChildren=ni.mergeAttrs=ni.rawFromNode=ni.emptyBag=void 0;var Fs=Y(),DR=1e6,rg=512;function cQ(){return{a:[],c:[]}}ni.emptyBag=cQ;function PR(e,t=0){if(t>rg)throw new Fs.InvalidArgumentError(`Artifact node tree exceeds the maximum depth of ${rg}`);return{n:e.getNodeName(),a:e.getAllProperties().map(n=>[n.key,n.value]),c:e.getAllChildren().map(n=>PR(n,t+1))}}ni.rawFromNode=PR;function dQ(e,t,n=[]){let r=new Map;for(let[s,u]of t)r.set(s,u);let i=new Set(n.filter(s=>!r.has(s))),o=new Set,a=[];for(let[s,u]of e)i.has(s)||(r.has(s)?a.push([s,r.get(s)]):a.push([s,u]),o.add(s));for(let[s,u]of t)o.has(s)||(a.push([s,u]),o.add(s));return a}ni.mergeAttrs=dQ;function ng(e,t){let n=new Set;for(let s of e){let u=s.i;if(!Number.isInteger(u)||u<0||u>DR)throw new Fs.InvalidArgumentError(`Bag child index must be an integer in [0, ${DR}] (got ${String(u)})`);if(n.has(u))throw new Fs.InvalidArgumentError(`Duplicate bag child index ${u}`);n.add(u)}let r=[...e].sort((s,u)=>s.i-u.i),i=[],o=0,a=0;for(let s of r){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}ni.spliceChildren=ng;function fQ(e,t){if(e.w){let n={n:e.w.n,a:e.w.a.map(r=>[r[0],r[1]]),c:ng(e.w.c,t)};return ng(e.c,[n])}return ng(e.c,t)}ni.assembleChildren=fQ;function RR(e,t,n,r=0){if(r>rg)throw new Fs.InvalidArgumentError(`Artifact node tree exceeds the maximum depth of ${rg}`);pQ(e,r);let i=t.make(e.n,n);for(let[o,a]of e.a)t.setProp(i,o,a);for(let o of e.c)t.addChild(i,RR(o,t,i,r+1));return i}ni.rebuildRaw=RR;function pQ(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Fs.InvalidArgumentError(`Malformed hybrid node at depth ${t}: expected a JSON object`);let n=e;if(typeof n.n!="string")throw new Fs.InvalidArgumentError(`Malformed hybrid node at depth ${t}: 'n' (tag name) must be a string`);if(!Array.isArray(n.a)||!Array.isArray(n.c))throw new Fs.InvalidArgumentError(`Malformed hybrid node '${n.n}': 'a' and 'c' must be arrays`);for(let r of n.a)if(!Array.isArray(r)||r.length!==2||typeof r[0]!="string"||typeof r[1]!="string")throw new Fs.InvalidArgumentError(`Malformed hybrid node '${n.n}': each attribute must be a [string, string] pair`)}});var Ga=C(ig=>{"use strict";Object.defineProperty(ig,"__esModule",{value:!0});ig.installDomShim=void 0;var kR=Ms(),$R=!1,mQ={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 hQ(){if($R)return;let e=globalThis;typeof e.DOMParser>"u"&&(e.DOMParser=kR.DOMParser),typeof e.XMLSerializer>"u"&&(e.XMLSerializer=kR.XMLSerializer),typeof e.Node>"u"&&(e.Node=mQ),$R=!0}ig.installDomShim=hQ});var ja=C(on=>{"use strict";Object.defineProperty(on,"__esModule",{value:!0});on.projectElementBag=on.serializeNode=on.domEngine=on.nodeLikeFromDom=on.parseXmlRoot=on.EMPTY_FORM_SENTINEL=on.TEXT_SENTINEL=void 0;var gQ=Us(),Ec=Y(),yQ=Ga();on.TEXT_SENTINEL="#text";on.EMPTY_FORM_SENTINEL="#empty";var ag=new WeakSet;function bQ(e,t){(0,yQ.installDomShim)();let n=e&&e.trim()!==""?e:t,r=new DOMParser().parseFromString(n,"text/xml"),i=r.documentElement;if(!i)throw new Ec.InvalidArgumentError("XML source has no root element (empty or malformed input)");return vQ(n),EQ(r),CQ(i),SQ(i),IQ(i,n),i}on.parseXmlRoot=bQ;function vQ(e){let t=e.search(/\S/);if(t!==-1&&e[t]!=="<")throw MR(3)}var wQ=["http://www.mozilla.org/newlayout/xml/parsererror.xml","http://www.w3.org/1999/xhtml"];function EQ(e){var t;for(let n of wQ){let r=e.getElementsByTagNameNS(n,"parsererror")[0];if(r){let i=((t=r.textContent)!==null&&t!==void 0?t:"").replace(/\s+/g," ").trim().slice(0,200);throw new Ec.InvalidArgumentError(`XML source is not well-formed (${i||"the XML parser reported an error"}), so it cannot be round-tripped`)}}}var AQ=new Set([1,3]);function CQ(e){let t=[e];for(;t.length>0;){let r=t.pop().childNodes;for(let i=0;i<r.length;i+=1){let o=r[i];if(!AQ.has(o.nodeType))throw new Ec.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 SQ(e){var t,n;let r=(t=e.ownerDocument)!==null&&t!==void 0?t:e.parentNode;if(!r)return;let i=r.childNodes;for(let o=0;o<i.length;o+=1){let a=i[o];if(a!==e&&!(a.nodeType===3&&((n=a.nodeValue)!==null&&n!==void 0?n:"").trim()===""))throw MR(a.nodeType)}}function MR(e){return new Ec.InvalidArgumentError(`Unsupported document-level XML node (type ${e}: declaration / comment / processing-instruction outside the root element) cannot be round-tripped`)}function NQ(e){let t=[],n=/<([^>]*)>/g;for(let r=n.exec(e);r!==null;r=n.exec(e)){let i=r[1];i.startsWith("/")||i.startsWith("?")||i.startsWith("!")||t.push(i.endsWith("/"))}return t}function _Q(e){let t=[],n=[e];for(;n.length>0;){let r=n.pop();t.push(r);let i=r.childNodes;for(let o=i.length-1;o>=0;o-=1){let a=i[o];a.nodeType===1&&n.push(a)}}return t}function xR(e){let t=e.childNodes;for(let n=0;n<t.length;n+=1){let r=t[n].nodeType;if(r===1||r===3)return!0}return!1}function IQ(e,t){let n=NQ(t),r=_Q(e),i=Math.min(n.length,r.length);for(let o=0;o<i;o+=1){if(n[o])continue;let a=r[o];xR(a)||ag.add(a)}}function Gw(e){let t=e.nodeType===3;return{getNodeName:()=>t?on.TEXT_SENTINEL:e.tagName,getAllProperties:()=>{var n;if(t)return[{key:on.TEXT_SENTINEL,value:(n=e.nodeValue)!==null&&n!==void 0?n:""}];let r=e.attributes,i=[];for(let o=0;o<r.length;o+=1)i.push({key:r[o].name,value:r[o].value});return ag.has(e)&&!xR(e)&&i.push({key:on.EMPTY_FORM_SENTINEL,value:"1"}),i},getAllChildren:()=>{if(t)return[];let n=[],r=e.childNodes;for(let i=0;i<r.length;i+=1){let o=r[i];(o.nodeType===1||o.nodeType===3)&&n.push(Gw(o))}return n}}}on.nodeLikeFromDom=Gw;function TQ(e){return{make:t=>t===on.TEXT_SENTINEL?e.createTextNode(""):e.createElement(t),setProp:(t,n,r)=>{t.nodeType===3?t.nodeValue=r:n===on.EMPTY_FORM_SENTINEL?ag.add(t):t.setAttribute(n,r)},addChild:(t,n)=>{t.appendChild(n)}}}on.domEngine=TQ;function FR(e){for(let t=0;t<e.length;t+=1){let n=e.charCodeAt(t);if(n<=31&&n!==9&&n!==10&&n!==13||n===65534||n===65535)throw og(n);if(n>=55296&&n<=56319){let r=e.charCodeAt(t+1);if(!(r>=56320&&r<=57343))throw og(n);t+=1;continue}if(n>=56320&&n<=57343)throw og(n)}}function og(e){let t=e.toString(16).toUpperCase().padStart(4,"0");return new Ec.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 OQ(e){return FR(e),String(e).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/\r/g,"
").replace(/\n/g,"
").replace(/\t/g,"	")}function DQ(e){return FR(e),String(e).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}function PQ(e){return UR(e,0)}on.serializeNode=PQ;var LR=512;function UR(e,t){var n;if(t>LR)throw new Ec.InvalidArgumentError(`XML nesting exceeds the maximum supported depth of ${LR}`);if(e.nodeType===3)return DQ((n=e.nodeValue)!==null&&n!==void 0?n:"");let r=e,i="<"+r.tagName,o=r.attributes;for(let u=0;u<o.length;u+=1)i+=" "+o[u].name+'="'+OQ(o[u].value)+'"';let a=[],s=r.childNodes;for(let u=0;u<s.length;u+=1){let l=s[u];(l.nodeType===1||l.nodeType===3)&&a.push(l)}if(a.length===0)return ag.has(r)?i+"></"+r.tagName+">":i+" />";i+=">";for(let u of a)i+=UR(u,t+1);return i+"</"+r.tagName+">"}function RQ(e){let t=Gw(e);return{a:t.getAllProperties().map(n=>[n.key,n.value]),c:t.getAllChildren().map((n,r)=>({i:r,node:(0,gQ.rawFromNode)(n)}))}}on.projectElementBag=RQ});var Vi=C(hr=>{"use strict";Object.defineProperty(hr,"__esModule",{value:!0});hr.rejectUnknownKeys=hr.childObjects=hr.optionalGuidId=hr.optionalEnum=hr.eachObject=hr.issue=hr.isJsonObject=void 0;function qR(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}hr.isJsonObject=qR;function Ac(e,t,n,r){return r?{pointer:e,rule:t,message:n,fatal:r}:{pointer:e,rule:t,message:n}}hr.issue=Ac;function BR(e,t,n,r){if(!Array.isArray(e))return[];let i=[];return e.forEach((o,a)=>{qR(o)?i.push({node:o,index:a}):r.push(Ac(`${t}/${a}`,`${n}-must-be-object`,`a ${n} must be a JSON object, got ${o===null?"null":typeof o}`))}),i}hr.eachObject=BR;function kQ(e,t,n,r,i,o){let a=e[t];a!==void 0&&(typeof a!="string"||!n.includes(a))&&o.push(Ac(`${r}/${t}`,i,`${t} must be one of ${n.map(s=>`'${s}'`).join(", ")}, got ${JSON.stringify(a)}`))}hr.optionalEnum=kQ;var $Q=/^(?:\{[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 LQ(e,t,n,r,i){let o=e[t];typeof o=="string"&&o!==""&&!$Q.test(o)&&i.push(Ac(`${n}/${t}`,r,`${t} must be a GUID or empty, got '${o}'`))}hr.optionalGuidId=LQ;function MQ(e,t,n,r,i){let o=e[t],a=`${n}/${t}`;return o===void 0?[]:Array.isArray(o)?BR(o,a,r,i):(i.push(Ac(a,`${r}-list-must-be-array`,`${t} must be an array when present, got ${typeof o}`)),[])}hr.childObjects=MQ;function xQ(e,t,n,r,i,o={}){var a,s;for(let u of Object.keys(e)){if(t.has(u))continue;let l=(a=o.elsewhere)===null||a===void 0?void 0:a[u],c=(s=o.unsupported)===null||s===void 0?void 0:s[u],d=l?` '${u}' is a ${l} key \u2014 set it on the ${l} instead.`:c?` ${c}`:` Put values the typed layer does not model in '${r}.bag', which round-trips them verbatim.`;i.push(Ac(`${n}/${u}`,`${r}-unknown-key`,`'${u}' is not a ${r} property, and would be SILENTLY DROPPED at serialization.${d}`))}}hr.rejectUnknownKeys=xQ});var dg=C(J=>{"use strict";Object.defineProperty(J,"__esModule",{value:!0});J.genPageEmbedIssues=J.setUniqueId=J.mintEmbedIdentity=J.authoredUniqueId=J.hasGenPage=J.applyEmbedCellDefaults=J.applyEmbedControlDefaults=J.mayCommitEmbedState=J.commitEmbedState=J.reconcileEmbedDescriptions=J.embedAppendIndex=J.activeEmbedBindings=J.projectGenPageEmbeds=J.isRecognizedEmbed=J.isUnbound=J.effectiveClassId=J.effectiveFormType=J.inputDataFrom=J.classifyBinding=J.isStaticParameter=J.entryParameter=J.pageEntries=J.descriptionFor=J.descriptionsRegion=J.controlUniqueIds=J.controlUniqueId=J.typedCellSites=J.typedCells=J.rawText=J.rawAttr=J.normGuid=J.GENPAGE_FORM_FACTORS=J.GENPAGE_EMBED_ROWSPAN=J.GENPAGE_CONTROL_NAME=J.CUSTOM_CONTROL_CLASS_ID=void 0;var FQ=Ms(),UQ=ec(),jw=ft(),Gi=Vi();J.CUSTOM_CONTROL_CLASS_ID="F9A8A302-114E-466A-B582-6771B2AE0D92";J.GENPAGE_CONTROL_NAME="MscrmControls.UxAgentControl";J.GENPAGE_EMBED_ROWSPAN=6;J.GENPAGE_FORM_FACTORS=["2","0","1"];var qQ=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function ri(e){if(typeof e!="string")return"";let t=e.trim().toLowerCase();return t.startsWith("{")&&t.endsWith("}")&&(t=t.slice(1,-1)),qQ.test(t)?t:""}J.normGuid=ri;function qs(e,t){let n=et(e?.a).find(r=>Array.isArray(r)&&r[0]===t);return n?n[1]:void 0}J.rawAttr=qs;function Wf(e){return et(e?.c).filter(t=>typeof t?.n=="string"&&t.n.startsWith("<")).map(t=>t.n.slice(1)).join("")}J.rawText=Wf;function et(e){return Array.isArray(e)?e:[]}function Yw(e,t){let n=et(e?.a).find(r=>Array.isArray(r)&&r[0]===t);return n?n[1]:void 0}function jR(e){return typeof e=="string"?e.trim().replace(/^\{|\}$/g,"").toUpperCase():""}function WR(e){return go(e).map(t=>t.cell)}J.typedCells=WR;function go(e){let t=[];return et(e?.tabs).forEach((n,r)=>{et(pt(n)?n.columns:void 0).forEach((i,o)=>{et(pt(i)?i.sections:void 0).forEach((a,s)=>{et(pt(a)?a.rows:void 0).forEach((u,l)=>{et(pt(u)?u.cells:void 0).forEach((c,d)=>{pt(c)&&t.push({cell:c,pointer:`/tabs/${r}/columns/${o}/sections/${s}/rows/${l}/cells/${d}`})})})})})}),t}J.typedCellSites=go;function Wa(e){return pt(e)?ri(Yw(e.bag,"uniqueid")):""}J.controlUniqueId=Wa;function BQ(e){let t=new Set;for(let{cell:n}of go(e)){let r=Ku(n.control)?Wa(n.control):"";r&&t.add(r)}return t}function VQ(e){let t=new Map;for(let{cell:n}of go(e)){let r=pt(n.control)?Wa(n.control):"";r&&!t.has(r)&&t.set(r,n.control)}return t}function GQ(e){return e!==void 0&&e.genPage===void 0&&(Zw(e)!==J.CUSTOM_CONTROL_CLASS_ID||!cg(e))}function Ww(e,t){if(pt(e)){t(e);for(let n of et(e.c))Ww(n,t)}}function zu(e,t){var n;if(pt(e)){for(let r of et(e.c))Ww(r?.node,t);for(let r of et((n=e.w)===null||n===void 0?void 0:n.c))Ww(r?.node,t)}}function ug(e){let t=new Map,n=i=>{var o;i&&t.set(i,((o=t.get(i))!==null&&o!==void 0?o:0)+1)},r=i=>{i.n==="control"&&n(ri(qs(i,"uniqueid")))};return zu(e?.bag,r),et(e?.tabs).forEach(i=>{pt(i)&&(zu(i.bag,r),et(i.columns).forEach(o=>{pt(o)&&(zu(o.bag,r),et(o.sections).forEach(a=>{pt(a)&&(zu(a.bag,r),et(a.rows).forEach(s=>{pt(s)&&(zu(s.bag,r),et(s.cells).forEach(u=>{pt(u)&&(zu(u.bag,r),pt(u.control)&&(n(Wa(u.control)),zu(u.control.bag,r)))}))}))}))}))}),t}J.controlUniqueIds=ug;function Cc(e){return et(e?.c).find(t=>{var n;return((n=t?.node)===null||n===void 0?void 0:n.n)==="controlDescriptions"})}J.descriptionsRegion=Cc;function Hu(e,t){var n;let r=ri(t);if(r)return et((n=Cc(e))===null||n===void 0?void 0:n.node.c).find(i=>i?.n==="controlDescription"&&ri(qs(i,"forControl"))===r)}J.descriptionFor=Hu;function zf(e){return et(e.c).filter(zR)}J.pageEntries=zf;function zR(e){return e?.n==="customControl"&&qs(e,"name")===J.GENPAGE_CONTROL_NAME}function zw(e,t){let n=et(e.c).find(r=>r?.n==="parameters");return et(n?.c).find(r=>r?.n===t)}J.entryParameter=zw;function Hw(e){return qs(e,"static")==="true"}J.isStaticParameter=Hw;function Hf(e){let t=zf(e);if(t.length===0)return{kind:"none"};let n,r;for(let i=0;i<t.length;i+=1){let o=zw(t[i],"RefId");if(!o||!Hw(o))return{kind:"unsupported"};let a=ri(Wf(o));if(!a)return{kind:"unsupported"};let s=zw(t[i],"PageInput");if(s&&!Hw(s))return{kind:"unsupported"};let u=s?Wf(s):void 0;if(i===0)n=a,r=u;else if(a!==n||u!==r)return{kind:"unsupported"}}return r===void 0?{kind:"projectable",pageId:n}:{kind:"projectable",pageId:n,pageInputRaw:r}}J.classifyBinding=Hf;function pt(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Qw(e){if(e===void 0)return;let t;try{t=JSON.parse(e)}catch{return}return pt(t)&&pt(t.data)?t.data:void 0}J.inputDataFrom=Qw;function Xw(e){var t;return(t=e.formType)!==null&&t!==void 0?t:"Main"}J.effectiveFormType=Xw;function Zw(e){return jR(e.classId!==void 0?e.classId:Yw(e.bag,"classid"))}J.effectiveClassId=Zw;function cg(e){return!e.fieldName}J.isUnbound=cg;function eE(e,t){if(Xw(e)!=="Main"||!cg(t)||Zw(t)!==J.CUSTOM_CONTROL_CLASS_ID)return!1;let n=Wa(t),r=n?Hu(e.bag,n):void 0;return r!==void 0&&Hf(r).kind==="projectable"}J.isRecognizedEmbed=eE;function jQ(e){for(let t of WR(e)){let n=t.control;if(!n||!eE(e,n))continue;let r=Hf(Hu(e.bag,Wa(n)));if(r.kind!=="projectable")continue;let i=Qw(r.pageInputRaw);n.genPage=i===void 0?{pageId:r.pageId}:{pageId:r.pageId,inputData:i}}}J.projectGenPageEmbeds=jQ;var WQ=new Set(["pageId","inputData"]);function jf(e){let t=[];for(let n=0;n<e.childNodes.length;n+=1){let r=e.childNodes[n];r.nodeType===1&&t.push(r)}return t}function zQ(e){var t;let n=[],r=c=>d=>n.push(`${c}: ${d}`),i=new FQ.DOMParser({errorHandler:{warning:r("warning"),error:r("error"),fatalError:r("fatalError")}}).parseFromString(e,"text/xml"),o=(t=i?.documentElement)!==null&&t!==void 0?t:null;if(!o||n.length>0)throw new Error(`the formxml does not parse cleanly${n.length>0?` (${n[0]})`:""}`);let a=new Set,s=o.getElementsByTagName("control");for(let c=0;c<s.length;c+=1){let d=ri(s[c].getAttribute("uniqueid"));d&&a.add(d)}let u=jf(o).find(c=>c.nodeName==="controlDescriptions"),l=new Map;for(let c of u?jf(u):[]){let d=ri(c.getAttribute("forControl"));if(!(c.nodeName!=="controlDescription"||!d||!a.has(d)))for(let f of jf(c)){if(f.nodeName!=="customControl"||f.getAttribute("name")!==J.GENPAGE_CONTROL_NAME)continue;let p=jf(f).find(g=>g.nodeName==="parameters"),m=p?jf(p).find(g=>g.nodeName==="RefId"):void 0,h=m&&m.getAttribute("static")==="true"?ri(m.textContent):"";h&&l.set(`${d}|${h}`,[d,h])}}return[...l.values()]}J.activeEmbedBindings=zQ;function sg(e){return{n:`<${e}`,a:[],c:[]}}function Kw(e,t){return{n:e,a:[["type","SingleLine.Text"],["static","true"]],c:[sg(t)]}}function Jw(e,t){let n={};if(t!==void 0)try{let r=JSON.parse(t);pt(r)&&(n=r)}catch{}return JSON.stringify({...n,data:e})}function HQ(e,t,n){return{n:"controlDescription",a:[["forControl",e]],c:J.GENPAGE_FORM_FACTORS.map(r=>({n:"customControl",a:[["name",J.GENPAGE_CONTROL_NAME],["formFactor",r]],c:[{n:"parameters",a:[],c:[Kw("RefId",t),...n===void 0?[]:[Kw("PageInput",Jw(n))]]}]}))}}function lg(e,t){if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((n,r)=>lg(n,t[r]));if(pt(e)&&pt(t)){let n=Object.keys(e);return n.length===Object.keys(t).length&&n.every(r=>r in t&&lg(e[r],t[r]))}return e===t}function KQ(e,t,n){let r=et(e.c).find(l=>l?.n==="parameters");if(!r||!Array.isArray(r.c))return;let i=r.c.find(l=>l?.n==="RefId");i&&ri(Wf(i))!==t&&(i.c=[sg(t)]);let o=r.c.findIndex(l=>l?.n==="PageInput"),a=o>=0?r.c[o]:void 0,s=a?Wf(a):void 0;if(lg(Qw(s),n))return;if(n!==void 0){a?a.c=[sg(Jw(n,s))]:r.c.push(Kw("PageInput",Jw(n)));return}let u=JSON.parse(s);delete u.data,Object.keys(u).length===0?r.c.splice(o,1):a.c=[sg(JSON.stringify(u))]}function tE(e){let t=et(e?.c),n=t.reduce((r,i)=>i.i>r?i.i:r,-1);return Math.max(n,t.length)+1}J.embedAppendIndex=tE;function JQ(e,t){var n;let r=e.bag,i=Cc(r);if(i&&t){let o=ug(t),a=ug(e),s=BQ(t),u=VQ(e),l=et(i.node.c),c=[];for(let d of l){let f=d?.n==="controlDescription"&&zf(d).length>0?ri(qs(d,"forControl")):"";if(!f||!o.has(f))c.push(d);else if(a.has(f))if(s.has(f)&&GQ(u.get(f))&&lg(d,Hu(t.bag,f))){let p=et(d.c).filter(m=>!zR(m));p.length>0&&c.push({...d,c:p})}else c.push(d)}(c.length!==l.length||c.some((d,f)=>d!==l[f]))&&(i.node.c=c)}for(let{cell:o}of go(e)){let a=o.control;if(!Ku(a)||!pt(a.genPage))continue;let s=ri(a.genPage.pageId),u=a.genPage.inputData,l=Wa(a);if(!l){if(Kf(a)!==void 0)continue;l=nE(a)}let c=Hu(r,l);if(c){for(let p of zf(c))KQ(p,s,u);continue}i||(i={i:tE(r),node:{n:"controlDescriptions",a:[],c:[]}},r.c.push(i));let d=((n=Yw(a.bag,"uniqueid"))!==null&&n!==void 0?n:"").trim(),f=d.startsWith("{")?d:`{${l}}`;i.node.c.push(HQ(f,s,u))}}J.reconcileEmbedDescriptions=JQ;function YQ(e,t){let n=Cc(e.bag),r=t!==void 0&&(n===void 0||JSON.stringify(n.node)!==JSON.stringify(t)),i=go(e).some(({cell:a})=>Ku(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(!r&&!i)return e;let o=JSON.parse(JSON.stringify(e));if(r){let a=JSON.parse(JSON.stringify(t)),s=Cc(o.bag);s?s.node=a:(o.bag=pt(o.bag)?o.bag:{a:[],c:[]},o.bag.c=et(o.bag.c),o.bag.c.push({i:tE(e.bag),node:a}))}for(let{cell:a}of go(o))Ku(a.control)&&(HR(a.control),KR(a));return o}J.commitEmbedState=YQ;function QQ(e){if(go(e).some(({cell:n})=>Ku(n.control)))return!0;let t=Cc(e.bag);return et(t?.node.c).some(n=>n?.n==="controlDescription"&&zf(n).length>0)}J.mayCommitEmbedState=QQ;function HR(e){e.classId===void 0&&(e.classId=J.CUSTOM_CONTROL_CLASS_ID),e.showLabel===void 0&&(e.showLabel=!1),e.label===void 0&&(e.label=""),e.fieldName===void 0&&(e.fieldName=null)}J.applyEmbedControlDefaults=HR;function KR(e){e.rowspan===void 0&&(e.rowspan=J.GENPAGE_EMBED_ROWSPAN)}J.applyEmbedCellDefaults=KR;function Ku(e){return pt(e)&&e.genPage!==void 0}J.hasGenPage=Ku;function VR(e){return Ku(e.control)&&(!e.control.id||!e.id||Kf(e.control)===void 0)}function Kf(e){let t=et(pt(e.bag)?e.bag.a:void 0).find(r=>Array.isArray(r)&&r[0]==="uniqueid");if(!t)return;let n=t[1];return typeof n=="string"&&n.trim()===""?void 0:n}J.authoredUniqueId=Kf;function XQ(e){if(!go(e).some(({cell:n})=>VR(n)))return e;let t=JSON.parse(JSON.stringify(e));for(let{cell:n}of go(t)){if(!VR(n))continue;let r=n.control;r.id||(r.id=(0,jw.newId)()),n.id||(n.id=(0,jw.newId)()),Kf(r)===void 0&&nE(r)}return t}J.mintEmbedIdentity=XQ;function nE(e){let t=(0,jw.newId)(),n=`{${t}}`;if(!pt(e.bag))return e.bag={a:[["uniqueid",n]],c:[]},t;let r=et(e.bag.a),i=r.find(o=>Array.isArray(o)&&o[0]==="uniqueid");return i?i[1]=n:r.push(["uniqueid",n]),e.bag.a=r,e.bag.c=et(e.bag.c),t}J.setUniqueId=nE;function GR(e){return e===null?"null":Array.isArray(e)?"an array":typeof e}function ZQ(e){let t=et(e.c).filter(n=>n?.n==="customControl").map(n=>{var r,i;return(i=(r=qs(n,"name"))!==null&&r!==void 0?r:qs(n,"id"))!==null&&i!==void 0?i:"unnamed"});return[...new Set(t)].join(", ")||"no custom control"}function eX(e){let t=[],n;for(let{cell:r,pointer:i}of go(e)){let o=r.control;if(!pt(o))continue;let a=`${i}/control`;if(o.genPage===void 0){tX(e,o,a,t);continue}n=n??ug(e),nX(e,o,a,n,t)}return t}J.genPageEmbedIssues=eX;function tX(e,t,n,r){if(!eE(e,t))return;let i=Hf(Hu(e.bag,Wa(t)));r.push((0,Gi.issue)(n,"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 nX(e,t,n,r,i){var o;let a=`${n}/genPage`,s=t.genPage;if(!pt(s))i.push((0,Gi.issue)(a,"genpage-embed-shape",`genPage must be an object { pageId, inputData? }, got ${GR(s)}.`+(s===null?" To remove an embed, remove the cell (or set the cell's control to null).":"")));else{(typeof s.pageId!="string"||!ri(s.pageId))&&i.push((0,Gi.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&&!pt(s.inputData)&&i.push((0,Gi.issue)(`${a}/inputData`,"genpage-embed-shape",`genPage.inputData must be a JSON object \u2014 the page reads it as pageInput.data \u2014 got ${GR(s.inputData)}`));for(let p of Object.keys(s))WQ.has(p)||i.push((0,Gi.issue)(UQ.JsonPointer.append(a,p),"genpage-embed-unknown-key",`'${p}' is not a genPage property (pageId, inputData), and would be SILENTLY DROPPED at serialization.`))}cg(t)||i.push((0,Gi.issue)(`${n}/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&&jR(t.classId)!==J.CUSTOM_CONTROL_CLASS_ID&&i.push((0,Gi.issue)(`${n}/classId`,"genpage-embed-class-id",`a generative-page embed is the custom control {${J.CUSTOM_CONTROL_CLASS_ID}}, but classId is ${JSON.stringify(t.classId)}. Omit classId (the SDK defaults it) or set it to that class.`));let u=Xw(e);u!=="Main"&&i.push((0,Gi.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 ${u} form.`));let l=Kf(t);l!==void 0&&!ri(l)&&i.push((0,Gi.issue)(`${n}/bag`,"genpage-embed-unique-id",`this embed's uniqueid ${JSON.stringify(l)} 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=Wa(t);if(!c)return;let d=Hu(e.bag,c),f=d?Hf(d):void 0;d&&f?.kind==="none"?i.push((0,Gi.issue)(a,"genpage-embed-other-control",`this control is already bound to another custom control (${ZQ(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,Gi.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=r.get(c))!==null&&o!==void 0?o:0)>1&&i.push((0,Gi.issue)(`${n}/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 Sc=C(hn=>{"use strict";Object.defineProperty(hn,"__esModule",{value:!0});hn.isKnownSystemFormType=hn.assertSystemFormKind=hn.readSystemFormType=hn.decodeCode=hn.assertSystemFormRecordKind=hn.describeSystemFormType=hn.systemFormKindOf=hn.SYSTEMFORM_KIND_MISMATCH_CODE=void 0;var YR=Y(),rX=pe(),JR=ae();hn.SYSTEMFORM_KIND_MISMATCH_CODE="SYSTEMFORM_KIND_MISMATCH";var iX={0:"dashboard",10:"dashboard",2:"form",6:"form",7:"form",11:"form"},QR={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 fg(e){return Number.isInteger(e)?iX[e]:void 0}hn.systemFormKindOf=fg;function XR(e){var t;return Number.isFinite(e)?`a ${(t=QR[e])!==null&&t!==void 0?t:"systemform"} (type ${e})`:"a systemform whose type could not be read"}hn.describeSystemFormType=XR;function ZR(e,t,n,r){let i=XR(n),o=fg(n);switch(r){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(n)?"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 ${r} systemform '${e}': it is ${i}, not a ${t}.`+(r==="set the security roles of"?" Nothing was written.":"")+" Check the id."}}function oX(e,t,n,r){let i=rE(e?.type);if(fg(i)!==n)throw new YR.SdkError(hn.SYSTEMFORM_KIND_MISMATCH_CODE,ZR(t,n,i,r));return i}hn.assertSystemFormRecordKind=oX;function rE(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}hn.decodeCode=rE;async function aX(e,t){return await ek(e,t,!1)}hn.readSystemFormType=aX;async function sX(e,t){return ek(e,t,!0)}async function ek(e,t,n){var r;let o=`/systemforms(${(0,JR.normalizeGuid)(t,"formId")})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,JR.odataQuery)([["$select","type"]]),a=await e.get(o);if(!(n&&a.status===404))return(0,rX.ensureSuccess)(a,e.apiUrl(o)),rE((r=a.body)===null||r===void 0?void 0:r.type)}async function uX(e,t,n){let r=await sX(e,t);if(!(r===void 0||fg(r)===n))throw new YR.SdkError(hn.SYSTEMFORM_KIND_MISMATCH_CODE,ZR(t,n,r,"delete"))}hn.assertSystemFormKind=uX;function lX(e){return Number.isInteger(e)&&QR[e]!==void 0}hn.isKnownSystemFormType=lX});var oE=C(Di=>{"use strict";Object.defineProperty(Di,"__esModule",{value:!0});Di.patchSystemForm=Di.assertSystemFormContentUnchanged=Di.readSystemFormRowEtag=Di.unpublishedSystemFormPath=Di.FORM_TYPE_IMMUTABLE_CODE=void 0;var ii=pe(),Jf=qi(),cX=ae(),pg=Y(),Bs=Sc();Di.FORM_TYPE_IMMUTABLE_CODE="FORM_TYPE_IMMUTABLE";function iE(e,t="formid"){return`/systemforms(${e})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,cX.odataQuery)([["$select",t]])}Di.unpublishedSystemFormPath=iE;function tk(e,t){return(0,ii.readRowEtag)(e,"systemforms","formid",t)}Di.readSystemFormRowEtag=tk;async function nk(e,t,n,r,i,o){let a={guard:"contentToken",componentName:"SystemForm",componentId:t};o&&!(0,ii.isVersionToken)(i)&&o.observe({...a,held:i,status:"missingHeld"}),(0,ii.requireEtag)(i,n,t);let s;try{s=(0,ii.ensureSuccess)(await e.get(r),e.apiUrl(r))}catch(c){throw o?.observe({...a,held:i,status:(0,Jf.failedReadStatus)(c),detail:(0,Jf.failureDetail)(c)}),c}let u=(0,Bs.assertSystemFormRecordKind)(s.body,t,n,"write"),l=(0,ii.readEtag)(s);if(o?.observe({...a,held:i,server:l,status:(0,Jf.compareTokens)(i,l)}),l===null)throw new pg.SdkError(ii.VERSION_CONFLICT_CODE,`Refusing to write ${n} '${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(l!==i)throw new pg.SdkError(ii.VERSION_CONFLICT_CODE,`Version conflict writing ${n} '${t}': its formxml changed on the server since it was read (held ${i}, server ${l}). Re-fetch the ${n} and re-apply the change.`);return u}Di.assertSystemFormContentUnchanged=nk;async function dX(e,t,n,r,i,o,a){a&&!(0,ii.isVersionToken)(i)&&a.observe({guard:"contentToken",componentName:"SystemForm",componentId:t,held:i,status:"missingHeld"}),(0,ii.requireEtag)(i,n,t);let s;try{s=await tk(e,t)}catch(d){throw a?.observe({guard:"rowToken",componentName:"SystemForm",componentId:t,status:(0,Jf.failedReadStatus)(d),detail:(0,Jf.failureDetail)(d)}),d}if(s===null)throw a?.observe({guard:"rowToken",componentName:"SystemForm",componentId:t,status:"missingServer"}),new pg.SdkError(ii.VERSION_CONFLICT_CODE,`Refusing to write ${n} '${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 u=await nk(e,t,n,iE(t,"formid,type"),i,a);if(r.type!==void 0&&(0,Bs.decodeCode)(r.type)!==u)throw new pg.SdkError(Di.FORM_TYPE_IMMUTABLE_CODE,`Refusing to push ${n} '${t}': it would change it from ${(0,Bs.describeSystemFormType)(u)} to ${(0,Bs.describeSystemFormType)((0,Bs.decodeCode)(r.type))}. The platform ignores a type change on an existing ${n}, so the push would report a change that did not happen. Nothing was written. Create a new ${n} of that type instead.`);if(a)return a.reached({effects:[{componentName:"SystemForm",componentId:t,identity:"known",operation:"update"}],attemptsWrite:!0});let l=(0,ii.echoWrite)("formid",{"If-Match":s}),c=`/systemforms(${t})${l.query}`;return(0,ii.ensureSuccess)(await e.patch(c,r,l.options),e.apiUrl(c)),fX(e,t,n,o)}Di.patchSystemForm=dX;async function fX(e,t,n,r){let i;try{let o=iE(t,r.select),a=(0,ii.ensureSuccess)(await e.get(o),e.apiUrl(o)),s=a.body,u=(0,ii.readEtag)(a),l=typeof s?.formid=="string"&&s.formid.replace(/[{}]/g,"").toLowerCase()===t,c=typeof s?.formxml=="string"&&s.formxml.trim()!=="",d=r.required.filter(m=>s?.[m]===void 0||s?.[m]===null),f=(0,Bs.decodeCode)(s?.type),p=(0,Bs.systemFormKindOf)(f)===n;if(u&&l&&c&&d.length===0&&p)return{id:t,etag:u,readBack:s};i=u?!l||!c?`the read did not return this ${n}'s document`:d.length>0?`the read did not return its ${d.join(", ")}`:`the read returned ${(0,Bs.describeSystemFormType)(f)}, not a ${n}`:"the read returned no version"}catch(o){i=o instanceof Error?o.message:String(o)}return{id:t,etag:null,warnings:[`The ${n} 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 ${n} before editing it again.`]}}});var mg=C(jn=>{"use strict";Object.defineProperty(jn,"__esModule",{value:!0});jn.getFormSecurityRoles=jn.setFormSecurityRoles=jn.formApi=jn.readPrimaryCreateRefusal=jn.FORM_GENPAGE_TARGET_UNVERIFIABLE=jn.FORM_GENPAGE_TARGET_NOT_FOUND=void 0;var pX=Ke(),Nn=pe(),Pi=ae(),Ju=Y(),aE=ja(),ok=dg(),rk=Vh(),sE=oE(),Qf=Sc(),Yf=qi();jn.FORM_GENPAGE_TARGET_NOT_FOUND="FORM_GENPAGE_TARGET_NOT_FOUND";jn.FORM_GENPAGE_TARGET_UNVERIFIABLE="FORM_GENPAGE_TARGET_UNVERIFIABLE";var ak="formid,formxml,name,type,objecttypecode,formpresentation,formactivationstate,uniquename,description,versionnumber",mX={select:ak,required:["name","type","objecttypecode"]},hX="formid,name,type,objecttypecode",gX=2,yX={Main:gX,QuickView:6,QuickCreate:7,Card:11},sk=new WeakMap;function bX(e){return typeof e=="object"&&e!==null?sk.get(e):void 0}jn.readPrimaryCreateRefusal=bX;jn.formApi={async get(e,t){let n=(0,Pi.normalizeGuid)(t,"id"),r=`/systemforms(${n})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,Pi.odataQuery)([["$select",ak]]),i=(0,Nn.ensureSuccess)(await e.get(r),e.apiUrl(r));return(0,Qf.assertSystemFormRecordKind)(i.body,n,"form","fetch"),{raw:i.body,etag:(0,Nn.readEtag)(i)}},async list(e,t){var n;let r=!((n=t?.formTypes)===null||n===void 0)&&n.length?t.formTypes:["Main"],i=[...new Set(r.map(l=>yX[l]))],a=[i.length===1?`type eq ${i[0]}`:`(${i.map(l=>`type eq ${l}`).join(" or ")})`];t?.entityLogicalName&&a.push(`objecttypecode eq '${(0,Pi.odataLiteral)(t.entityLogicalName)}'`);let s=`/systemforms${(0,Pi.odataQuery)([["$select",hX],["$filter",a.join(" and ")]])}`;return(await(0,pX.collectPages)(e,s,"listArtifacts('form')")).map(l=>{var c,d;return{type:"form",id:(c=l.formid)!==null&&c!==void 0?c:"",name:(d=l.name)!==null&&d!==void 0?d:"",entityLogicalName:l.objecttypecode,isDirty:!1}})},async create(e,t,n,r=void 0){let i=ik(t);i!==void 0&&await uk(e,lE(i,"payload"),[],r);let o=(0,Nn.echoWrite)("formid"),a=`/systemforms${o.query}`,s=(0,Nn.withClientMintedId)(t,"formid",n),u=Object.freeze({...s});if(r){let c=n?(0,Pi.normalizeGuid)(n,"formid"):void 0;return r.reached({effects:[{componentName:"SystemForm",componentId:c,identity:"known",operation:"create"}],attemptsWrite:!0},c?()=>(0,Yf.existsByKey)(e,r,{collection:"/systemforms",key:"formid",id:c,componentName:"SystemForm"}):void 0)}let l=await(0,Nn.resendDeadlockVictim)(()=>e.post(a,{...u},o.options));try{(0,Nn.ensureSuccess)(l,e.apiUrl(a))}catch(c){throw typeof c=="object"&&c!==null&&sk.set(c,{status:l.status,sent:u,desiredId:n}),c}return{id:(0,Nn.resolveCreatedId)(l,"formid","form",n),etag:(0,Nn.readEtag)(l)}},async update(e,t,n,r,i=void 0,o,a){let s=(0,Pi.normalizeGuid)(t,"id"),u=ik(n);return u!==void 0&&await wX(e,s,u,r,a),(0,sE.patchSystemForm)(e,s,"form",n,r,mX,a)},readContentThenToken(e,t){return jn.formApi.get(e,t)},planPush(e,t,n){return(0,Yf.planPushThrough)(jn.formApi,e,t,n)},async delete(e,t){let n=(0,Pi.normalizeGuid)(t,"id");return await(0,Qf.assertSystemFormKind)(e,n,"form"),(0,Nn.deleteRecord)(e,"systemforms",n)}};var uE="DisplayConditions";async function vX(e,t,n){var r,i,o,a;if(n.everyone&&n.roleIds&&n.roleIds.length>0)throw new Ju.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,Pi.normalizeGuid)(t,"formId"),u=`/systemforms(${s})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,Pi.odataQuery)([["$select","formid,formxml,type"]]),l=(0,Nn.ensureSuccess)(await e.get(u),e.apiUrl(u));(0,Qf.assertSystemFormRecordKind)(l.body,s,"form","set the security roles of");let c=(0,Nn.readEtag)(l),d=l.body,f=d?.formxml;if(!f)throw new Ju.InvalidArgumentError(`form '${s}' returned no formxml, so its roles cannot be set`);let p=(0,aE.parseXmlRoot)(f,"<form/>"),m=p.ownerDocument;if(!m)throw new Ju.InvalidArgumentError(`form '${s}' produced no owner document`);let h=lk(p,uE),g=h?.hasAttribute("Order")&&(r=h.getAttribute("Order"))!==null&&r!==void 0?r:void 0,y=h?.getAttribute("FallbackForm")||void 0;h&&p.removeChild(h);let b=!!n.everyone||((o=(i=n.roleIds)===null||i===void 0?void 0:i.length)!==null&&o!==void 0?o:0)>0;if(!b&&(n.order!==void 0||n.fallbackForm!==void 0)){if(!h)throw new Ju.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.");n.order!==void 0&&h.setAttribute("Order",String(n.order)),n.fallbackForm!==void 0&&h.setAttribute("FallbackForm",String(n.fallbackForm)),p.appendChild(h)}else if(b){let T=m.createElement(uE),O=n.order!==void 0?String(n.order):g;O!==void 0&&T.setAttribute("Order",O);let v=n.fallbackForm!==void 0?String(n.fallbackForm):y??"false";if(T.setAttribute("FallbackForm",v),n.everyone)T.appendChild(m.createElement("Everyone"));else for(let N of(a=n.roleIds)!==null&&a!==void 0?a:[]){let S=m.createElement("Role");S.setAttribute("Id",`{${(0,Pi.normalizeGuid)(N,"roleId")}}`),T.appendChild(S)}p.appendChild(T)}let w=(0,aE.serializeNode)(p);await(0,sE.assertSystemFormContentUnchanged)(e,s,"form",u,c);let _=await(0,sE.readSystemFormRowEtag)(e,s),I=`/systemforms(${s})`;(0,Nn.ensureSuccess)(await e.patch(I,{formxml:w},{headers:{"Content-Type":"application/json","If-Match":(0,Nn.requireEtag)(_,"form",s)}}),e.apiUrl(I))}jn.setFormSecurityRoles=vX;function ik(e){let t=e?.formxml;return typeof t=="string"&&t.includes(ok.GENPAGE_CONTROL_NAME)?t:void 0}function lE(e,t){try{return(0,ok.activeEmbedBindings)(e)}catch(n){throw new Ju.SdkError(jn.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 (${n instanceof Error?n.message:String(n)}).`)}}async function uk(e,t,n,r){let i=new Set(n.map(([s,u])=>`${s}|${u}`)),o=t.filter(([s,u])=>!i.has(`${s}|${u}`)).map(([,s])=>s);if(o.length===0)return;let a=await(0,rk.findMissingGenPages)(e,o,"form generative-page preflight");if((0,rk.observeGenPageTargets)(r,o,a),a.length>0)throw new Ju.SdkError(jn.FORM_GENPAGE_TARGET_NOT_FOUND,`Refusing to push the form: it embeds generative page(s) ${a.map(s=>`'${s}'`).join(", ")} that do not exist in this environment. Push the page before the form that embeds it.`)}async function wX(e,t,n,r,i){var o;let a={guard:"contentToken",componentName:"SystemForm",componentId:t};i&&!(0,Nn.isVersionToken)(r)&&i.observe({...a,held:r,status:"missingHeld"}),(0,Nn.requireEtag)(r,"form",t);let s=`/systemforms(${t})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,Pi.odataQuery)([["$select","formid,formxml,type"]]),u;try{u=(0,Nn.ensureSuccess)(await e.get(s),e.apiUrl(s))}catch(f){throw i?.observe({...a,held:r,status:(0,Yf.failedReadStatus)(f),detail:(0,Yf.failureDetail)(f)}),f}(0,Qf.assertSystemFormRecordKind)(u.body,t,"form","write");let l=(0,Nn.readEtag)(u);if(i?.observe({...a,held:r,server:l,status:(0,Yf.compareTokens)(r,l)}),l===null||l!==r)throw new Ju.SdkError(Nn.VERSION_CONFLICT_CODE,`Version conflict writing form '${t}': its formxml changed on the server since it was read (held ${r}, server ${l??"(unreadable)"}). Re-fetch the form and re-apply the change.`);let c=(o=u.body)===null||o===void 0?void 0:o.formxml,d=typeof c=="string"&&c!==""?lE(c,"server"):[];await uk(e,lE(n,"payload"),d,i)}function lk(e,t){let n=e.childNodes;for(let r=0;r<n.length;r+=1){let i=n[r];if(i.nodeType===1&&i.tagName===t)return i}}async function EX(e,t){var n,r;let i=(0,Pi.normalizeGuid)(t,"formId"),o=`/systemforms(${i})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,Pi.odataQuery)([["$select","formid,formxml,type"]]),a=(0,Nn.ensureSuccess)(await e.get(o),e.apiUrl(o));(0,Qf.assertSystemFormRecordKind)(a.body,i,"form","read the security roles of");let s=(n=a.body)===null||n===void 0?void 0:n.formxml;if(!s)return;let u=(0,aE.parseXmlRoot)(s,"<form/>"),l=lk(u,uE);if(!l)return;let c=[],d=!1,f=l.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 y=(r=g.getAttribute("Id"))!==null&&r!==void 0?r:"";y&&c.push(y.replace(/[{}]/g,"").toLowerCase())}}let p=l.getAttribute("Order");return{...d?{everyone:!0}:{},...c.length>0?{roleIds:c}:{},fallbackForm:l.getAttribute("FallbackForm")==="true",...p!==null&&p!==""?{order:Number(p)}:{}}}jn.getFormSecurityRoles=EX});var hk=C(Gs=>{"use strict";Object.defineProperty(Gs,"__esModule",{value:!0});Gs.judgeBatchDependencies=Gs.previewArtifact=Gs.readTargetSolution=void 0;var AX=vc(),CX=mg(),SX=Vh(),hg=qi(),dE=Y(),NX=pe(),_X=Rs(),Vs=ae(),mk=["writePlan","concurrency","existence","createAnswer","deleteOfManaged","solution","managedSolutionTarget","batchDependency"],cE=new Set([CX.FORM_GENPAGE_TARGET_NOT_FOUND,AX.SITEMAP_TARGET_NOT_FOUND_CODE]),IX={[SX.GENPAGE_COMPONENT_NAME]:"genPage"},TX=new Set(["view","form","chart","dashboard","app"]),OX=/^1900-01-01T00:00:00/,DX=new Set(["different","goneOnServer","addedOnServer"]),PX=new Set(["missingHeld","missingServer","readFailed"]);async function RX(e,t){var n;let r=`/solutions${(0,Vs.odataQuery)([["$select","solutionid,ismanaged"],["$filter",`uniquename eq '${(0,Vs.odataLiteral)(t)}'`]])}`;try{let i=await e.get(r),o=(n=i.body)===null||n===void 0?void 0:n.value;if(i.status<200||i.status>=300||!Array.isArray(o))return{uniqueName:t,status:"unreadable",detail:`HTTP ${i.status}`};let a=o[0];return a?typeof a.solutionid!="string"?{uniqueName:t,status:"unreadable",detail:"the solution row carried no solutionid"}:{uniqueName:t,status:a.ismanaged===!0?"managed":"found",solutionId:(0,Vs.normalizeGuid)(a.solutionid,"solutionid")}:{uniqueName:t,status:"missing"}}catch(i){return{uniqueName:t,status:"unreadable",detail:(0,hg.failureDetail)(i)}}}Gs.readTargetSolution=RX;function ck(e){return!(e instanceof dE.SdkError)||e.code==="PREVIEW_WRITE_REFUSED"||e.code==="PREVIEW_PLAN_INCOMPLETE"}function dk(e){return{code:e.code,message:e.message,...e instanceof dE.ValidationError?{issues:e.issues}:{}}}function kX(e,t,n){if(e){if(!t)return"notEvaluated";switch(t.existence){case"absent":return"absent";case"present":return"exists";case"unread":return"unknown";default:return"notApplicable"}}let r=n.filter(i=>i.guard!=="dependency");return r.some(i=>DX.has(i.status))?"stale":r.some(i=>PX.has(i.status))?"unknown":t||r.length>0?"current":"notEvaluated"}async function $X(e,t,n){var r;let i=`/msdyn_componentlayers${(0,Vs.odataQuery)([["$select","msdyn_order,msdyn_solutionname,msdyn_publishername,msdyn_overwritetime"],["$filter",`(msdyn_componentid eq '${(0,Vs.normalizeGuid)(n,"componentId")}' and msdyn_solutioncomponentname eq '${(0,Vs.odataLiteral)(t)}')`]])}`,o;try{let s=await e.get(i);if(o=(r=s.body)===null||r===void 0?void 0:r.value,s.status<200||s.status>=300||!Array.isArray(o))return{failed:`HTTP ${s.status}`}}catch(s){return{failed:(0,hg.failureDetail)(s)}}let a=o.map(s=>{var u,l;let c=typeof s.msdyn_overwritetime=="string"?s.msdyn_overwritetime:void 0;return{order:Number(s.msdyn_order),solutionName:String((u=s.msdyn_solutionname)!==null&&u!==void 0?u:""),publisherName:String((l=s.msdyn_publishername)!==null&&l!==void 0?l:""),...c&&!OX.test(c)?{overwriteTime:c}:{}}}).sort((s,u)=>u.order-s.order);return a.length===0?{status:"empty"}:{status:"read",layers:a,hasManagedLayers:a.some(s=>s.solutionName!=="Active")}}async function LX(e,t,n){var r;let i=`/solutioncomponents${(0,Vs.odataQuery)([["$select","objectid"],["$filter",`_solutionid_value eq ${t} and (${n.map(o=>`objectid eq ${o}`).join(" or ")})`]])}`;try{let o=await e.get(i),a=(r=o.body)===null||r===void 0?void 0:r.value;return o.status<200||o.status>=300||!Array.isArray(a)?{failed:`HTTP ${o.status}`}:new Set(a.map(s=>typeof s.objectid=="string"?(0,Vs.normalizeGuid)(s.objectid,"objectid"):"").filter(s=>s!==""))}catch(o){return{failed:(0,hg.failureDetail)(o)}}}function fk(e){return e.status==="read"?e.layers.filter(t=>t.solutionName!=="Active").map(t=>t.solutionName).join(", "):""}async function MX(e){var t,n,r,i,o,a;let{type:s,id:u,reg:l,client:c,guard:d,meta:f}=e,p=d.gets,m=[],h=[],g=new Set,y=[],b=f===null,E=b?"create":e.localChanges.length>0?"update":"noChange",w;try{w=await e.prepare()}catch(M){if(ck(M))throw M;m.push(dk(M)),g.add("writePlan")}let _;if(w&&!l.api.planPush)g.add("writePlan");else if(w&&l.api.planPush)try{_=await l.api.planPush(c,{id:u,payload:w.payload,...f?{held:{etag:f.etag,memberEtags:f.memberEtags,siblingEtags:f.siblingEtags}}:{}},M=>y.push(M))}catch(M){if(ck(M))throw M;m.push(dk(M))}for(let M of(t=_?.warnings)!==null&&t!==void 0?t:[])h.push(M);let I=kX(b,_,y);for(let M of y)M.guard==="ifMatch"&&M.status==="different"?m.push({code:NX.VERSION_CONFLICT_CODE,message:`The push's write to ${M.componentName} '${M.componentId}' is conditioned on If-Match ${M.held}, but the row is now at ${M.server}: another writer changed it since it was read, and the platform refuses the write (412). Re-fetch and re-apply the change.`}):M.guard==="ifMatch"&&M.status==="goneOnServer"&&m.push({code:"CONNECTION_ERROR",message:`${M.componentName} '${M.componentId}' no longer exists on the server (a read of it answered 404): the push's conditional write to it fails. Re-fetch the artifact.`});I==="unknown"&&!b&&m.length===0&&g.add("concurrency");let T={verdict:I,observations:y};if(I==="stale")try{let M=await l.api.get(c,u),q=X=>{var ye,Ve,_e;return(_e=(Ve=(ye=l.adapter).baselineContent)===null||Ve===void 0?void 0:Ve.call(ye,X))!==null&&_e!==void 0?_e:X};T.remoteChanges=(0,_X.deepDiff)(q(f?.snapshot),q(l.adapter.fromApiResponse(M.raw)))}catch(M){if(M instanceof dE.SdkError&&M.code==="PREVIEW_WRITE_REFUSED")throw M;let q={code:"PREVIEW_REMOTE_CHANGES_UNAVAILABLE",message:`The server changed since the last fetch or push, but reading what changed failed: ${(0,hg.failureDetail)(M)}`};T.remoteChangesError=q,h.push(q)}let O=b&&_?.existence==="present";if(b&&_?.existence==="unread"&&g.add("existence"),O&&w)if(e.judgeAdoption){let M=await e.judgeAdoption(w.payload,w.json);"eligible"in M?(h.push({code:"PREVIEW_CREATE_ADOPTION_ELIGIBLE",message:`A record already exists at '${u}' and matches what this create would write: the push ADOPTS it if its create is answered 412, and reports ARTIFACT_ALREADY_EXISTS if it is answered 404 (both are measured platform answers to a replayed create).`}),g.add("createAnswer")):m.push({code:"ARTIFACT_ALREADY_EXISTS",message:e.alreadyExists(M.refused)})}else m.push({code:"ARTIFACT_ALREADY_EXISTS",message:e.alreadyExists()});let v=O?[]:(n=_?.effects)!==null&&n!==void 0?n:[],N=[],S=!1;for(let M of v){let q;if(M.operation==="create"||M.identity==="assignedAtWrite"||!M.componentId)q={status:"notRead",reason:"new"};else if(((r=e.options)===null||r===void 0?void 0:r.layers)===!1)q={status:"notRead",reason:"disabled"};else{let X=await $X(c,M.componentName,M.componentId);"failed"in X?(q={status:"notRead",reason:"failed"},h.push({code:"PREVIEW_READ_FAILED",message:`The solution layers of ${M.componentName} '${M.componentId}' could not be read: ${X.failed}`})):q=X}M.operation==="update"&&q.status==="read"&&q.hasManagedLayers&&h.push({code:"PREVIEW_LAYER_OVER_MANAGED",message:`This push saves an unmanaged change to ${M.componentName} '${M.componentId}', which carries managed layers from ${fk(q)}. Once published, the change sits in the Active (unmanaged) layer ABOVE them, masking their values for what it changes \u2014 later updates of those solutions do not show through for those values until the active customization is removed. Removing the solution that introduced a component removes the component with its unmanaged changes (measured where that solution was the component's only managed layer); removing a solution layered above another exposes the layer below instead. This lists layers; it does not compute which properties conflict.`}),M.operation==="delete"&&(q.status==="read"&&!q.hasManagedLayers||(S=!0,h.push({code:"PREVIEW_DELETE_OF_MANAGED",message:`This push DELETES ${M.componentName} '${M.componentId}', which is not proven unmanaged (`+(q.status==="read"?`managed layers from ${fk(q)}`:q.status==="empty"?"its layer read answered no rows":`its layers were not read: ${q.reason}`)+"). The platform refuses to delete a managed form (measured); for other components it was not measured."}))),N.push({componentName:M.componentName,...M.componentId?{componentId:M.componentId}:{},identity:M.identity,operation:M.operation,layers:q})}S&&g.add("deleteOfManaged");let R,x=await e.solution();if(x){let M=_?.attemptsWrite===!0;R={uniqueName:x.uniqueName,status:x.status,appliesToPush:M},M&&await xX(c,s,x,N,m,h,g)}let G=w?((i=l.publishesOnPush)===null||i===void 0?void 0:i.call(l,w.payload,b))===!0:!1,U=(o=l.publishScope)===null||o===void 0?void 0:o.call(l,u,(a=w?.json)!==null&&a!==void 0?a:e.json);return{type:s,id:u,action:E,outcome:m.length>0?"refused":g.size>0?"unknown":"ready",refusals:m,warnings:h,notEvaluated:mk.filter(M=>g.has(M)),localChanges:e.localChanges,concurrency:T,components:N,...R?{solution:R}:{},publish:{byPush:G,...U?{scope:U}:{}},requests:d.gets-p}}Gs.previewArtifact=MX;async function xX(e,t,n,r,i,o,a){var s;let u=r.filter(d=>d.operation!=="delete");if(n.status==="missing"){i.push({code:"PREVIEW_SOLUTION_NOT_FOUND",message:`The configured solution '${n.uniqueName}' does not exist, and the platform refuses every write that names it: the push fails with HTTP 404 0x80040217 (a ConnectionError \u2014 the push has no code of its own for it).`});return}if(n.status==="unreadable"){a.add("solution"),o.push({code:"PREVIEW_READ_FAILED",message:`The configured solution '${n.uniqueName}' could not be read: ${(s=n.detail)!==null&&s!==void 0?s:"unknown failure"}`});return}if(n.status==="managed"){let d=TX.has(t);if(o.push({code:"PREVIEW_SOLUTION_MANAGED",message:d?`The configured solution '${n.uniqueName}' is MANAGED: the push saves, and what it writes does not join that solution (measured for this kind).`:`The configured solution '${n.uniqueName}' is MANAGED, and what a push of this kind does then was not measured.`}),d)for(let f of u)f.joinsSolution=!1;else a.add("managedSolutionTarget");return}let l=u.filter(d=>d.operation==="update"&&d.componentId),c=l.length>0&&n.solutionId?await LX(e,n.solutionId,l.map(d=>d.componentId)):new Set;c instanceof Set||o.push({code:"PREVIEW_READ_FAILED",message:`The membership of the configured solution '${n.uniqueName}' could not be read: ${c.failed}`});for(let d of u)d.operation==="create"?d.joinsSolution=!0:c instanceof Set&&d.componentId&&(d.joinsSolution=!c.has(d.componentId))}function pk(e){return e.replace(/[{}]/g,"").toLowerCase()}function FX(e){e.forEach((t,n)=>{let r=t.concurrency.observations.filter(u=>u.guard==="dependency"&&u.status==="absent");if(r.length===0||!t.refusals.some(u=>cE.has(u.code)))return;let i=e.slice(0,n).filter(u=>u.action==="create"&&u.outcome!=="refused"),o=[];for(let u of r){let l=i.find(c=>c.type===IX[u.componentName]&&u.componentId!==void 0&&pk(c.id)===pk(u.componentId));if(!l)return;o.push(l)}let a=t.refusals.filter(u=>cE.has(u.code)).map(u=>u.code);t.refusals=t.refusals.filter(u=>!cE.has(u.code)),t.warnings.push({code:"PREVIEW_BATCH_DEPENDENCY",message:`This push needs ${r.map(u=>`${u.componentName} '${u.componentId}'`).join(", ")}, missing on the server now, which ${o.map(u=>`${u.type} '${u.id}' (${u.outcome})`).join(", ")} creates earlier in this batch. Its check for it, and every check after that, were not evaluated; if that create fails, this push is refused (${a.join(", ")}).`});let s=new Set([...t.notEvaluated,"writePlan","batchDependency"]);t.notEvaluated=mk.filter(u=>s.has(u)),t.outcome=t.refusals.length>0?"refused":"unknown"})}Gs.judgeBatchDependencies=FX});var wk=C($r=>{"use strict";Object.defineProperty($r,"__esModule",{value:!0});$r.findColumns=$r.findTables=$r.readCheckColumns=$r.readColumnHints=$r.fetchEntityMetadataFromApi=$r.COLUMN_DETAIL_VERSION=void 0;var bk=Ke(),vk=pe(),oi=ae();function ji(e){var t,n;return(n=(t=e?.UserLocalizedLabel)===null||t===void 0?void 0:t.Label)!==null&&n!==void 0?n:""}$r.COLUMN_DETAIL_VERSION=2;function fE(e){var t,n;return typeof((t=e?.UserLocalizedLabel)===null||t===void 0?void 0:t.Label)=="string"||((n=e?.LocalizedLabels)!==null&&n!==void 0?n:[]).some(r=>typeof r?.Label=="string")}function Yu(e){let t=e?.LocalizedLabels;if(!Array.isArray(t)||t.length<2)return;let n={};for(let r of t)typeof r?.LanguageCode=="number"&&typeof r.Label=="string"&&(n[r.LanguageCode]=r.Label);return Object.keys(n).length?n:void 0}async function gg(e,t){return(await bg(e,t)).rows}async function bg(e,t){var n,r;let i=await e.get(t);return i.status<200||i.status>=300?{rows:[],ok:!1}:{rows:(r=(n=i.body)===null||n===void 0?void 0:n.value)!==null&&r!==void 0?r:[],ok:!0}}function Ri(e){return`/EntityDefinitions(LogicalName='${(0,oi.odataPathLiteral)(e)}')`}async function UX(e,t,n){let r=await gg(e,`${Ri(t)}/Attributes/Microsoft.Dynamics.CRM.StringAttributeMetadata${(0,oi.odataQuery)([["$select","LogicalName,MaxLength"]])}`);for(let i of r){let o=n.get(i.LogicalName);o&&typeof i.MaxLength=="number"&&(o.maxLength=i.MaxLength)}}function qX(e){return`${Ri(e)}/Attributes/Microsoft.Dynamics.CRM.PicklistAttributeMetadata${(0,oi.odataQuery)([["$select","LogicalName"],["$expand","OptionSet($select=Options)"]])}`}async function BX(e,t){var n;let{rows:r}=await e;for(let i of r){let o=t.get(i.LogicalName);o&&(!((n=i.OptionSet)===null||n===void 0)&&n.Options)&&(o.options=i.OptionSet.Options.map(a=>{var s;return{value:(s=a.Value)!==null&&s!==void 0?s:0,label:ji(a.Label),...Yu(a.Label)?{localizedLabel:Yu(a.Label)}:{}}}))}}function pE(e){var t;return{value:(t=e.Value)!==null&&t!==void 0?t:0,label:ji(e.Label),...e.InvariantName?{invariantName:e.InvariantName}:{},...e.Color?{color:e.Color}:{}}}async function VX(e,t,n){var r;let i=c=>bg(e,c).catch(()=>({rows:[],ok:!1})),o=["MultiSelectPicklistAttributeMetadata","StateAttributeMetadata","StatusAttributeMetadata"],a=await Promise.all([n.catch(()=>({rows:[],ok:!1})),...o.map(c=>i(`${Ri(t)}/Attributes/Microsoft.Dynamics.CRM.${c}${(0,oi.odataQuery)([["$select","LogicalName"],["$expand","OptionSet($select=Options)"]])}`))]),s=new Map,u=!0;for(let{rows:c}of a)for(let d of c)!((r=d.OptionSet)===null||r===void 0)&&r.Options&&(u=u&&d.OptionSet.Options.every(f=>fE(f.Label)),s.set(d.LogicalName,d.OptionSet.Options.map(pE)));let l=await i(`${Ri(t)}/Attributes/Microsoft.Dynamics.CRM.BooleanAttributeMetadata${(0,oi.odataQuery)([["$select","LogicalName"],["$expand","OptionSet($select=TrueOption,FalseOption)"]])}`);for(let c of l.rows){let d=c.OptionSet;d?.TrueOption&&d.FalseOption&&(u=u&&fE(d.TrueOption.Label)&&fE(d.FalseOption.Label),s.set(c.LogicalName,[pE(d.FalseOption),pE(d.TrueOption)]))}return{byColumn:s,complete:u&&l.ok&&a.every(c=>c.ok)}}async function GX(e,t,n){let{rows:r,ok:i}=await bg(e,`${Ri(t)}/Attributes/Microsoft.Dynamics.CRM.LookupAttributeMetadata${(0,oi.odataQuery)([["$select","LogicalName,Targets"]])}`);for(let o of r){let a=n.get(o.LogicalName);a&&o.Targets&&(a.targets=o.Targets)}return i}function yg(e,t){return e<t?-1:e>t?1:0}var gk={OneToMany:0,ManyToOne:1,ManyToMany:2};function jX(e,t){return gk[e.type]-gk[t.type]||yg(e.schemaName,t.schemaName)||yg(e.relatedEntity,t.relatedEntity)||yg(e.relatedAttribute,t.relatedAttribute)}async function WX(e,t){var n,r,i,o;let a=[],s=await gg(e,`${Ri(t)}/OneToManyRelationships${(0,oi.odataQuery)([["$select","SchemaName,ReferencingEntity,ReferencingAttribute"]])}`);for(let c of s)a.push({schemaName:c.SchemaName,type:"OneToMany",relatedEntity:(n=c.ReferencingEntity)!==null&&n!==void 0?n:"",relatedAttribute:(r=c.ReferencingAttribute)!==null&&r!==void 0?r:""});let u=await gg(e,`${Ri(t)}/ManyToOneRelationships${(0,oi.odataQuery)([["$select","SchemaName,ReferencedEntity,ReferencedAttribute"]])}`);for(let c of u)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 l=await gg(e,`${Ri(t)}/ManyToManyRelationships${(0,oi.odataQuery)([["$select","SchemaName,Entity1LogicalName,Entity2LogicalName"]])}`);for(let c of l){let d=c.Entity1LogicalName===t?c.Entity2LogicalName:c.Entity1LogicalName;a.push({schemaName:c.SchemaName,type:"ManyToMany",relatedEntity:d??"",relatedAttribute:""})}return a.sort(jX)}async function zX(e,t){var n,r,i,o,a;let s=`${Ri(t)}`+(0,oi.odataQuery)([["$select","LogicalName,SchemaName,DisplayName,Description,EntitySetName,IsCustomEntity,PrimaryNameAttribute,PrimaryIdAttribute,PrimaryImageAttribute"],["$expand","Attributes($select=LogicalName,DisplayName,Description,AttributeType,AttributeTypeName,IsCustomAttribute,IsValidForUpdate,IsValidForRead,AttributeOf)"]]),l=(0,vk.ensureSuccess)(await e.get(s),e.apiUrl(s)).body,c=((n=l.Attributes)!==null&&n!==void 0?n:[]).map(g=>{var y,b,E;return{logicalName:g.LogicalName,displayName:ji(g.DisplayName),...Yu(g.DisplayName)?{localizedDisplayName:Yu(g.DisplayName)}:{},attributeType:(y=g.AttributeType)!==null&&y!==void 0?y:"Unknown",isCustomAttribute:!!g.IsCustomAttribute,attributeTypeName:(E=(b=g.AttributeTypeName)===null||b===void 0?void 0:b.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}:{},...ji(g.Description)?{description:ji(g.Description)}:{}}}).sort((g,y)=>yg(g.logicalName,y.logicalName)),d=new Map(c.map(g=>[g.logicalName,g])),f=bg(e,qX(t)),[,,p,m,h]=await Promise.all([UX(e,t,d),BX(f,d),VX(e,t,f),GX(e,t,d),WX(e,t)]);for(let g of c){let y=p.byColumn.get(g.logicalName);y&&(g.choices=y)}return{logicalName:l.LogicalName,schemaName:(r=l.SchemaName)!==null&&r!==void 0?r:l.LogicalName,displayName:ji(l.DisplayName),...Yu(l.DisplayName)?{localizedDisplayName:Yu(l.DisplayName)}:{},entitySetName:(i=l.EntitySetName)!==null&&i!==void 0?i:"",primaryNameAttribute:(o=l.PrimaryNameAttribute)!==null&&o!==void 0?o:"",primaryIdAttribute:(a=l.PrimaryIdAttribute)!==null&&a!==void 0?a:"",...l.PrimaryImageAttribute?{primaryImageAttribute:l.PrimaryImageAttribute}:{},isCustomEntity:!!l.IsCustomEntity,...ji(l.Description)?{description:ji(l.Description)}:{},columnDetailComplete:p.complete&&m,columnDetailVersion:$r.COLUMN_DETAIL_VERSION,attributes:c,relationships:h}}$r.fetchEntityMetadataFromApi=zX;var yk=40;async function mE(e,t,n,r){var i,o;let a=[...new Set(r.filter(u=>u!==""))],s=[];for(let u=0;u<a.length;u+=yk){let l=a.slice(u,u+yk).map(f=>`LogicalName eq '${(0,oi.odataLiteral)(f)}'`).join(" or "),c=t+(0,oi.odataQuery)([["$select",n],["$filter",l]]),d=(0,vk.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 HX(e,t,n){return(await mE(e,`${Ri(t)}/Attributes`,"LogicalName,AttributeType,DisplayName",n)).map(i=>{var o;let a=Yu(i.DisplayName);return{logicalName:i.LogicalName,displayName:ji(i.DisplayName),...a?{localizedDisplayName:a}:{},attributeType:(o=i.AttributeType)!==null&&o!==void 0?o:"Unknown"}})}$r.readColumnHints=HX;async function KX(e,t,n){let i=(await mE(e,`${Ri(t)}/Attributes`,"LogicalName,AttributeType,DisplayName,IsCustomAttribute",n)).map(s=>{var u;return{logicalName:s.LogicalName,displayName:ji(s.DisplayName),attributeType:(u=s.AttributeType)!==null&&u!==void 0?u:"Unknown",isCustomAttribute:!!s.IsCustomAttribute}}),o=new Map(i.filter(s=>s.attributeType==="String").map(s=>[s.logicalName,s])),a=await mE(e,`${Ri(t)}/Attributes/Microsoft.Dynamics.CRM.StringAttributeMetadata`,"LogicalName,MaxLength",[...o.keys()]);for(let s of a){let u=o.get(s.LogicalName);u&&typeof s.MaxLength=="number"&&(u.maxLength=s.MaxLength)}return i}$r.readCheckColumns=KX;async function JX(e,t,n){let r=`/EntityDefinitions${(0,oi.odataQuery)([["$select","LogicalName,SchemaName,EntitySetName,DisplayName,IsCustomEntity"]])}`,i=await(0,bk.collectPages)(e,r,"findTables"),o=(t??"").toLowerCase(),a=i.filter(s=>!n?.customOnly||s.IsCustomEntity).map(s=>{var u,l;return{logicalName:s.LogicalName,schemaName:(u=s.SchemaName)!==null&&u!==void 0?u:s.LogicalName,displayName:ji(s.DisplayName),entitySetName:(l=s.EntitySetName)!==null&&l!==void 0?l:"",isCustom:!!s.IsCustomEntity}}).filter(s=>s.logicalName.toLowerCase().includes(o)||s.schemaName.toLowerCase().includes(o)||s.displayName.toLowerCase().includes(o));return typeof n?.top=="number"?a.slice(0,n.top):a}$r.findTables=JX;async function YX(e,t,n,r){let i=`${Ri(t)}/Attributes`+(0,oi.odataQuery)([["$select","LogicalName,SchemaName,DisplayName,AttributeType,IsCustomAttribute"]]),o=await(0,bk.collectPages)(e,i,"findColumns"),a=(n??"").toLowerCase(),s=o.map(u=>{var l,c;return{logicalName:u.LogicalName,schemaName:(l=u.SchemaName)!==null&&l!==void 0?l:u.LogicalName,displayName:ji(u.DisplayName),attributeType:(c=u.AttributeType)!==null&&c!==void 0?c:"Unknown",isCustom:!!u.IsCustomAttribute}}).filter(u=>u.logicalName.toLowerCase().includes(a)||u.schemaName.toLowerCase().includes(a)||u.displayName.toLowerCase().includes(a));return typeof r?.top=="number"?s.slice(0,r.top):s}$r.findColumns=YX});var yE=C(ai=>{"use strict";Object.defineProperty(ai,"__esModule",{value:!0});ai.renderTypeRegistrations=ai.buildGenPageLegacyEnums=ai.renderGenPageAuthoringTypes=ai.buildGenPageRuntimeTypes=ai.toDesignerEntity=ai.TABLE_LOGICAL_NAME=void 0;ai.TABLE_LOGICAL_NAME=/^[a-z_][a-z0-9_]*$/;function hE(e){return e.replace(/[\r\n\u2028\u2029]+/g," ")}var QX=new Set(["createdby","createdon","createdonbehalfby","importsequencenumber","modifiedby","modifiedon","modifiedonbehalfby","overriddencreatedon","ownerid","owningbusinessunit","owningteam","owninguser","timezoneruleversionnumber","utcconversiontimezonecode","versionnumber"]);function vg(e){var t;return((t=e.attributeTypeName)!==null&&t!==void 0?t:"").replace(/Type$/,"").toLowerCase()}function Ck(e){var t,n;let r=e.choices;if(!r||r.length===0)return;let i=vg(e)==="boolean",o={};for(let a of r)o[a.value]={text:(n=(t=a.invariantName)!==null&&t!==void 0?t:a.label)!==null&&n!==void 0?n:"",value:a.value,...!i&&a.color?{color:a.color}:{}};return o}function Ek(e,t){return e.logicalName<t.logicalName?-1:e.logicalName>t.logicalName?1:0}function Sk(e){return!QX.has(e.logicalName)&&(!e.attributeOf||vg(e)==="image")&&e.isValidForRead!==!1}var Ak=new Set(["boolean","picklist","multiselectpicklist","state","status"]);function Nk(e){let t=e.primaryImageAttribute,n=new Set([e.primaryIdAttribute,e.primaryNameAttribute,t,t?`${t}_url`:void 0,"processid","statecode","statuscode"].filter(o=>!!o)),r=e.attributes.filter(o=>n.has(o.logicalName)).sort(Ek),i=e.attributes.filter(o=>!n.has(o.logicalName)).sort(Ek);return[...r,...i]}function gE(e){var t;let n=[],r=new Set,i=Nk(e);for(let o of i){let a=vg(o),s=a==="image";Sk(o)&&(s&&o.attributeOf&&r.add(o.attributeOf),n.push({AttributeTypeName:a,IsReadOnly:!o.isValidForUpdate,LogicalName:o.logicalName,OptionSet:Ck(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:n.filter(o=>!r.has(o.LogicalName))}}ai.toDesignerEntity=gE;function _k(e,t="None"){let n={};for(let r of e)n[r.logicalName]=gE(r);return Ok(n,t)}ai.buildGenPageRuntimeTypes=_k;var Ik=`export interface TableRegistrations extends BaseTableRegistrations {+`,Tk=`export interface EnumRegistrations extends BaseEnumRegistrations {+`;function XX(e,t){return e.length>0?_k(e,t).text:Pk(`${Ik}}+`,`${Tk}}+`,"","")}ai.renderGenPageAuthoringTypes=XX;function ZX(e){let t=new Set;for(let r of e)for(let i of gE(r).Attributes)Ak.has(i.AttributeTypeName)&&t.add(`${r.logicalName}_${i.LogicalName}`);let n=new Map;for(let r of e)for(let i of Nk(r)){let o=`${r.logicalName}_${i.logicalName}`,a=Ck(i);if(Sk(i)||!Ak.has(vg(i))||!a||t.has(o)||n.has(o))continue;let s={name:o,runtime:{},labels:new Map};n.set(o,{declaration:Dk(o,a,!1,s),model:s})}return n}ai.buildGenPageLegacyEnums=ZX;function Ok(e,t="None"){var n,r;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",u=Ik,l=Tk,c="",d="";for(let f of o){s&&f.Description&&(c+=`// ${hE(f.Description)}`),c+=`export type ${f.LogicalName} = TableRow<{// Primary Key Columnreadonly ${f.PrimaryIdAttribute}: string,-`,l+=` "${f.LogicalName}": ${f.LogicalName},-`;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+=PE(g,m.OptionSet,a,b),u+=` "${f.LogicalName}-${m.LogicalName}": ${g},+`,u+=` "${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=(n=p.Targets)!==null&&n!==void 0?n:p.AttributeTypeName==="customer"?["account","contact"]:void 0;if(!g||g.length===0){h=!1;break}m=` // Foreign Key Column+ ${p.IsReadOnly||g.every(b=>!e[b])?" readonly ":""}_${p.LogicalName}_value: `;let y="";for(let b of g)y+=`${y.length===0?"":" | "}\`/${b}(\${string})\``;m+=`${y},+`;break}case"boolean":case"picklist":case"multiselectpicklist":case"state":case"status":{let g=`${f.LogicalName}_${p.LogicalName}`;m+=`: ${g},+`;let y=(r=i.get(g))!==null&&r!==void 0?r:{name:g,runtime:{},labels:new Map};i.set(g,y),d+=Dk(g,p.OptionSet,a,y),l+=` "${f.LogicalName}-${p.LogicalName}": ${g},`;break}case"image":c+=` // This is an image encoded as a base64 string-`,p+=`: string,-`;break;default:h=!1}h&&(s&&m.Description&&(c+=` // ${eh(m.Description)}-`),a&&m.MaxLength&&(c+=" // Maximum length: "+m.MaxLength+`-`),c+=` ${p}`)}c+=`}>-`}return l+=`}-`,u+=`}-`,{text:RE(l,u,c,d),enums:i}}vr.renderTypeRegistrations=OE;function PE(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: ${eh(a.color)}+`,m+=`: string,+`;break;default:h=!1}h&&(s&&p.Description&&(c+=` // ${hE(p.Description)}+`),a&&p.MaxLength&&(c+=" // Maximum length: "+p.MaxLength+`+`),c+=` ${m}`)}c+=`}>+`}return u+=`}+`,l+=`}+`,{text:Pk(u,l,c,d),enums:i}}ai.renderTypeRegistrations=Ok;function Dk(e,t,n,r){var i;let o=`const enum ${e} {+`;for(let a of Object.values(t??{}))if(a){n&&(o+=`${a.color?`// Option Color: ${hE(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 RE(e,t,r,n){return`+`,r.runtime[a.text]=a.value,r.runtime[String(a.value)]=a.text;let s=(i=r.labels.get(a.text))!==null&&i!==void 0?i:[];s.includes(a.value)||s.push(a.value),r.labels.set(a.text,s)}return`${o}}+`}function Pk(e,t,n,r){return`// ---------------- Type Definitions which can be imported from ./RuntimeTypes -------------------------${e}${t}-${r}${n}+${r}/*** Possible scalar values of a data column in a data row.@@ -345,23 +362,10 @@ export interface GeneratedComponentProps {dataApi: UxAgentDataApi;pageInput?: PageInput;}-`}});var $E=v(Wc=>{"use strict";Object.defineProperty(Wc,"__esModule",{value:!0});Wc.generateGenPageRuntimeTypes=void 0;var LE=rh(),Uo=Q(),kE=new Set(["None","ColorsDefaultsConstraints","ColorsDefaultsConstraintsDescriptions"]),Bo="generateGenPageRuntimeTypes";async function IV(e,t,r){let n=OV(t),i=PV(r),o=[];for(let a of n){let s=await e(a);if(s.columnDetailComplete!==!0)throw new Uo.SdkError("GENPAGE_DATA_SOURCE_INCOMPLETE",`${Bo}: 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,LE.renderGenPageAuthoringTypes)(o,i)}Wc.generateGenPageRuntimeTypes=IV;function OV(e){if(!Array.isArray(e))throw new Uo.InvalidArgumentError(`${Bo}: dataSources must be an array of table logical names`);let t=new Set;for(let r of e){if(typeof r!="string"||!LE.TABLE_LOGICAL_NAME.test(r))throw new Uo.InvalidArgumentError(`${Bo}: a data source must be a table logical name (lowercase, e.g. 'account'), got '${String(r)}'`);if(t.has(r))throw new Uo.InvalidArgumentError(`${Bo}: data source '${r}' is listed twice; a page's dataSources hold each table once`);t.add(r)}return[...t]}function PV(e){if(e===void 0)return"None";if(e===null||typeof e!="object"||Array.isArray(e))throw new Uo.InvalidArgumentError(`${Bo}: options must be an object`);let t=Object.keys(e).filter(n=>n!=="detail");if(t.length>0)throw new Uo.InvalidArgumentError(`${Bo}: unknown option '${t[0]}' (the only option is 'detail')`);let r=e.detail===void 0?"None":e.detail;if(typeof r!="string"||!kE.has(r))throw new Uo.InvalidArgumentError(`${Bo}: detail must be one of ${[...kE].map(n=>`'${n}'`).join(", ")}, got '${String(r)}'`);return r}});var qE=v(qo=>{"use strict";Object.defineProperty(qo,"__esModule",{value:!0});qo.getEnvironmentLanguages=qo.ENVIRONMENT_LANGUAGES_UNREADABLE_CODE=void 0;var RV=Q(),ME=ye();qo.ENVIRONMENT_LANGUAGES_UNREADABLE_CODE="ENVIRONMENT_LANGUAGES_UNREADABLE";var xE="/organizations?$select=languagecode",kV="/RetrieveProvisionedLanguages()",LV="/RetrieveAvailableLanguages()";function UE(e,t){return new RV.SdkError(qo.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 BE(e){return typeof e=="number"&&Number.isInteger(e)&&e>0}async function FE(e,t,r,n){let i=(0,ME.ensureSuccess)(await e.get(t),e.apiUrl(t)).body,o=i?.[r];if(!Array.isArray(o)||o.length===0||!o.every(BE))throw UE(n,`answered no list of language codes in '${r}'`);return[...new Set(o)]}async function $V(e){var t;let r=(0,ME.ensureSuccess)(await e.get(xE),e.apiUrl(xE)).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(!BE(i))throw UE("the organization read","did not answer one row with a language code");let o=await FE(e,kV,"RetrieveProvisionedLanguages","RetrieveProvisionedLanguages"),a=await FE(e,LV,"LocaleIds","RetrieveAvailableLanguages");return{baseLanguage:i,available:a,provisioned:o}}qo.getEnvironmentLanguages=$V});var Tl=v(it=>{"use strict";Object.defineProperty(it,"__esModule",{value:!0});it.projectConnectorOperationSchema=it.projectConnectorOperations=it.validateConnectorSwagger=it.CONNECTOR_SCHEMA_TOO_LARGE_CODE=it.CONNECTOR_OPERATION_NOT_FOUND_CODE=it.CONNECTOR_SWAGGER_UNSUPPORTED_CODE=it.CONNECTIVITY_RESPONSE_UNREADABLE_CODE=void 0;var _l=Q();it.CONNECTIVITY_RESPONSE_UNREADABLE_CODE="CONNECTIVITY_RESPONSE_UNREADABLE";it.CONNECTOR_SWAGGER_UNSUPPORTED_CODE="CONNECTOR_SWAGGER_UNSUPPORTED";it.CONNECTOR_OPERATION_NOT_FOUND_CODE="CONNECTOR_OPERATION_NOT_FOUND";it.CONNECTOR_SCHEMA_TOO_LARGE_CODE="CONNECTOR_SCHEMA_TOO_LARGE";var VE=64,GE=128,WE=2e5,zE=4e6,xV=new Set(["get","put","post","delete","patch","head","options"]),FV=new Set(["query","header","path","formData","body"]);function Zr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function wn(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function At(e){return e===void 0?"absent":e===null?"null":Array.isArray(e)?"an array":`a ${typeof e}`}function Ze(e){return e.length>80?`'${e.slice(0,80)}\u2026'`:`'${e}'`}function Le(e,t){return new _l.SdkError(it.CONNECTIVITY_RESPONSE_UNREADABLE_CODE,`The connector's swagger could not be read: ${e} ${t}. Nothing was skipped or assumed in its place.`)}function eo(e,t){return new _l.SdkError(it.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 MV(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||!wn(r,i))return{found:!1};r=r[i]}return{found:!0,value:r}}function oh(e,t,r){if(!t.startsWith("#/"))throw eo(r,`has a $ref that is not a local '#/\u2026' pointer (${Ze(t)})`);if(t.includes("%"))throw eo(r,`has a $ref with a percent-encoded character (${Ze(t)}), which is not decoded`);if(/~(?![01])/.test(t))throw Le(r,`has a $ref with a malformed escape (${Ze(t)}): a '~' not followed by 0 or 1`);let n=MV(e,t);if(!n.found)throw Le(r,`has a $ref that does not resolve (${Ze(t)})`);return n.value}function zc(e,t){if(wn(e,"$ref")){if(typeof e.$ref!="string")throw Le(t,`has a $ref that is ${At(e.$ref)}, not a string`);return e.$ref}}function UV(e,t,r){if(!Zr(t))throw Le(r,`is ${At(t)}, not a parameter object`);let n=t,i=zc(t,r);if(i!==void 0){let s=oh(e,i,r);if(!Zr(s))throw Le(r,`has a $ref (${Ze(i)}) that resolves to ${At(s)}, not a parameter object`);if(zc(s,`${r} \u2192 ${Ze(i)}`)!==void 0)throw eo(r,`has a $ref (${Ze(i)}) to a parameter that is itself a $ref`);n=s}if(typeof n.name!="string")throw Le(r,"has no string name");let o=n.in;if(typeof o!="string"||!FV.has(o))throw Le(r,`has an in that is ${typeof o=="string"?Ze(o):At(o)}, not one of query, header, path, formData or body`);if(wn(n,"required")&&typeof n.required!="boolean")throw Le(r,`has a required that is ${At(n.required)}, not a boolean`);let a=n["x-ms-visibility"];if(wn(n,"x-ms-visibility")&&typeof a!="string")throw Le(r,`has an x-ms-visibility that is ${At(a)}, not a string`);return{name:n.name,in:o,required:n.required===!0,internal:a==="internal"}}function nh(e){return`${e.in}:${e.name}`}function HE(e,t,r){if(!wn(t,"parameters"))return[];let n=t.parameters;if(!Array.isArray(n))throw Le(r,`has parameters that are ${At(n)}, not an array`);let i=new Set;return n.map((o,a)=>{let s=`${r} parameters[${a}]`,l=UV(e,o,s),u=nh(l);if(i.has(u))throw Le(s,`repeats the parameter ${Ze(l.name)} in ${Ze(l.in)}, which must be unique in its list`);return i.add(u),l})}function KE(e,t,r){let n=t.responses;if(!wn(n,"200"))return;let i=`${r} response 200`,o=n[200];if(!Zr(o))throw Le(i,`is ${At(o)}, not a response object`);let a=o,s=zc(o,i);if(s!==void 0){if(s.startsWith("#/")&&!/^#\/responses\/[^/]+$/.test(s))throw Le(i,`has a $ref (${Ze(s)}) that does not name a response ('#/responses/<name>')`);let l=oh(e,s,i);if(!Zr(l))throw Le(i,`has a $ref (${Ze(s)}) that resolves to ${At(l)}, not a response object`);if(zc(l,`${i} \u2192 ${Ze(s)}`)!==void 0)throw eo(i,`has a $ref (${Ze(s)}) to a response that is itself a $ref`);a=l}if(wn(a,"content"))throw eo(i,"is an OpenAPI 3 response (it has content), not a Swagger 2.0 one");if(wn(a,"schema")){if(!Zr(a.schema))throw Le(i,`has a schema that is ${At(a.schema)}, not an object`);return a.schema}}function jE(e,t,r){if(!wn(e,t))return;let n=e[t];if(typeof n!="string")throw Le(r,`has a ${t} that is ${At(n)}, not a string`);return n}function BV(e,t,r,n,i){if(!Zr(t))throw Le(r,`is ${At(t)}, not an operation object`);let o=t.operationId;if(typeof o!="string")throw Le(r,`has no string operationId (${At(o)})`);if(n.has(o))throw Le(r,`repeats the operationId ${Ze(o)}, which must be unique in the document`);n.add(o);let a=jE(t,"summary",r),s=jE(t,"description",r),l=HE(e,t,r);if(!Zr(t.responses))throw Le(r,`has no responses object (${At(t.responses)})`);return KE(e,t,r),{id:o,summary:a,description:s,node:t,where:r,parameters:l,pathParameters:i}}function ah(e){if(!Zr(e))throw Le("the document",`is ${At(e)}, not an object`);if(wn(e,"openapi"))throw eo("the document","is OpenAPI 3 (it has an openapi member), not Swagger 2.0");if(!wn(e,"swagger"))throw Le("the document","names no Swagger version");if(e.swagger!=="2.0")throw eo("the document",`declares swagger ${Ze(String(e.swagger))}, not 2.0`);let t=e.paths;if(!Zr(t))throw Le("the document",`has paths that are ${At(t)}, not an object`);let r=[],n=new Set;for(let i of Object.keys(t)){let o=t[i],a=`paths[${Ze(i)}]`;if(!Zr(o))throw Le(a,`is ${At(o)}, not a path item object`);let s=[];for(let l of Object.keys(o))if(xV.has(l.toLowerCase()))r.push(BV(e,o[l],`${a}.${l}`,n,s));else if(l==="parameters")for(let u of HE(e,o,a))s.push(u);else if(!l.startsWith("x-"))throw eo(a,`has a ${Ze(l)} member; a path item may hold only HTTP methods, parameters and x- extensions`)}return{document:e,operations:r}}function qV(e){ah(e)}it.validateConnectorSwagger=qV;var ih=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 _l.SdkError(it.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>WE)throw this.tooLarge(`more than ${WE} nodes`)}text(t){if(this.characters+=t,this.characters>zE)throw this.tooLarge(`more than ${zE} characters of strings and keys`)}checkDepth(t){if(t>GE)throw this.tooLarge(`nesting deeper than ${GE} 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(Zr(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>=VE)throw this.tooLarge(`a $ref chain of more than ${VE} references`);let n=oh(this.root,t,this.where);if(!Zr(n))throw Le(this.where,`has a schema $ref (${Ze(t)}) that resolves to ${At(n)}, not a schema object`);this.path.push(t);let i=this.visit(n,r);return this.path.pop(),i}};function VV(e){let{operations:t}=ah(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}})}}it.projectConnectorOperations=VV;function GV(e,t){if(typeof t!="string"||t==="")throw new _l.InvalidArgumentError("operationId must be a non-empty string.");let{document:r,operations:n}=ah(e),i=n.find(u=>u.id===t);if(!i)throw new _l.SdkError(it.CONNECTOR_OPERATION_NOT_FOUND_CODE,`The connector has no operation with the id ${Ze(t)} (ids are matched exactly, case included). List the connector\u2019s operations to see its ids.`);let o=new Set(i.parameters.map(nh)),a=[...i.parameters,...i.pathParameters.filter(u=>!o.has(nh(u)))].filter(u=>!u.internal).map(({name:u,required:c})=>({name:u,required:c})),s=KE(r,i.node,i.where),l=s===void 0?{}:new ih(r,`${i.where} (${Ze(i.id)})`).run(s);return{operation:i.id,parameters:a,response:l}}it.projectConnectorOperationSchema=GV});var Vo=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 Dl=Q(),WV=ye(),zV=Tl();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 wr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}J.isObject=wr;function Ga(e){return e===void 0?"absent":e===null?"null":Array.isArray(e)?"an array":`a ${typeof e}`}J.kindOf=Ga;function Wa(e,t=200){return e.length>t?`${e.slice(0,t)}\u2026`:e}J.bounded=Wa;function YE(e){try{let t=new URL(e);return{protocol:t.protocol,host:t.host,origin:t.origin}}catch{return}}J.parseUrl=YE;function jV(e,t){return e.protocol===t.protocol&&e.host.toLowerCase()===t.host.toLowerCase()}J.sameOrigin=jV;var HV=/^[a-z0-9-]+\.crm(\d*)\.dynamics\.com$/,KV=/^[a-z0-9-]+\.crmtest\.dynamics\.com$/;function JV(e){let t=YE(e),r=t?t.host.toLowerCase():"";if(KV.test(r))return"Test";let n=HV.exec(r);return n&&n[1]!=="9"?"Public":"Unsupported"}J.connectivityCloudOf=JV;function Gn(e,t){return new Dl.SdkError(zV.CONNECTIVITY_RESPONSE_UNREADABLE_CODE,`${e} could not be read: ${t}. Nothing was skipped or assumed in its place.`)}J.unreadable=Gn;function YV(e){return encodeURIComponent(`environment eq '${e.replace(/'/g,"''")}'`)}J.environmentFilter=YV;function QV(e){if(typeof e=="string"&&e.length>0)return Wa(e,500);if(wr(e)){let t=wr(e.error)?e.error.message:void 0;for(let r of[t,e.Message,e.message])if(typeof r=="string")return Wa(r,500)}return"request failed"}J.messageOf=QV;function QE(e){return wr(e)&&wr(e.error)?e.error.code:void 0}J.errorCodeOf=QE;function XV(e){if(wr(e)&&wr(e.error)&&wr(e.error.innererror))return e.error.innererror.code}function ZV(e,t,r){let n=[],i=QE(t);typeof i=="string"&&i.length>0&&n.push(Wa(i,80));let o=XV(t);typeof o=="string"&&o.length>0&&n.push(Wa(o,80));let a=n.length>0?` (${n.join("; ")})`:"";return(0,Dl.attachCause)(new Dl.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=ZV;J.CONNECTOR_PREFIX="/providers/Microsoft.PowerApps/apis/";var e4=/^[A-Za-z0-9_.-]{1,128}$/,t4=new Set(["shared_logicflows","shared_powerflows","shared_pqogenericconnector"]);function r4(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(e4.test(r)&&!/^\.{1,2}$/.test(r))return r}throw new Dl.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"?`'${Wa(e,80)}'`:Ga(e)}.`)}J.connectorShortName=r4;function n4(e,t,r){let n=`Connection row ${t}`;if(!wr(e))throw Gn(n,`it is ${Ga(e)}, not an object`);let i=e.properties;if(!wr(i))throw Gn(n,`its properties are ${Ga(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 Gn(n,`its apiId is not '${J.CONNECTOR_PREFIX}<connector>'`);let a=o.slice(J.CONNECTOR_PREFIX.length);if(a===""||a.includes("/"))throw Gn(n,"its apiId names no single connector");if(t4.has(a.toLowerCase()))return;let s=e.name;if(typeof s!="string"||s==="")throw Gn(n,"it has no name");let l=i.environment,u=wr(l)?l.name:void 0;if(typeof u!="string"||u.toLowerCase()!==r.toLowerCase())throw Gn(n,"it is not a connection of this environment (properties.environment.name)");let c=i.displayName;if(typeof c!="string")throw Gn(n,`its displayName is ${Ga(c)}, not a string`);let d=i.statuses;if(!Array.isArray(d))throw Gn(n,`its statuses are ${Ga(d)}, not an array`);return{connectionId:s,displayName:c,connectorId:o,connectorName:a,statuses:d.map(f=>{let m=wr(f)?f.status:void 0;if(typeof m!="string")throw Gn(n,"one of its statuses has no string status");return m})}}J.readConnection=n4;var JE="/RetrieveCurrentOrganization(AccessType=@p1)?@p1=Microsoft.Dynamics.CRM.EndpointAccessType'Default'";async function i4(e){let t=(0,WV.ensureSuccess)(await e.get(JE),e.apiUrl(JE)).body,r=wr(t)?t.Detail:void 0,n=wr(r)?r.EnvironmentId:void 0;if(typeof n!="string"||n==="")throw new Dl.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=i4});var iA=v(Cr=>{"use strict";Object.defineProperty(Cr,"__esModule",{value:!0});Cr.ConnectivityApi=Cr.CONNECTIVITY_UNAUTHORIZED_CODE=Cr.CONNECTIVITY_ROUTE_DECOMMISSIONED_CODE=Cr.CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE=Cr.CONNECTIVITY_CLOUD_UNSUPPORTED_CODE=Cr.CONNECTIVITY_NOT_CONFIGURED_CODE=void 0;var zt=Q(),o4=ye(),Hc=Tl(),Ol=Vo(),Pl=Vo();Object.defineProperty(Cr,"CONNECTIVITY_NOT_CONFIGURED_CODE",{enumerable:!0,get:function(){return Pl.CONNECTIVITY_NOT_CONFIGURED_CODE}});Object.defineProperty(Cr,"CONNECTIVITY_CLOUD_UNSUPPORTED_CODE",{enumerable:!0,get:function(){return Pl.CONNECTIVITY_CLOUD_UNSUPPORTED_CODE}});Object.defineProperty(Cr,"CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE",{enumerable:!0,get:function(){return Pl.CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE}});Object.defineProperty(Cr,"CONNECTIVITY_ROUTE_DECOMMISSIONED_CODE",{enumerable:!0,get:function(){return Pl.CONNECTIVITY_ROUTE_DECOMMISSIONED_CODE}});Object.defineProperty(Cr,"CONNECTIVITY_UNAUTHORIZED_CODE",{enumerable:!0,get:function(){return Pl.CONNECTIVITY_UNAUTHORIZED_CODE}});var XE="2016-11-01",a4="2021-04-01",s4="https://api.bap.microsoft.com",l4="https://test.api.bap.microsoft.com",u4=/^[a-z0-9-]+\.crm(\d*)\.dynamics\.com$/,c4=/^[a-z0-9-]+\.crmtest\.dynamics\.com$/,ZE="/RetrieveCurrentOrganization(AccessType=@p1)?@p1=Microsoft.Dynamics.CRM.EndpointAccessType'Default'",vi="/providers/Microsoft.PowerApps/apis/",d4=/^[A-Za-z0-9_.-]{1,128}$/,f4=new Set(["shared_logicflows","shared_powerflows","shared_pqogenericconnector"]),p4="ServiceDecommissioned";function ft(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function to(e){return e===void 0?"absent":e===null?"null":Array.isArray(e)?"an array":`a ${typeof e}`}function Wn(e,t=200){return e.length>t?`${e.slice(0,t)}\u2026`:e}function Il(e){try{let t=new URL(e);return{protocol:t.protocol,host:t.host,origin:t.origin}}catch{return}}function eA(e,t){return e.protocol===t.protocol&&e.host.toLowerCase()===t.host.toLowerCase()}function m4(e){return/^[a-z0-9][a-z0-9.-]*$/.test(e)&&(e==="api.powerapps.com"||e.endsWith(".api.powerapps.com"))}function en(e,t){return new zt.SdkError(Hc.CONNECTIVITY_RESPONSE_UNREADABLE_CODE,`${e} could not be read: ${t}. Nothing was skipped or assumed in its place.`)}function jc(e){return new zt.SdkError(Ol.CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE,`The environment of this org could not be verified: ${e}. The Power Apps service was not asked about it.`)}function tA(e){return encodeURIComponent(`environment eq '${e.replace(/'/g,"''")}'`)}function rA(e){if(typeof e=="string"&&e.length>0)return Wn(e,500);if(ft(e)){let t=ft(e.error)?e.error.message:void 0;for(let r of[t,e.Message,e.message])if(typeof r=="string")return Wn(r,500)}return"request failed"}function h4(e){return ft(e)&&ft(e.error)?e.error.code:void 0}function nA(e){if(typeof e=="string"){let r=e.slice(0,vi.length).toLowerCase()===vi.toLowerCase()?e.slice(vi.length):e;if(d4.test(r)&&!/^\.{1,2}$/.test(r))return r}throw new zt.InvalidArgumentError(`connector must be a connector's short name ('shared_office365users') or its full API id ('${vi}shared_office365users'); got ${typeof e=="string"?`'${Wn(e,80)}'`:to(e)}.`)}function g4(e,t,r){let n=`Connection row ${t}`;if(!ft(e))throw en(n,`it is ${to(e)}, not an object`);let i=e.properties;if(!ft(i))throw en(n,`its properties are ${to(i)}, not an object`);let o=i.apiId;if(typeof o!="string"||o.slice(0,vi.length).toLowerCase()!==vi.toLowerCase())throw en(n,`its apiId is not '${vi}<connector>'`);let a=o.slice(vi.length);if(a===""||a.includes("/"))throw en(n,"its apiId names no single connector");if(f4.has(a.toLowerCase()))return;let s=e.name;if(typeof s!="string"||s==="")throw en(n,"it has no name");let l=i.environment,u=ft(l)?l.name:void 0;if(typeof u!="string"||u.toLowerCase()!==r.toLowerCase())throw en(n,"it is not a connection of this environment (properties.environment.name)");let c=i.displayName;if(typeof c!="string")throw en(n,`its displayName is ${to(c)}, not a string`);let d=i.statuses;if(!Array.isArray(d))throw en(n,`its statuses are ${to(d)}, not an array`);return{connectionId:s,displayName:c,connectorId:o,connectorName:a,statuses:d.map(f=>{let m=ft(f)?f.status:void 0;if(typeof m!="string")throw en(n,"one of its statuses has no string status");return m})}}var sh=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=${tA(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 en(u,`its value is ${to(d)}, not an array`);for(let m of d){let p=g4(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 en(u,`its nextLink is ${f===""?"an empty string":to(f)}, not a non-empty string`);if(i.has(f))throw new zt.InvalidArgumentError(`listConnections: aborting pagination \u2014 the server returned a repeated nextLink ('${Wn(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=nA(t);return(0,Hc.projectConnectorOperations)(await this.swagger(r,n))}async getConnectorOperationSchema(t,r){let n=this.requireService(),i=nA(t);if(typeof r!="string"||r==="")throw new zt.InvalidArgumentError("operationId must be a non-empty string.");return(0,Hc.projectConnectorOperationSchema)(await this.swagger(n,i),r)}requireService(){if(!this.service)throw new zt.SdkError(Ol.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=${a4}`,o=(await this.send(t,i,!1)).body,a=ft(o)?o.properties:void 0,s=ft(o)?o.name:void 0;if(typeof s!="string"||s.toLowerCase()!==n.toLowerCase())throw jc(`BAP's environment row is not the one named '${Wn(n,80)}' (its name)`);let l=ft(a)&&ft(a.linkedEnvironmentMetadata)?a.linkedEnvironmentMetadata.instanceUrl:void 0,u=typeof l=="string"?Il(l):void 0,c=Il(this.instanceUrl);if(!u||!c||!eA(u,c))throw jc("BAP's row is not linked to this org (its linkedEnvironmentMetadata.instanceUrl is another origin)");let d=ft(a)?a.runtimeEndpoints:void 0,f=ft(d)?d["microsoft.PowerApps"]:void 0,m=typeof f=="string"?Il(f):void 0;if(!m||m.protocol!=="https:"||!m4(m.host.toLowerCase()))throw jc("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=Il(this.instanceUrl),r=t?t.host.toLowerCase():"",n=u4.exec(r);if(n&&n[1]!=="9")return s4;if(c4.test(r))return l4;throw new zt.SdkError(Ol.CONNECTIVITY_CLOUD_UNSUPPORTED_CODE,`The org's host is not one of the clouds this reads in (${t?`'${Wn(t.host,80)}'`:`'${Wn(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,o4.ensureSuccess)(await this.org.get(ZE),this.org.apiUrl(ZE)).body,r=ft(t)?t.Detail:void 0,n=ft(r)?r.EnvironmentId:void 0;if(typeof n!="string"||n==="")throw jc("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}${vi}${i}?api-version=${XE}&$filter=${tA(n.id)}`,a=(await this.send(t,o,!0)).body,s=ft(a)?a.properties:void 0,l=ft(s)?s.swagger:void 0;if(!ft(l))throw en(`The connector '${Wn(r,80)}'`,`its properties.swagger is ${to(l)}, not an object`);return(0,Hc.validateConnectorSwagger)(l),l}assertSameOrigin(t,r){let n=Il(t);if(!n)throw new zt.InvalidArgumentError(`Refusing to follow a malformed absolute URL: '${Wn(t)}'`);if(!eA(n,r))throw new zt.InvalidArgumentError(`Refusing to follow a cross-origin link ('${Wn(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 zt.ConnectionError&&typeof o.statusCode=="number"&&o.statusCode>0?this.mapNon2xx(r,o.statusCode,void 0,n,o):o instanceof zt.SdkError?o:new zt.ConnectionError(r,0,o instanceof Error?o.message:String(o),o)}if(!i||typeof i.status!="number")throw new zt.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 zt.ConnectionError(t,r,rA(n),n);return i&&r===410&&h4(n)===p4?(0,zt.attachCause)(new zt.SdkError(Ol.CONNECTIVITY_ROUTE_DECOMMISSIONED_CODE,`The Power Apps API this reads through is decommissioned for this environment: ${rA(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,Ol.connectivityUnauthorized)(r,n,a):a}};Cr.ConnectivityApi=sh});var fh=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 Go=Q(),M=Vo(),y4=/^[A-Za-z0-9_.-]{1,128}$/,Wo=/^\.{1,2}$/,b4="shared_sharepointonline",v4=/^[0-9]{1,9}$/,w4=/^[A-Za-z0-9._~-]+$/,C4=/^\/apim\/([A-Za-z0-9._-]+)\/?$/,E4=/^\/connectors\/runtime\/invoke\/scalegroups\/([A-Za-z0-9._-]+)\/(scaleunits|shards)\/([A-Za-z0-9._-]+)\/apis\/([A-Za-z0-9._-]+)\/connections\/?$/,A4=/^[A-Za-z0-9._~!'()*-]$/,S4=/^[0-9A-Fa-f]{2}$/;function wi(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Rl(e){return typeof e=="string"?`'${(0,M.bounded)(e,80)}'`:(0,M.kindOf)(e)}function lh(e,t){return new Go.SdkError(M.CONNECTOR_NOT_TABULAR_CODE,`The connector '${(0,M.bounded)(e,80)}' has no tables: ${t}.`)}function Kc(e,t){return new Go.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 N4(e){if(typeof e=="string"&&y4.test(e)&&!Wo.test(e))return e;throw new Go.InvalidArgumentError(`connectionId must be a connection's name (letters, digits, '_', '.', '-'; at most 128; not '.' or '..'); got ${Rl(e)}.`)}function _4(e){if(e!=null){if(typeof e=="string"&&e!==""&&e.split(",").find(r=>r===""||Wo.test(r))===void 0)return e;throw new Go.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 ${Rl(e)}.`)}}function T4(e){if(typeof e=="string"&&e!==""&&!Wo.test(e))return e;throw new Go.InvalidArgumentError(`table must be a non-empty string other than '.' and '..'; got ${Rl(e)}.`)}function aA(e,t,r){return{short:(0,M.connectorShortName)(e),connectionId:N4(t),dataset:_4(r)}}Me.checkListTablesArguments=aA;function D4(e,t,r,n){return{...aA(e,t,r),table:T4(n)}}Me.checkTableSchemaArguments=D4;function I4(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(!wi(n,"interfaces"))throw lh(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(!wi(i,"CDPTabular1"))throw lh(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(!v4.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=O4(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 lh(t,"its CDPTabular1 interface has no Production revision");return s.revision}Me.tabularRevision=I4;function O4(e){if(typeof e!="string")return;let t=e.replace(/^\/+/,"").replace(/\/+$/,"");return t===""?"":t.split("/").every(i=>w4.test(i)&&!Wo.test(i))?t:void 0}function P4(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 Kc(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 Kc(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:C4.exec(l);if(!c||Wo.test(c[1]))throw Kc(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:E4.exec(l);if(!u||[u[1],u[3],u[4]].some(c=>Wo.test(c)))throw Kc(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=P4;function R4(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 ${Rl(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 ${Rl(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=R4;function oA(e){return encodeURIComponent(e).replace(/[!'()*]/g,t=>`%${t.charCodeAt(0).toString(16).toUpperCase()}`)}function k4(e){if(e==="")return!1;for(let t=0;t<e.length;t+=1)if(e[t]==="%"){if(!S4.test(e.slice(t+1,t+3)))return!1;t+=2}else if(!A4.test(e[t]))return!1;return!0}function sA(e,t){let r,n,i;try{r=oA(e),n=oA(r),i=decodeURIComponent(n)}catch{throw new Go.InvalidArgumentError(`${t} is not well-formed Unicode (it has a lone surrogate), so it cannot be sent.`)}if(!k4(n)||Wo.test(n)||i!==r)throw new Go.InvalidArgumentError(`${t} cannot be sent as one path segment.`);return n}function dh(e){return e.split(",").map((t,r)=>sA(t,`dataset part ${r}`)).join(",")}Me.encodeDataset=dh;function lA(e){return sA(e,"table")}Me.encodeTable=lA;function L4(e,t){if(t===void 0)return"/tables";let r=e.toLowerCase()===b4?"allTables":"tables";return`/datasets/${dh(t)}/${r}`}Me.tablesSuffix=L4;function $4(e,t){return`/$metadata.json${e===void 0?"":`/datasets/${dh(e)}`}/tables/${lA(t)}`}Me.tableSchemaSuffix=$4;function za(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 x4(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(za(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=za(e,"value"),i=n.found?n:za(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)=>F4(n,i))}}Me.projectConnectorTables=x4;function F4(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=za(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=za(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=za(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 uh(e,t,r){if(!wi(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 ch(e,t,r){if(!wi(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 M4(e,t){var r,n;if(wi(e,"$ref"))throw(0,M.unreadable)(t,"it is a $ref, whose type is not guessed");let i=ch(e,"type",t),o=ch(e,"format",t),a=(r=i??o)!==null&&r!==void 0?r:"object";if(!wi(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(wi(s,"$ref"))throw(0,M.unreadable)(t,"its items are a $ref, whose type is not guessed");return`${a}<${(n=ch(s,"type",`${t} items`))!==null&&n!==void 0?n:"object"}>`}function U4(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=uh(e,"items","items"),i=uh(e,"schema","schema"),o=i?uh(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&&wi(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&&wi(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:M4(f,d),required:s.has(c.toLowerCase())}});return{table:t,columns:u}}Me.projectConnectorTableSchema=U4});var uA=v(Jc=>{"use strict";Object.defineProperty(Jc,"__esModule",{value:!0});Jc.PowerPlatformApiDiscovery=void 0;var ph=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}`)}}};Jc.PowerPlatformApiDiscovery=ph});var cA=v(Yc=>{"use strict";Object.defineProperty(Yc,"__esModule",{value:!0});Yc.PowerPlatformApiDiscovery=void 0;var B4=uA();Object.defineProperty(Yc,"PowerPlatformApiDiscovery",{enumerable:!0,get:function(){return B4.PowerPlatformApiDiscovery}})});var mA=v(ro=>{"use strict";Object.defineProperty(ro,"__esModule",{value:!0});ro.platformTokenAudience=ro.platformEnvironment=ro.platformClusterOf=void 0;var dA=cA(),fA=Q(),pA=Vo(),q4=/^[a-z0-9-]+\.crm(\d*)\.dynamics\.com$/,V4=/^[a-z0-9-]+\.crmtest\.dynamics\.com$/,G4=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,W4=/^default-/i;function mh(e,t=80){return e.length>t?`${e.slice(0,t)}\u2026`:e}function z4(e){try{return new URL(e).host.toLowerCase()}catch{return}}function j4(e){let t=z4(e);if(t){if(V4.test(t))return{cloud:"Test",category:"test"};let r=q4.exec(t);if(r&&r[1]!=="9")return{cloud:"Public",category:"prod"}}throw new fA.SdkError(pA.CONNECTIVITY_CLOUD_UNSUPPORTED_CODE,`The Power Platform API route is built for the Test and Public clouds; this org (${t?`'${mh(t)}'`:`'${mh(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.`)}ro.platformClusterOf=j4;function H4(e,t){let r=W4.test(e)?e.slice(8):e;if(!G4.test(r))throw new fA.SdkError(pA.CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE,`The environment of this org could not be verified: its name ('${mh(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 dA.PowerPlatformApiDiscovery(t).getEnvironmentEndpoint(e)}`,guid:r.toLowerCase()}}ro.platformEnvironment=H4;function K4(e){return new dA.PowerPlatformApiDiscovery(e).getTokenAudience()}ro.platformTokenAudience=K4});var gA=v(ja=>{"use strict";Object.defineProperty(ja,"__esModule",{value:!0});ja.PlatformConnectivityApi=ja.assertTabularCloud=void 0;var Cn=Q(),hh=Tl(),me=Vo(),hA=mA(),Ci=fh(),gh="1";function yh(e){let t=(0,me.connectivityCloudOf)(e);if(t!=="Test"&&t!=="Public")throw new Cn.SdkError(me.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.")}ja.assertTabularCloud=yh;var bh=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=${gh}`,[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,me.unreadable)(s,`its value is ${(0,me.kindOf)(u)}, not an array`);for(let d of u){let f=(0,me.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,me.unreadable)(s,`its nextLink is ${c===""?"an empty string":(0,me.kindOf)(c)}, not a non-empty string`);if(n.has(c))throw new Cn.InvalidArgumentError(`listConnections: aborting pagination \u2014 the server returned a repeated nextLink ('${(0,me.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,me.connectorShortName)(t);return(0,hh.projectConnectorOperations)(await this.swagger(r))}async getConnectorOperationSchema(t,r){let n=(0,me.connectorShortName)(t);if(typeof r!="string"||r==="")throw new Cn.InvalidArgumentError("operationId must be a non-empty string.");return(0,hh.projectConnectorOperationSchema)(await this.swagger(n),r)}async listConnectorTables(t,r,n){yh(this.instanceUrl);let i=(0,Ci.checkListTablesArguments)(t,r,n),o=(0,Ci.tablesSuffix)(i.short,i.dataset);return(0,Ci.projectConnectorTables)(await this.invokeTabular(i,o))}async getConnectorTableSchema(t,r,n,i){yh(this.instanceUrl);let o=(0,Ci.checkTableSchemaArguments)(t,r,n,i),a=(0,Ci.tableSchemaSuffix)(o.dataset,o.table);return(0,Ci.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,Ci.tabularRevision)(o,t.short),s=(0,Ci.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,me.environmentFilter)(i.name)}&api-version=${gh}`,u=(await this.send(this.client,"GET",l,[401,403])).body,c=(0,Ci.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 Cn.SdkError(me.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,hA.platformClusterOf)(this.instanceUrl),n=await(0,me.readEnvironmentName)(this.org),{origin:i,guid:o}=(0,hA.platformEnvironment)(n,r),a=(0,me.parseUrl)(i);if(!a)throw(0,me.unreadable)("The Power Platform API origin",`'${(0,me.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,me.environmentFilter)(r.name)}&api-version=${gh}`,i=(await this.send(this.client,"GET",n,[401,403])).body,o=(0,me.isObject)(i)?i.name:void 0;if(!(0,me.isObject)(i)||typeof o!="string"||o.toLowerCase()!==t.toLowerCase())throw(0,me.unreadable)(`The connector '${(0,me.bounded)(t,80)}'`,`the record's name is ${typeof o=="string"?`'${(0,me.bounded)(o,80)}'`:(0,me.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,me.isObject)(n)?n.swagger:void 0;if(!(0,me.isObject)(i))throw(0,me.unreadable)(`The connector '${(0,me.bounded)(t,80)}'`,`its properties.swagger is ${(0,me.kindOf)(i)}, not an object`);return(0,hh.validateConnectorSwagger)(i),i})}assertSameOrigin(t,r){let n=(0,me.parseUrl)(t);if(!n)throw new Cn.InvalidArgumentError(`Refusing to follow a malformed absolute URL: '${(0,me.bounded)(t)}'`);if(!(0,me.sameOrigin)(n,r))throw new Cn.InvalidArgumentError(`Refusing to follow a cross-origin link ('${(0,me.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 Cn.ConnectionError&&typeof s.statusCode=="number"&&s.statusCode>0?this.non2xx(n,s.statusCode,void 0,i,s):s instanceof Cn.SdkError?s:new Cn.ConnectionError(n,0,s instanceof Error?s.message:String(s),s)}if(!a||typeof a.status!="number")throw new Cn.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 Cn.ConnectionError(t,r,(0,me.messageOf)(n),n);return i.includes(r)?(0,me.connectivityUnauthorized)(r,n,a):a}};ja.PlatformConnectivityApi=bh});var bA=v(Xc=>{"use strict";Object.defineProperty(Xc,"__esModule",{value:!0});Xc.ConnectivityRouter=void 0;var vh=Q(),J4=iA(),Qc=Vo(),yA=fh(),wh=gA(),Ch=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,wh.assertTabularCloud)(this.instanceUrl),(0,yA.checkListTablesArguments)(t,r,n),this.tabularRoute().listConnectorTables(t,r,n)}async getConnectorTableSchema(t,r,n,i){return(0,wh.assertTabularCloud)(this.instanceUrl),(0,yA.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 wh.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 vh.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 vh.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 J4.ConnectivityApi(this.org,this.instanceUrl,r);throw new vh.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.")}};Xc.ConnectivityRouter=Ch});var Ha=v(Ei=>{"use strict";function Y4(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 Ah(e,t){return t===void 0&&(t=Object),t&&typeof t.freeze=="function"?t.freeze(e):e}function Q4(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 vA=Ah({HTML:"text/html",isHTML:function(e){return e===vA.HTML},XML_APPLICATION:"application/xml",XML_TEXT:"text/xml",XML_XHTML_APPLICATION:"application/xhtml+xml",XML_SVG_IMAGE:"image/svg+xml"}),wA=Ah({HTML:"http://www.w3.org/1999/xhtml",isHTML:function(e){return e===wA.HTML},SVG:"http://www.w3.org/2000/svg",XML:"http://www.w3.org/XML/1998/namespace",XMLNS:"http://www.w3.org/2000/xmlns/"}),Zc=/[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]/,Eh=new RegExp("[\\-\\.0-9"+Zc.source.slice(1,-1)+"\\u00B7\\u0300-\\u036F\\u203F-\\u2040]"),X4=new RegExp("^"+Zc.source+Eh.source+"*(?::"+Zc.source+Eh.source+"*)?$");Ei.assign=Q4;Ei.find=Y4;Ei.freeze=Ah;Ei.MIME_TYPE=vA;Ei.NAMESPACE=wA;Ei.nameStartChar=Zc;Ei.nameChar=Eh;Ei.tagNamePattern=X4});var $h=v(_i=>{var Sh=Ha(),zn=Sh.find,Ll=Sh.NAMESPACE,Ka=Sh.tagNamePattern;function Z4(e){return e!==""}function eG(e){return e?e.split(/[\t\n\f\r ]+/).filter(Z4):[]}function tG(e,t){return e.hasOwnProperty(t)||(e[t]=!0),e}function CA(e){if(!e)return[];var t=eG(e);return Object.keys(t.reduce(tG,{}))}function rG(e){return function(t){return e&&e.indexOf(t)!==-1}}function xl(e,t){for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r])}function Ar(e,t){var r=e.prototype;if(!(r instanceof t)){let i=function(){};var n=i;i.prototype=t.prototype,i=new i,xl(r,i),e.prototype=r=i}r.constructor!=e&&(typeof e!="function"&&console.error("unknown Class:"+e),r.constructor=e)}var Sr={},tn=Sr.ELEMENT_NODE=1,Ja=Sr.ATTRIBUTE_NODE=2,kl=Sr.TEXT_NODE=3,IA=Sr.CDATA_SECTION_NODE=4,OA=Sr.ENTITY_REFERENCE_NODE=5,nG=Sr.ENTITY_NODE=6,Nh=Sr.PROCESSING_INSTRUCTION_NODE=7,_h=Sr.COMMENT_NODE=8,PA=Sr.DOCUMENT_NODE=9,RA=Sr.DOCUMENT_TYPE_NODE=10,Ai=Sr.DOCUMENT_FRAGMENT_NODE=11,iG=Sr.NOTATION_NODE=12,jt={},Nt={},qse=jt.INDEX_SIZE_ERR=(Nt[1]="Index size error",1),Vse=jt.DOMSTRING_SIZE_ERR=(Nt[2]="DOMString size error",2),Er=jt.HIERARCHY_REQUEST_ERR=(Nt[3]="Hierarchy request error",3),Gse=jt.WRONG_DOCUMENT_ERR=(Nt[4]="Wrong document",4),EA=jt.INVALID_CHARACTER_ERR=(Nt[5]="Invalid character",5),Wse=jt.NO_DATA_ALLOWED_ERR=(Nt[6]="No data allowed",6),zse=jt.NO_MODIFICATION_ALLOWED_ERR=(Nt[7]="No modification allowed",7),kA=jt.NOT_FOUND_ERR=(Nt[8]="Not found",8),jse=jt.NOT_SUPPORTED_ERR=(Nt[9]="Not supported",9),AA=jt.INUSE_ATTRIBUTE_ERR=(Nt[10]="Attribute in use",10),En=jt.INVALID_STATE_ERR=(Nt[11]="Invalid state",11),Hse=jt.SYNTAX_ERR=(Nt[12]="Syntax error",12),Kse=jt.INVALID_MODIFICATION_ERR=(Nt[13]="Invalid modification",13),Jse=jt.NAMESPACE_ERR=(Nt[14]="Invalid namespace",14),Yse=jt.INVALID_ACCESS_ERR=(Nt[15]="Invalid access",15);function he(e,t){if(t instanceof Error)var r=t;else r=this,Error.call(this,Nt[e]),this.message=Nt[e],Error.captureStackTrace&&Error.captureStackTrace(this,he);return r.code=e,t&&(this.message=this.message+": "+t),r}he.prototype=Error.prototype;xl(jt,he);function Si(){}Si.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++)Lh(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 Ya(e,t){this._node=e,this._refresh=t,Th(this)}function Th(e){var t=e._node._inc||e._node.ownerDocument._inc;if(e._inc!==t){var r=e._refresh(e._node);if(jA(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];xl(r,e),e._inc=t}}Ya.prototype.item=function(e){return Th(this),this[e]||null};Ar(Ya,Si);function td(){this._nameIndex=Object.create(null)}function LA(e,t){for(var r=e.length;r--;)if(e[r]===t)return r}function oG(e,t){e._nameIndex[t.nodeName]=t}function $A(e,t){e._nameIndex[t.nodeName]===t&&delete e._nameIndex[t.nodeName]}function SA(e,t,r,n){if(n?(t[LA(t,n)]=r,$A(t,n)):t[t.length++]=r,oG(t,r),e){r.ownerElement=e;var i=e.ownerDocument;i&&(n&&MA(i,e,n),aG(i,e,r))}}function NA(e,t,r){var n=LA(t,r);if(n>=0){for(var i=t.length-1;n<i;)t[n]=t[++n];if(t.length=i,$A(t,r),e){var o=e.ownerDocument;o&&(MA(o,e,r),r.ownerElement=null)}}else throw new he(kA,new Error(e.tagName+"@"+r))}td.prototype={length:0,item:Si.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 he(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 he(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 NA(this._ownerElement,this,t),t},removeNamedItemNS:function(e,t){var r=this.getNamedItemNS(e,t);return NA(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 xA(){}xA.prototype={hasFeature:function(e,t){return!0},createDocument:function(e,t,r){var n=new Fl;if(n.implementation=this,n.childNodes=new Si,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 ad;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 nd(this,e,t)},replaceChild:function(e,t){nd(this,e,t,BA),t&&this.removeChild(t)},removeChild:function(e){return UA(this,e)},appendChild:function(e){return this.insertBefore(e,null)},hasChildNodes:function(){return this.firstChild!=null},cloneNode:function(e){return zA(this.ownerDocument||this,this,e)},normalize:function(){St(this,null,{enter:function(e){for(var t=e.firstChild;t;){var r=t.nextSibling;if(r!==null&&r.nodeType===kl&&t.nodeType===kl){for(var n=[],i=r;i!==null&&i.nodeType===kl;)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("")),od(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==Ja?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==Ja?t.ownerDocument:t.parentNode}return null},isDefaultNamespace:function(e){var t=this.lookupPrefix(e);return t==null}};function FA(e){return e=="<"&&"<"||e==">"&&">"||e=="&"&&"&"||e=='"'&&"""||"&#"+e.charCodeAt()+";"}xl(Sr,De);xl(Sr,De.prototype);function rd(e,t){return St(e,null,{enter:function(r){return t(r)?St.STOP:!0}})===St.STOP}function St(e,t,r){for(var n=[{node:e,context:t,phase:St.ENTER}];n.length>0;){var i=n.pop();if(i.phase===St.ENTER){var o=r.enter(i.node,i.context);if(o===St.STOP)return St.STOP;if(n.push({node:i.node,context:o,phase:St.EXIT}),o==null)continue;for(var a=i.node.lastChild;a;)n.push({node:a,context:o,phase:St.ENTER}),a=a.previousSibling}else r.exit&&r.exit(i.node,i.context)}}St.STOP=Symbol("walkDOM.STOP");St.ENTER=0;St.EXIT=1;function Fl(){this.ownerDocument=this}function aG(e,t,r){e&&e._inc++;var n=r.namespaceURI;n===Ll.XMLNS&&(t._nsMap[r.prefix?r.localName:""]=r.value)}function MA(e,t,r,n){e&&e._inc++;var i=r.namespaceURI;i===Ll.XMLNS&&delete t._nsMap[r.prefix?r.localName:""]}function od(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 UA(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,od(e.ownerDocument,e),t}function sG(e){return e&&(e.nodeType===De.DOCUMENT_NODE||e.nodeType===De.DOCUMENT_FRAGMENT_NODE||e.nodeType===De.ELEMENT_NODE)}function lG(e){return e&&(jn(e)||Dh(e)||Ni(e)||e.nodeType===De.DOCUMENT_FRAGMENT_NODE||e.nodeType===De.COMMENT_NODE||e.nodeType===De.PROCESSING_INSTRUCTION_NODE)}function Ni(e){return e&&e.nodeType===De.DOCUMENT_TYPE_NODE}function jn(e){return e&&e.nodeType===De.ELEMENT_NODE}function Dh(e){return e&&e.nodeType===De.TEXT_NODE}function _A(e,t){var r=e.childNodes||[];if(zn(r,jn)||Ni(t))return!1;var n=zn(r,Ni);return!(t&&n&&r.indexOf(n)>r.indexOf(t))}function TA(e,t){var r=e.childNodes||[];function n(o){return jn(o)&&o!==t}if(zn(r,n))return!1;var i=zn(r,Ni);return!(t&&i&&r.indexOf(i)>r.indexOf(t))}function uG(e,t,r){if(!sG(e))throw new he(Er,"Unexpected parent node type "+e.nodeType);if(r&&r.parentNode!==e)throw new he(kA,"child not in parent");if(!lG(t)||Ni(t)&&e.nodeType!==De.DOCUMENT_NODE)throw new he(Er,"Unexpected node type "+t.nodeType+" for parent node type "+e.nodeType)}function cG(e,t,r){var n=e.childNodes||[],i=t.childNodes||[];if(t.nodeType===De.DOCUMENT_FRAGMENT_NODE){var o=i.filter(jn);if(o.length>1||zn(i,Dh))throw new he(Er,"More than one element or text in fragment");if(o.length===1&&!_A(e,r))throw new he(Er,"Element in fragment can not be inserted before doctype")}if(jn(t)&&!_A(e,r))throw new he(Er,"Only one element can be added and only after doctype");if(Ni(t)){if(zn(n,Ni))throw new he(Er,"Only one doctype is allowed");var a=zn(n,jn);if(r&&n.indexOf(a)<n.indexOf(r))throw new he(Er,"Doctype can only be inserted before an element");if(!r&&a)throw new he(Er,"Doctype can not be appended since element is present")}}function BA(e,t,r){var n=e.childNodes||[],i=t.childNodes||[];if(t.nodeType===De.DOCUMENT_FRAGMENT_NODE){var o=i.filter(jn);if(o.length>1||zn(i,Dh))throw new he(Er,"More than one element or text in fragment");if(o.length===1&&!TA(e,r))throw new he(Er,"Element in fragment can not be inserted before doctype")}if(jn(t)&&!TA(e,r))throw new he(Er,"Only one element can be added and only after doctype");if(Ni(t)){let l=function(u){return Ni(u)&&u!==r};var s=l;if(zn(n,l))throw new he(Er,"Only one doctype is allowed");var a=zn(n,jn);if(r&&n.indexOf(a)<n.indexOf(r))throw new he(Er,"Doctype can only be inserted before an element")}}function nd(e,t,r,n){uG(e,t,r),e.nodeType===De.DOCUMENT_NODE&&(n||cG)(e,t,r);var i=t.parentNode;if(i&&i.removeChild(t),t.nodeType===Ai){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;$l(o,l)}while(o!==a&&(o=o.nextSibling));return od(e.ownerDocument||e,e),t.nodeType==Ai&&(t.firstChild=t.lastChild=null),t}function $l(e,t){if(e.ownerDocument!==t){if(e.ownerDocument=t,e.nodeType===tn&&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;)$l(i,t),i=i.nextSibling}}function dG(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,od(e.ownerDocument,e,t);var r=e.ownerDocument||e;return $l(t,r),t}Fl.prototype={nodeName:"#document",nodeType:PA,doctype:null,documentElement:null,_inc:1,insertBefore:function(e,t){if(e.nodeType==Ai){for(var r=e.firstChild;r;){var n=r.nextSibling;this.insertBefore(r,t),r=n}return e}return nd(this,e,t),$l(e,this),this.documentElement===null&&e.nodeType===tn&&(this.documentElement=e),e},removeChild:function(e){return this.documentElement==e&&(this.documentElement=null),UA(this,e)},replaceChild:function(e,t){nd(this,e,t,BA),$l(e,this),t&&this.removeChild(t),jn(e)&&(this.documentElement=e)},importNode:function(e,t){return fG(this,e,t)},getElementById:function(e){var t=null;return rd(this.documentElement,function(r){if(r.nodeType==tn&&r.getAttribute("id")==e)return t=r,!0}),t},getElementsByClassName:function(e){var t=CA(e);return new Ya(this,function(r){var n=[];return t.length>0&&rd(r.documentElement,function(i){if(i!==r&&i.nodeType===tn){var o=i.getAttribute("class");if(o){var a=e===o;if(!a){var s=CA(o);a=t.every(rG(s))}a&&n.push(i)}}}),n})},createElement:function(e){var t=new zo;t.ownerDocument=this,t.nodeName=e,t.tagName=e,t.localName=e,t.childNodes=new Si;var r=t.attributes=new td;return r._ownerElement=t,t},createDocumentFragment:function(){var e=new sd;return e.ownerDocument=this,e.childNodes=new Si,e},createTextNode:function(e){var t=new Ih;return t.ownerDocument=this,t.appendData(e),t},createComment:function(e){var t=new Oh;return t.ownerDocument=this,t.appendData(e),t},createCDATASection:function(e){if(e.indexOf("]]>")!==-1)throw new he(EA,'data contains "]]>"');var t=new Ph;return t.ownerDocument=this,t.appendData(e),t},createProcessingInstruction:function(e,t){var r=new kh;return r.ownerDocument=this,r.tagName=r.nodeName=r.target=e,r.nodeValue=r.data=t,r},createAttribute:function(e){var t=new id;return t.ownerDocument=this,t.name=e,t.nodeName=e,t.localName=e,t.specified=!0,t},createEntityReference:function(e){if(!Ka.test(e))throw new he(EA,'not a valid xml name "'+e+'"');var t=new Rh;return t.ownerDocument=this,t.nodeName=e,t},createElementNS:function(e,t){var r=new zo,n=t.split(":"),i=r.attributes=new td;return r.childNodes=new Si,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 id,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}};Ar(Fl,De);function zo(){this._nsMap={}}zo.prototype={nodeType:tn,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===Ai?this.insertBefore(e,null):dG(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 Ya(this,function(t){var r=[];return rd(t,function(n){n!==t&&n.nodeType==tn&&(e==="*"||n.tagName==e)&&r.push(n)}),r})},getElementsByTagNameNS:function(e,t){return new Ya(this,function(r){var n=[];return rd(r,function(i){i!==r&&i.nodeType===tn&&(e==="*"||i.namespaceURI===e)&&(t==="*"||i.localName==t)&&n.push(i)}),n})}};Fl.prototype.getElementsByTagName=zo.prototype.getElementsByTagName;Fl.prototype.getElementsByTagNameNS=zo.prototype.getElementsByTagNameNS;Ar(zo,De);function id(){}id.prototype.nodeType=Ja;Ar(id,De);function Ml(){}Ml.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(Nt[Er])},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}};Ar(Ml,De);function Ih(){}Ih.prototype={nodeName:"#text",nodeType:kl,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}};Ar(Ih,Ml);function Oh(){}Oh.prototype={nodeName:"#comment",nodeType:_h};Ar(Oh,Ml);function Ph(){}Ph.prototype={nodeName:"#cdata-section",nodeType:IA};Ar(Ph,Ml);function ad(){}ad.prototype.nodeType=RA;Ar(ad,De);function qA(){}qA.prototype.nodeType=iG;Ar(qA,De);function VA(){}VA.prototype.nodeType=nG;Ar(VA,De);function Rh(){}Rh.prototype.nodeType=OA;Ar(Rh,De);function sd(){}sd.prototype.nodeName="#document-fragment";sd.prototype.nodeType=Ai;Ar(sd,De);function kh(){}kh.prototype.nodeType=Nh;Ar(kh,De);function GA(){}GA.prototype.serializeToString=function(e,t,r,n){return WA.call(e,t,r,n)};De.prototype.toString=WA;function WA(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 Lh(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===Ll.XML||i===Ll.XMLNS)return!1;for(var o=r.length;o--;){var a=r[o];if(a.prefix===n)return a.namespace!==i}return!0}function ed(e,t,r,n){if(n&&!Ka.test(t))throw new he(En,'The attribute name "'+t+'" is not a valid XML QName');e.push(" ",t,'="',r.replace(/[<>&"\t\n\r]/g,FA),'"')}function Lh(e,t,r,n,i,o){i||(i=[]),St(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 tn:var c=a.attributes,d=c.length,f=a.tagName;u=Ll.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&&!Ka.test(m))throw new he(En,'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(DA(S,u,w)){var O=S.prefix||"",k=S.namespaceURI;ed(t,O?"xmlns:"+O:"xmlns",k,o),w.push({prefix:O,namespace:k})}var I=n?n(S):S;I&&(typeof I=="string"?t.push(I):ed(t,I.name,I.value,o))}if(f===m&&DA(a,u,w)){var D=a.prefix||"",k=a.namespaceURI;ed(t,D?"xmlns:"+D:"xmlns",k,o),w.push({prefix:D,namespace:k})}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):Lh(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 PA:case Ai:return{ns:l.slice(),isHTML:u,tag:null};case Ja:return ed(t,a.name,a.value,o),null;case kl:return t.push(a.data.replace(/[<&>]/g,FA)),null;case IA:if(o&&a.data.indexOf("]]>")!==-1)throw new he(En,'The CDATASection data contains "]]>"');return t.push("<![CDATA[",a.data.replace(/]]>/g,"]]]]><![CDATA[>"),"]]>"),null;case _h:if(o&&a.data.indexOf("-->")!==-1)throw new he(En,'The comment node data contains "-->"');return t.push("<!--",a.data,"-->"),null;case RA:if(o){if(!Ka.test(a.name))throw new he(En,'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 he(En,"DocumentType publicId is not a valid PubidLiteral");if(a.systemId&&!/^("[^"]*"|'[^']*')$/.test(a.systemId))throw new he(En,"DocumentType systemId is not a valid SystemLiteral");if(a.internalSubset&&a.internalSubset.indexOf("]>")!==-1)throw new he(En,'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 Oe=a.internalSubset;Oe&&t.push(" [",Oe,"]"),t.push(">")}return null;case Nh:if(o){if(!Ka.test(a.target)||a.target.indexOf(":")!==-1||a.target.toLowerCase()==="xml")throw new he(En,'The processing instruction target "'+a.target+'" is not a valid XML NCName or is reserved');if(a.data.indexOf("?>")!==-1)throw new he(En,'The ProcessingInstruction data contains "?>"')}return t.push("<?",a.target," ",a.data,"?>"),null;case OA:if(o&&!Ka.test(a.nodeName))throw new he(En,'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 fG(e,t,r){var n;return St(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===Ja||r;return s?a:null}}),n}function zA(e,t,r){var n;return St(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 Si),a.ownerDocument=e;var u=r;switch(a.nodeType){case tn:var c=i.attributes,d=a.attributes=new td,f=c.length;d._ownerElement=a;for(var m=0;m<f;m++)a.setAttributeNode(zA(e,c.item(m),!0));break;case Ja:u=!0}return o!==null?o.appendChild(a):n=a,u?a:null}}),n}function jA(e,t,r){e[t]=r}try{Object.defineProperty&&(Object.defineProperty(Ya.prototype,"length",{get:function(){return Th(this),this.$$length}}),Object.defineProperty(De.prototype,"textContent",{get:function(){if(this.nodeType===tn||this.nodeType===Ai){var e=[];return St(this,null,{enter:function(t){if(t.nodeType===tn||t.nodeType===Ai)return!0;if(t.nodeType===Nh||t.nodeType===_h)return null;e.push(t.nodeValue)}}),e.join("")}return this.nodeValue},set:function(e){switch(this.nodeType){case tn:case Ai: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}}}),jA=function(e,t,r){e["$$"+t]=r})}catch{}_i.DocumentType=ad;_i.DOMException=he;_i.DOMImplementation=xA;_i.Element=zo;_i.Node=De;_i.NodeList=Si;_i.walkDOM=St;_i.XMLSerializer=GA});var KA=v(Ul=>{"use strict";var HA=Ha().freeze;Ul.XML_ENTITIES=HA({amp:"&",apos:"'",gt:">",lt:"<",quot:'"'});Ul.HTML_ENTITIES=HA({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"});Ul.entityMap=Ul.HTML_ENTITIES});var ZA=v(Fh=>{var Vl=Ha().NAMESPACE,xh=Ha().tagNamePattern,Qa=0,no=1,Xa=2,Bl=3,Za=4,es=5,ql=6,ld=7;function ts(e,t){this.message=e,this.locator=t,Error.captureStackTrace&&Error.captureStackTrace(this,ts)}ts.prototype=new Error;ts.prototype.name=ts.name;function QA(){}QA.prototype={parse:function(e,t,r){var n=this.domBuilder;n.startDocument(),yG(t,t={}),pG(e,t,r,n,this.errorHandler),n.endDocument()}};function pG(e,t,r,n,i){function o(se){if(se>65535){se-=65536;var We=55296+(se>>10),ir=56320+(se&1023);return String.fromCharCode(We,ir)}else return String.fromCharCode(se)}function a(se){var We=se.slice(1,-1);return Object.hasOwnProperty.call(r,We)?r[We]:We.charAt(0)==="#"?o(parseInt(We.substr(1).replace("x","0x"))):(i.error("entity not found:"+se),se)}function s(se){if(se>h){var We=e.substring(h,se).replace(/&#?\w+;/g,a);f&&l(h),n.characters(We,0,se-h),h=se}}function l(se,We){for(;se>=c&&(We=d.exec(e));)u=We.index,c=u+We[0].length,f.lineNumber++;f.columnNumber=se-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)&&xh.test(C.split(/[ \t\n\r]/)[0])&&i.error('end tag name is followed by whitespace and trailing content: "'+C+'"');var O=S.localNSMap,k=S.tagName==C,I=k||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);k||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=vG(e,g,n);break;case"!":f&&l(g),K=bG(e,g,n,i);break;default:f&&l(g);var P=new XA,x=m[m.length-1].currentNSMap,K=mG(e,g,P,x,a,i),Oe=P.length;if(!P.closed&&gG(e,K,P.tagName,p)&&(P.closed=!0,r.nbsp||i.warning("unclosed xml attribute")),f&&Oe){for(var Vt=JA(f,{}),Xe=0;Xe<Oe;Xe++){var Ne=P[Xe];l(Ne.offset),Ne.locator=JA(f,{})}n.locator=Vt,YA(P,n,x)&&m.push(P),n.locator=f}else YA(P,n,x)&&m.push(P);Vl.isHTML(P.uri)&&!P.closed?K=hG(e,K,P.tagName,a,n):K++}}catch(se){if(se instanceof ts)throw se;i.error("element parse error: "+se),K=-1}K>h?h=K:s(Math.max(g,h)+1)}}function JA(e,t){return t.lineNumber=e.lineNumber,t.columnNumber=e.columnNumber,t}function mG(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=Qa;;){var d=e.charAt(u);if(c===Qa&&d==="<")throw new Error("unexpected < in tag name: "+e.slice(t,u));switch(d){case"=":if(c===no)s=e.slice(t,u),c=Bl;else if(c===Xa)c=Bl;else throw new Error("attribute equal must after attrName");break;case"'":case'"':if(c===Bl||c===no)if(c===no&&(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=es;else throw new Error("attribute value no end '"+d+"' match");else if(c==Za)l=e.slice(t,u),a(s,l,t),o.warning('attribute "'+s+'" missed start quot('+d+")!!"),t=u+1,c=es;else throw new Error('attribute value must after "="');break;case"/":switch(c){case Qa:r.setTagName(e.slice(t,u));case es:case ql:case ld:c=ld,r.closed=!0;case Za:case no:break;case Xa:r.closed=!0;break;default:throw new Error("attribute invalid close char('/')")}break;case"":return o.error("unexpected end of input"),c==Qa&&r.setTagName(e.slice(t,u)),u;case">":switch(c){case Qa:r.setTagName(e.slice(t,u));case es:case ql:case ld:break;case Za:case no:l=e.slice(t,u),l.slice(-1)==="/"&&(r.closed=!0,l=l.slice(0,-1));case Xa:c===Xa&&(l=s),c==Za?(o.warning('attribute "'+l+'" missed quot(")!'),a(s,l,t)):((!Vl.isHTML(n[""])||!l.match(/^(?:disabled|checked|selected)$/i))&&o.warning('attribute "'+l+'" missed value!! "'+l+'" instead!!'),a(l,l,t));break;case Bl:throw new Error("attribute value missed!!")}return u;case"\x80":d=" ";default:if(d<=" ")switch(c){case Qa:r.setTagName(e.slice(t,u)),c=ql;break;case no:s=e.slice(t,u),c=Xa;break;case Za:var l=e.slice(t,u);o.warning('attribute "'+l+'" missed quot(")!!'),a(s,l,t);case es:c=ql;break}else switch(c){case Xa:var f=r.tagName;(!Vl.isHTML(n[""])||!s.match(/^(?:disabled|checked|selected)$/i))&&o.warning('attribute "'+s+'" missed value!! "'+s+'" instead2!!'),a(s,s,t),t=u,c=no;break;case es:o.warning('attribute space is required"'+s+'"!!');case ql:c=no,t=u;break;case Bl:c=Za,t=u;break;case ld:throw new Error("elements closed character '/' and '>' must be connected to")}}u++}}function YA(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=Vl.XMLNS,t.startPrefixMapping(c,s))}for(var d=e.length;d--;){o=e[d];var l=o.prefix;l&&(l==="xml"&&(o.uri=Vl.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 hG(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 gG(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 yG(e,t){for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r])}function bG(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=wG(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 vG(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(!xh.test(e))throw new Error("invalid tagName:"+e);this.tagName=e},addValue:function(e,t,r){if(!xh.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 wG(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}Fh.XMLReader=QA;Fh.ParseError=ts});var aS=v(cd=>{var CG=Ha(),EG=$h(),eS=KA(),nS=ZA(),AG=EG.DOMImplementation,tS=CG.NAMESPACE,SG=nS.ParseError,NG=nS.XMLReader;function iS(e){return e.replace(/\r[\n\u0085]/g,`-`).replace(/[\r\u0085\u2028]/g,`-`)}function oS(e){this.options=e||{locator:{}}}oS.prototype.parseFromString=function(e,t){var r=this.options,n=new NG,i=r.domBuilder||new Gl,o=r.errorHandler,a=r.locator,s=r.xmlns||{},l=/\/x?html?$/.test(t),u=l?eS.HTML_ENTITIES:eS.XML_ENTITIES;a&&i.setDocumentLocator(a),n.errorHandler=_G(o,i,a),n.domBuilder=r.domBuilder||i,l&&(s[""]=tS.HTML),s.xml=s.xml||tS.XML;var c=r.normalizeLineEndings||iS;return e&&typeof e=="string"?n.parse(c(e),s,u):n.errorHandler.error("invalid doc source"),i.doc};function _G(e,t,r){if(!e){if(t instanceof Gl)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+Mh(r))}||function(){}}return o("warning"),o("error"),o("fatalError"),n}function Gl(){this.cdata=!1}function rs(e,t){t.lineNumber=e.lineNumber,t.columnNumber=e.columnNumber}Gl.prototype={startDocument:function(){this.doc=new AG().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;ud(this,o),this.currentElement=o,this.locator&&rs(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&&rs(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&&rs(this.locator,r),ud(this,r)},ignorableWhitespace:function(e,t,r){},characters:function(e,t,r){if(e=rS.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&&rs(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=rS.apply(this,arguments);var n=this.doc.createComment(e);this.locator&&rs(this.locator,n),ud(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&&rs(this.locator,i),ud(this,i),this.doc.doctype=i}},warning:function(e){console.warn("[xmldom warning] "+e,Mh(this.locator))},error:function(e){console.error("[xmldom error] "+e,Mh(this.locator))},fatalError:function(e){throw new SG(e,this.locator)}};function Mh(e){if(e)return`-@`+(e.systemId||"")+"#[line:"+e.lineNumber+",col:"+e.columnNumber+"]"}function rS(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){Gl.prototype[e]=function(){return null}});function ud(e,t){e.currentElement?e.currentElement.appendChild(t):e.doc.appendChild(t)}cd.__DOMHandler=Gl;cd.normalizeLineEndings=iS;cd.DOMParser=oS});var ns=v(dd=>{var sS=$h();dd.DOMImplementation=sS.DOMImplementation;dd.XMLSerializer=sS.XMLSerializer;dd.DOMParser=aS().DOMParser});var uS={};Jr(uS,{CCFControlConstants:()=>lS,CCFPropertyConstants:()=>Bh,CustomControlDataType:()=>F,CustomControlNames:()=>Ti,DefaultControlNameKeys:()=>Uh,ICCModeEnum:()=>io,JSONParametersConstants:()=>qh,LookUpType:()=>fd,ManifestXMLConstants:()=>Ht,NumberType:()=>pd,Usage:()=>jo});var lS,Bh,qh,Ht,F,Uh,Ti,io,jo,fd,pd,Ho=L(()=>{"use strict";lS={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"},Bh={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"},qh={GroupDefinition:"GroupDefinition"},Ht={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"})(Uh||(Uh={}));(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"})(Ti||(Ti={}));(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"})(io||(io={}));(function(e){e[e.Bound=0]="Bound",e[e.Input=1]="Input",e[e.Output=2]="Output"})(jo||(jo={}));fd=[F.LookupCustomer,F.LookupOwner,F.LookupPartyList,F.LookupRegarding,F.LookupSimple],pd=[F.WholeNone,F.WholeDuration,F.WholeLanguage,F.WholeTimeZone,F.FP,F.Decimal]});var is,ar,Wl=L(()=>{"use strict";is=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}},ar=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 cS={};Jr(cS,{AttributeDataSourceType:()=>zl,AttributeDataSourceTypeMask:()=>md,AttributePrecisionSource:()=>jl,EntityAttributeDataSourceType:()=>Ko,EntityAttributeDateTimeBehavior:()=>Wh,EntityAttributeImeMode:()=>Gh,EntityAttributePrecisionSource:()=>zh,EntityAttributeRequiredLevel:()=>oo,EntityAttributeType:()=>$,EntityAttributeTypeFormat:()=>W,EntityMetadataLookUpBase:()=>Di,EntityResxKeyLookUp:()=>hd,SourceTypeMask:()=>Vh});var Di,$,W,oo,Ko,Vh,zl,md,Gh,Wh,zh,jl,hd,os=L(()=>{"use strict";Wl();Di=class{name;constructor(t){this.name=t}toString(){return this.name}getName(){return this.name}getDisplayNameResourceKey(){return hd.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={}));oo=class extends Di{constructor(t){super(t)}static get None(){return"None"}static get SystemRequired(){return"SystemRequired"}static get ApplicationRequired(){return"ApplicationRequired"}static get Recommended(){return"Recommended"}},Ko=class e extends Di{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?zl.Persistent:parseInt(zl[this.name])}},Vh=class e extends Di{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(md[this.name])}};(function(e){e[e.Persistent=0]="Persistent",e[e.Calculated=1]="Calculated",e[e.Rollup=2]="Rollup"})(zl||(zl={}));(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"})(md||(md={}));Gh=class e extends Di{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"}},Wh=class e extends Di{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"}},zh=class e extends Di{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?jl.Currency:parseInt(jl[this.name])}};(function(e){e[e.Attribute=0]="Attribute",e[e.Organization=1]="Organization",e[e.Currency=2]="Currency"})(jl||(jl={}));hd=class e{static resourceKeyMap=e.initResourceKeyMap();static initResourceKeyMap(){let t=new is;return t.add($.TwoOptions,"SystemCustomization.type.bit.label"),t.add($.Customer,"SystemCustomization.type.customer.label"),t.add($.CustomerType,"SystemCustomization.type.customer.label"),t.add($.DateTime,"SystemCustomization.type.datetime.label"),t.add($.DecimalNumber,"SystemCustomization.type.decimal.label"),t.add($.FloatingPointNumber,"SystemCustomization.type.float.label"),t.add($.WholeNumber,"SystemCustomization.type.int.label"),t.add($.LookupType,"SystemCustomization.type.lookup.label"),t.add($.Lookup,"SystemCustomization.type.lookup.label"),t.add($.MultipleLineofText,"SystemCustomization.type.ntext.label"),t.add($.Currency,"SystemCustomization.type.money.label"),t.add($.Owner,"SystemCustomization.type.owner.label"),t.add($.OwnerType,"SystemCustomization.type.owner.label"),t.add($.PartyList,"SystemCustomization.type.partylist.label"),t.add($.PartyListType,"SystemCustomization.type.partylist.label"),t.add($.OptionSet,"SystemCustomization.type.picklist.label"),t.add($.State,"SystemCustomization.type.state.label"),t.add($.Status,"SystemCustomization.type.status.label"),t.add($.SingleLineofText,"SystemCustomization.type.nvarchar.label"),t.add($.UniqueIdentifier,"SystemCustomization.type.uniqueidentifier.label"),t.add($.UniqueIdentifierType,"SystemCustomization.type.uniqueidentifiertype.label"),t.add($.CalendarRulesType,"SystemCustomization.type.calendarrules.label"),t.add($.VirtualType,"SystemCustomization.type.virtual.label"),t.add($.BigInt,"SystemCustomization.type.bigint.label"),t.add($.ManagedPropertyType,"SystemCustomization.type.managedproperty.label"),t.add($.EntityNameType,"SystemCustomization.type.entityname.label"),t.add($.Image,"SystemCustomization.type.image.label"),t.add($.MultiSelectOptionSet,"SystemCustomization.type.multiselectpicklist.label"),t.add($.PrimaryNameAttributeType,"SystemCustomization.type.primaryname.label"),t.add($.LookupType,"SystemCustomization.type.lookuptype.label"),t.add($.Subject,"SystemCustomization.type.subject.label"),t.add(W.Email,"SystemCustomization.String.Format.email"),t.add(W.Text,"SystemCustomization.String.Format.text"),t.add(W.TextArea,"SystemCustomization.String.Format.textarea"),t.add(W.Url,"SystemCustomization.String.Format.url"),t.add(W.TickerSymbol,"SystemCustomization.String.Format.tickersymbol"),t.add(W.PhoneticGuide,"SystemCustomization.String.Format.phoneticguide"),t.add(W.VersionNumber,"SystemCustomization.String.Format.versionnumber"),t.add(W.Phone,"SystemCustomization.String.Format.phone"),t.add(W.None,"SystemCustomization.Integer.Format."),t.add(W.Duration,"SystemCustomization.Integer.Format.duration"),t.add(W.TimeZone,"SystemCustomization.Integer.Format.timezone"),t.add(W.Language,"SystemCustomization.Integer.Format.language"),t.add(W.Locale,"SystemCustomization.Integer.Format.language"),t.add(W.DateOnly,"SystemCustomization.DateTime.Format.date"),t.add(W.DateAndTime,"SystemCustomization.DateTime.Format.datetime"),t.add(W.Regarding,"SystemCustomization.Lookup.Format.regarding"),t.add(Ko.Persistent,"SystemCustomization.String.Source.persistent"),t.add(Ko.Calculated,"SystemCustomization.String.Source.calculated"),t.add(Ko.Rollup,"SystemCustomization.String.Source.rollup"),t.add(Ko.None,"SystemCustomization.String.Source.none"),t}static getDisplayNameResourceKey(t){return e.resourceKeyMap.getValue(t)}}});var Hh=v(ot=>{"use strict";Object.defineProperty(ot,"__esModule",{value:!0});ot.parsePcfManifest=ot.parseControlElement=ot.parseManifestRoot=ot.firstLevel=ot.attr=ot.elementChildren=ot.manifestTypesForColumn=ot.DEFAULT_TYPE_GROUPS=void 0;var TG=ns(),H=(Ho(),Br(uS)),we=(os(),Br(cS));ot.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 DG="Phone";function IG(e,t,r){switch(e){case we.EntityAttributeType.TwoOptions:return[H.CustomControlDataType.TwoOptions,H.CustomControlDataType.Boolean];case we.EntityAttributeType.Customer:case we.EntityAttributeType.CustomerType:return[H.CustomControlDataType.LookupCustomer];case we.EntityAttributeType.DateTime:return t===we.EntityAttributeTypeFormat.DateAndTime?[H.CustomControlDataType.DateAndTimeDateAndTime]:[H.CustomControlDataType.DateAndTimeDateOnly];case we.EntityAttributeType.DecimalNumber:return[H.CustomControlDataType.Decimal];case we.EntityAttributeType.FloatingPointNumber:return[H.CustomControlDataType.FP];case we.EntityAttributeType.File:return[H.CustomControlDataType.File];case we.EntityAttributeType.Image:return[H.CustomControlDataType.Image];case we.EntityAttributeType.WholeNumber:return t===we.EntityAttributeTypeFormat.Duration?[H.CustomControlDataType.WholeDuration]:t===we.EntityAttributeTypeFormat.Language?[H.CustomControlDataType.WholeLanguage]:t===we.EntityAttributeTypeFormat.TimeZone?[H.CustomControlDataType.WholeTimeZone]:[H.CustomControlDataType.WholeNone];case we.EntityAttributeType.LookupType:case we.EntityAttributeType.Lookup:return t===we.EntityAttributeTypeFormat.Regarding?[H.CustomControlDataType.LookupRegarding]:[H.CustomControlDataType.LookupSimple];case we.EntityAttributeType.MultipleLineofText:return[H.CustomControlDataType.Multiple];case we.EntityAttributeType.Currency:return[H.CustomControlDataType.Currency];case we.EntityAttributeType.Owner:case we.EntityAttributeType.OwnerType:return[H.CustomControlDataType.LookupOwner];case we.EntityAttributeType.PartyList:case we.EntityAttributeType.PartyListType:return[H.CustomControlDataType.LookupPartyList];case we.EntityAttributeType.Status:case we.EntityAttributeType.OptionSet:return[H.CustomControlDataType.OptionSet];case we.EntityAttributeType.SingleLineofText:switch(t){case we.EntityAttributeTypeFormat.Email:return[H.CustomControlDataType.SingleLineEmail];case we.EntityAttributeTypeFormat.Phone:return[H.CustomControlDataType.SingleLinePhone];case we.EntityAttributeTypeFormat.Text:return r===DG?[H.CustomControlDataType.SingleLinePhone]:[H.CustomControlDataType.SingleLineText];case we.EntityAttributeTypeFormat.TextArea:return[H.CustomControlDataType.SingleLineTextArea];case we.EntityAttributeTypeFormat.TickerSymbol:return[H.CustomControlDataType.SingleLineTickerSymbol];case we.EntityAttributeTypeFormat.Url:return[H.CustomControlDataType.SingleLineURL];default:return[H.CustomControlDataType.SingleLineText]}case we.EntityAttributeType.MultiSelectOptionSet:return[H.CustomControlDataType.MultiSelectOptionSet];default:return null}}ot.manifestTypesForColumn=IG;function jh(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}ot.elementChildren=jh;function An(e,t){return e.hasAttribute(t)?e.getAttribute(t):null}ot.attr=An;function Hn(e,...t){return jh(e).filter(r=>t.includes(r.tagName))}ot.firstLevel=Hn;function OG(e){let t=new Map;for(let r of Hn(e,"type-group"))t.set(String(An(r,"name")),Hn(r,"type").map(n=>String(n.textContent)));for(let[r,n]of t)t.set(r,n.sort());return t}function PG(e){let t=e.getElementsByTagName("AvailableOn")[0];if(!t)return{web:!0,phone:!0,tablet:!0};let r=new Set(jh(t).map(n=>n.tagName));return{web:r.has("web"),phone:r.has("phone"),tablet:r.has("tablet")}}var RG={input:"input",bound:"bound",output:"output"};function kG(e,t,r){let n=An(e,"usage"),i=n!==null&&RG[n]||"input",o=An(e,"default-value"),a=Hn(e,"value").map(m=>{let p={name:An(m,"name"),value:String(m.textContent),isDefault:An(m,"default")==="true"};return p.isDefault&&(o=p.value),p}),s=An(e,"of-type-group"),l=s!==null?t.get(s):void 0,u=s!==null&&Object.prototype.hasOwnProperty.call(ot.DEFAULT_TYPE_GROUPS,s)?ot.DEFAULT_TYPE_GROUPS[s]:void 0,c=l?[...l]:u?[...u]:[],d=An(e,"of-type"),f=d!==null?d:c.length>0?c[0]:null;return{name:An(e,"name"),usage:i,ofType:d,typeGroupName:s,ofTypeGroup:c,defaultType:f||void 0,required:An(e,"required")==="true",hidden:An(e,"hidden")==="true",defaultValue:o,enumValues:a,isPrimary:r&&i==="bound"}}function dS(e){var t;let r=[],n=a=>s=>r.push(`${a}: ${s}`),i=new TG.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}ot.parseManifestRoot=dS;function fS(e){let t=Hn(dS(e),"control")[0];if(!t)throw new Error("the control manifest has no <control> element");return t}ot.parseControlElement=fS;function LG(e){let t=fS(e),r=OG(t),n=Hn(t,"data-set"),i=Hn(t,"property"),o=Hn(t,"groups"),a=[],s=!1;for(let u of i){let c=kG(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=>Hn(u,"group").some(c=>Hn(c,"data-set","property").length>0)));return{properties:a,hasDataset:n.length>0,hasGroups:o.length>0,isBound:l,availableOn:PG(t)}}ot.parsePcfManifest=LG});var mS=v(ss=>{"use strict";Object.defineProperty(ss,"__esModule",{value:!0});ss.readPcfColumn=ss.readControlManifest=void 0;var as=le(),$G=Hh();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 xG(e,t){var r;let n="/customcontrols"+(0,as.odataQuery)([["$select","name,manifest"],["$filter",`name eq '${(0,as.odataLiteral)(t)}'`]]);try{let i=await e.get(n);if(i.status<200||i.status>=300)return{kind:"unavailable",error:Kh(`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,$G.parsePcfManifest)(s)}}catch(i){return{kind:"unavailable",error:i instanceof Error?i:new Error(String(i))}}}ss.readControlManifest=xG;var FG=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 pS(e){let t=e?.Value;return typeof t=="string"?t:void 0}async function MG(e,t,r,n){var i;let o=`/EntityDefinitions(LogicalName='${(0,as.odataPathLiteral)(t)}')/Attributes(LogicalName='${(0,as.odataPathLiteral)(r)}')`,a=n?.requireCreateEligibility===!0;try{let s=await e.get(o+(0,as.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:Kh(`reading column "${r}"`,s.status,s.body)};let l=(i=s.body)!==null&&i!==void 0?i:{},u=pS(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=FG.get(u);if(d){let f=await e.get(`${o}/Microsoft.Dynamics.CRM.${d.cast}`+(0,as.odataQuery)([["$select",d.select]]));if(f.status<200||f.status>=300)return{kind:"unavailable",error:Kh(`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=pS(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))}}}ss.readPcfColumn=MG});var Jo=v(gd=>{"use strict";Object.defineProperty(gd,"__esModule",{value:!0});gd.DEFAULT_LCID=void 0;gd.DEFAULT_LCID=1033});var pt=v(Kn=>{"use strict";Object.defineProperty(Kn,"__esModule",{value:!0});Kn.assignMissingIds=Kn.pointerTouchesValueMap=Kn.isValueMapKey=Kn.newId=void 0;var UG=Ma();function hS(){return globalThis.crypto.randomUUID().toLowerCase()}Kn.newId=hS;function BG(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}var Yh=new Set(["parameters","bag","expression","rawExpression","lookupValue","stepLabels","genPage","inputData","customControl"]);function qG(e){return Yh.has(e)}Kn.isValueMapKey=qG;function VG(e){return UG.JsonPointer.parse(e).some(t=>Yh.has(t))}Kn.pointerTouchesValueMap=VG;function GG(e){return Jh(e),e}Kn.assignMissingIds=GG;function Jh(e){if(Array.isArray(e)){e.forEach(t=>Jh(t));return}if(BG(e)){(typeof e.id!="string"||e.id.length===0)&&(e.id=hS());for(let t of Object.keys(e))t==="id"||Yh.has(t)||Jh(e[t])}}});var Kl=v(Kt=>{"use strict";Object.defineProperty(Kt,"__esModule",{value:!0});Kt.sendChangeSet=Kt.isChangeSetLockRefusal=Kt.partResponse=Kt.postChangeSet=Kt.parseChangeSetParts=Kt.parseChangeSetStatuses=Kt.renderChangeSet=void 0;var Ii=Q(),Yo=ye(),gS=pt(),Hl=le();function Qh(e,t){let r=`batch_${(0,gS.newId)()}`,n=`changeset_${(0,gS.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 Ii.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 Ii.InvalidArgumentError(`batch operation ${s.method} ${s.path} has a body containing the batch boundary`);(0,Hl.assertNoControlChars)(s.path,"batch operation path"),s.etag&&(0,Hl.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,Hl.assertNoControlChars)(m,"batch operation header name"),(0,Hl.assertNoControlChars)(p,"batch operation header value"),!/^[A-Za-z0-9!#$%&'*+.^_`|~-]+$/.test(m))throw new Ii.InvalidArgumentError(`batch operation header name '${m}' is not a valid HTTP token`);return s.contentType!==void 0&&(0,Hl.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}}Kt.renderChangeSet=Qh;function bS(e,t){var r;return(r=yd(e,t))===null||r===void 0?void 0:r.map(n=>n.status)}Kt.parseChangeSetStatuses=bS;function yd(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(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}Kt.parseChangeSetParts=yd;async function WG(e,t,r){if(t.length===0)return;let{body:n,batchId:i,contentIds:o}=Qh(e,t),a=await e.postBatch(n,i),s=e.apiUrl("/$batch");if((0,Yo.ensureSuccess)(a,s),typeof a.body!="string"||a.body.length===0)throw new Ii.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=bS(a.body,o);if(l===void 0)throw new Ii.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 Ii.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 Ii.ConnectionError(s,u,`atomic write of ${r} was rolled back: the change set reported HTTP ${u}`)}Kt.postChangeSet=WG;function Xh(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}}Kt.partResponse=Xh;function yS(e){let t=e.path.indexOf("?");return t===-1?e.path:e.path.slice(0,t)}function zG(e,t){let r=e.find(n=>(0,Yo.isVersionToken)(n.etag));if(!r||e.some(n=>yS(n)!==yS(r)))throw new Ii.InvalidArgumentError(`the change set writing ${t} cannot be re-sent under the customization lock: it needs an operation conditioned on a version token and every operation writing that operation's row`)}function vS(e,t){var r;if(e.status!==429&&(e.status<200||e.status>=300))return!1;let n=(r=yd(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=>(0,Yo.isConcurrencyLockRefusal)(Xh(i)))}Kt.isChangeSetLockRefusal=vS;async function jG(e,t,r,n={}){n.resendWhileLockRefused&&zG(t,r);let{body:i,batchId:o,contentIds:a}=Qh(e,t),s=()=>e.postBatch(i,o),l=n.resendWhileLockRefused?await(0,Yo.resendWhile)(f=>vS(f,a),s,Yo.LOCK_BACKOFF_MS):await s(),u=e.apiUrl("/$batch"),c=yd(l.body,a),d=c?.find(f=>f.status<200||f.status>=300);if(d&&(0,Yo.ensureSuccess)(Xh(d),e.apiUrl(t[a.indexOf(d.contentId)].path)),(0,Yo.ensureSuccess)(l,u),!c||c.length!==t.length)throw new Ii.ConnectionError(u,l.status,`atomic write of ${r} cannot be confirmed: the $batch response ${c?`reported ${c.length} result(s) for ${t.length} operation(s)`:"could not be parsed"}, so the outcome is unknown`);return a.map(f=>c.find(m=>m.contentId===f))}Kt.sendChangeSet=jG});var bd=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 _e=ye(),te=le(),Jn=Jo(),ge=Q(),HG=Kl(),KG={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 et(e,t){return{"@odata.type":"Microsoft.Dynamics.CRM.Label",LocalizedLabels:JG(e,t)}}var wS=65535;function JG(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 ge.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 ge.InvalidArgumentError(`localized label key '${o}' is not an LCID (expected a canonical positive integer, e.g. 1033)`);let s=Number(o);if(s>wS)throw new ge.InvalidArgumentError(`localized label LCID ${s} is out of range (1-${wS})`);if(i.has(s))throw new ge.InvalidArgumentError(`localized label LCID ${s} is specified more than once`);if(i.add(s),typeof a!="string")throw new ge.InvalidArgumentError(`localized label for LCID ${s} must be a string`);return r(a,s)})}function NS(e){return typeof e=="string"?`${e}s`:Object.fromEntries(Object.entries(e).map(([t,r])=>{if(typeof r!="string")throw new ge.InvalidArgumentError(`localized label for LCID ${t} must be a string`);return[t,`${r}s`]}))}ie.pluralFallback=NS;function Jl(e){return{Value:e,CanBeChanged:!0,ManagedPropertyLogicalName:"canmodifyrequirementlevelsettings"}}var CS=["None","ApplicationRequired","Recommended"];function tg(e){let t=e.indexOf("_");return t>0?e.slice(0,t):e}function ES(e,t,r){let n=e[t];n&&typeof n=="object"?n.Value=r:e[t]={Value:r}}function Yl(e){let t=(0,_e.readCreatedId)(e,"MetadataId");if(!t)throw new ge.InvalidArgumentError("Dataverse did not return a MetadataId for the created metadata component");return t}function YG(e,t,r){var n,i,o,a,s,l,u,c,d,f,m,p,h,g,b,w,C,S,O,k,I,D,P,x;if(t.defaultValue!==void 0&&e!=="boolean")throw new ge.InvalidArgumentError(`createColumn: 'defaultValue' applies to boolean columns, but '${t.schemaName}' is of type '${e}'.`);if(t.integerFormat!==void 0&&e!=="integer")throw new ge.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:et((C=t.trueLabel)!==null&&C!==void 0?C:"Yes",r)},FalseOption:{Value:0,Label:et((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 AS(t,r,!1);case"multiChoice":return AS(t,r,!0);case"file":return{"@odata.type":"Microsoft.Dynamics.CRM.FileAttributeMetadata",AttributeType:"Virtual",AttributeTypeName:{Value:"FileType"},MaxSizeInKB:(k=t.maxSizeKb)!==null&&k!==void 0?k: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 ge.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 ge.InvalidArgumentError(`unsupported column type '${String(e)}'`)}}function AS(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 ge.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:et(o.label,t)}))},i}var Zh=new WeakMap;async function QG(e,t){var r,n;let i=(r=Zh.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,_e.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||n===void 0?void 0:n.EntitySetName;if(!s)throw new ge.InvalidArgumentError(`could not resolve EntitySetName for '${t}'`);(0,te.assertODataName)(s,`server-derived EntitySetName for '${t}'`);let l=Zh.get(e);return l||(l=new Map,Zh.set(e,l)),l.set(t,s),s}ie.resolveEntitySetName=QG;async function XG(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&&!CS.includes(b))throw new ge.InvalidArgumentError(`createTable: 'primaryColumnRequired' must be one of ${CS.join(", ")}; got '${String(b)}'.`);let w=b!==void 0&&b!=="None";if(w&&!t.primaryColumnAutoNumberFormat&&!e.supportsPut)throw new ge.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:Jn.DEFAULT_LCID,S=tg(t.schemaName),O=(n=t.primaryColumnSchemaName)!==null&&n!==void 0?n:`${S}_Name`,k={"@odata.type":"Microsoft.Dynamics.CRM.StringAttributeMetadata",AttributeType:"String",AttributeTypeName:{Value:"StringType"},SchemaName:O,RequiredLevel:Jl(b??"None"),MaxLength:(i=t.primaryColumnMaxLength)!==null&&i!==void 0?i:100,FormatName:{Value:"Text"},DisplayName:et((o=t.primaryColumnDisplayName)!==null&&o!==void 0?o:"Name",C),IsPrimaryName:!0};t.primaryColumnAutoNumberFormat&&(k.AutoNumberFormat=t.primaryColumnAutoNumberFormat),t.columns&&IS(t.columns,"createTable");let I={"@odata.type":"Microsoft.Dynamics.CRM.EntityMetadata",SchemaName:t.schemaName,DisplayName:et(t.displayName,C),DisplayCollectionName:et((a=t.pluralName)!==null&&a!==void 0?a:NS(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:[k,...((c=t.columns)!==null&&c!==void 0?c:[]).map(ir=>rg(ir,C))]};t.description&&(I.Description=et(t.description,C));let D="/EntityDefinitions",P=(0,_e.ensureSuccess)(await e.post(D,I),e.apiUrl(D)),x=Yl(P),K=`/EntityDefinitions(${x})`+(0,te.odataQuery)([["$select","LogicalName,EntitySetName,PrimaryIdAttribute,PrimaryNameAttribute"]]),Oe=Math.max(1,Math.trunc((d=t.readBackAttempts)!==null&&d!==void 0?d:6)),Vt=Math.max(0,(f=t.readBackDelayMs)!==null&&f!==void 0?f:1e3),Xe=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}' }).`:"",Ne;try{Ne=await _S(e,K,Oe,Vt)}catch(ir){throw w?(0,ge.attachCause)(new ge.SdkError("PRIMARY_COLUMN_REQUIRED_NOT_APPLIED",`Table '${t.schemaName}' WAS CREATED (MetadataId ${x}), but reading it back failed (${ir instanceof Error?ir.message:String(ir)}).${Xe} Do NOT re-run the create \u2014 it will collide on the schema name.`),ir):ir}if(!Ne)throw new ge.SdkError("TABLE_METADATA_NOT_VISIBLE",`Table '${t.schemaName}' WAS CREATED (MetadataId ${x}) but its metadata was still not readable after ${Oe} 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'.${Xe}`);let se=Ne.body,We={logicalName:(m=se.LogicalName)!==null&&m!==void 0?m:t.schemaName.toLowerCase(),metadataId:x,entitySetName:(p=se.EntitySetName)!==null&&p!==void 0?p:"",primaryIdAttribute:(h=se.PrimaryIdAttribute)!==null&&h!==void 0?h:`${t.schemaName.toLowerCase()}id`,primaryNameAttribute:(g=se.PrimaryNameAttribute)!==null&&g!==void 0?g:O.toLowerCase()};return w&&(We.primaryColumnRequired=await ZG(e,t.schemaName,We,b,Oe,Vt)),We}ie.createTable=XG;async function _S(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,_e.ensureSuccess)(o,e.apiUrl(t)),i<r&&n>0&&await new Promise(a=>setTimeout(a,n))}}async function ZG(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 _S(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 ge.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 kS(e,r.logicalName,r.primaryNameAttribute,{required:n}),l="verify",u=await s())}catch(d){throw l==="verify"&&(u=void 0),(0,ge.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 rg(e,t){var r,n;let i=(r=e.languageCode)!==null&&r!==void 0?r:t,o={...YG(e.type,e,i),SchemaName:e.schemaName,RequiredLevel:Jl((n=e.required)!==null&&n!==void 0?n:"None"),DisplayName:et(e.displayName,i)};return e.description&&(o.Description=et(e.description,i)),e.sourceType&&e.sourceType!=="Simple"&&(o.SourceType=e.sourceType==="Rollup"?2:1,e.formulaDefinition&&(o.FormulaDefinition=e.formulaDefinition)),TS(o,e),o}function TS(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 e9(e,t,r){var n;let i=rg(r,(n=r.languageCode)!==null&&n!==void 0?n:Jn.DEFAULT_LCID),o=`/EntityDefinitions(LogicalName='${(0,te.odataPathLiteral)(t)}')/Attributes`,a=(0,_e.ensureSuccess)(await e.post(o,i),e.apiUrl(o)),s={logicalName:r.schemaName.toLowerCase(),metadataId:Yl(a)};if(r.visualization&&r.visualization!=="None")try{await RS(e,t,s.logicalName,s.metadataId,r.visualization)}catch(l){let u=new ge.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,ge.attachCause)(u,l),u}return s}ie.createColumn=e9;var ls="/controlconfigurations",DS="CustomRenderersConfiguration",eg={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 IS(e,t){let r=e.find(n=>n.visualization&&n.visualization!=="None");if(r)throw new ge.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 OS(e){return JSON.stringify({type:eg[e]})}function t9(e){if(!e)return"None";let t;try{t=JSON.parse(e)}catch{return"None"}let r=t?.type,n=Object.keys(eg).find(i=>eg[i]===r);return n??"None"}async function PS(e,t,r){var n,i;let o=`entitylogicalname eq '${(0,te.odataLiteral)(t)}' and Attribute/logicalname eq '${(0,te.odataLiteral)(r)}'`,a=`${ls}${(0,te.odataQuery)([["$select","name,uniquename,metadatajson"],["$expand","Attribute($select=name,logicalname)"],["$filter",o]])}`,l=(i=(n=(0,_e.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 r9(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,_e.ensureSuccess)(await e.get(i),e.apiUrl(i)).body)===null||n===void 0?void 0:n.MetadataId;if(!a)throw new ge.InvalidArgumentError(`cannot resolve column '${r}' on '${t}' to set its visualization`);return(0,te.normalizeGuid)(a,"MetadataId")}async function RS(e,t,r,n,i){let o={name:DS,uniquename:`msdyn_${t}_${r}_customrenderers`,metadatajson:OS(i),"[email protected]":`/attributes(${(0,te.normalizeGuid)(n,"MetadataId")})`,entitylogicalname:t};(0,_e.ensureSuccess)(await e.post(ls,o),e.apiUrl(ls))}async function n9(e,t,r){var n;let i=await PS(e,t,r);return t9((n=i[0])===null||n===void 0?void 0:n.metadatajson)}ie.getColumnVisualization=n9;async function i9(e,t,r,n){let o=(await PS(e,t,r)).map(u=>u.controlconfigurationid).filter(u=>!!u);if(n==="None"){for(let u of o){let c=`${ls}(${(0,te.normalizeGuid)(u,"controlconfigurationid")})`;(0,_e.ensureSuccess)(await e.delete(c),e.apiUrl(c))}return}let[a,...s]=o,l=await r9(e,t,r);if(a){let u=`${ls}(${(0,te.normalizeGuid)(a,"controlconfigurationid")})`,c={name:DS,metadatajson:OS(n),"[email protected]":`/attributes(${l})`,entitylogicalname:t};(0,_e.ensureSuccess)(await e.patch(u,c),e.apiUrl(u))}else await RS(e,t,r,l,n);for(let u of s){let c=`${ls}(${(0,te.normalizeGuid)(u,"controlconfigurationid")})`;(0,_e.ensureSuccess)(await e.delete(c),e.apiUrl(c))}}ie.setColumnVisualization=i9;async function o9(e,t,r){if(r.length===0)return;if(IS(r,"createColumns"),!e.supportsAtomicBatch)throw new ge.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,HG.postChangeSet)(e,r.map(i=>{var o;return{method:"POST",path:n,body:rg(i,(o=i.languageCode)!==null&&o!==void 0?o:Jn.DEFAULT_LCID)}}),`${r.length} column(s) on '${t}'`)}ie.createColumns=o9;async function a9(e,t,r){var n,i,o,a;let s=(n=r.languageCode)!==null&&n!==void 0?n:Jn.DEFAULT_LCID,l=tg(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:et(r.displayName,s),RequiredLevel:Jl((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,_e.ensureSuccess)(await e.post("/CreateCustomerRelationships",d),e.apiUrl("/CreateCustomerRelationships")),{logicalName:r.schemaName.toLowerCase(),metadataId:""}}ie.createCustomerColumn=a9;async function s9(e,t,r){var n,i,o,a,s;let l=(n=r.languageCode)!==null&&n!==void 0?n:Jn.DEFAULT_LCID,u={EntityLogicalName:t,AttributeLogicalName:"statuscode",Label:et(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,_e.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=s9;async function l9(e,t){var r,n,i,o,a;let s=(r=t.languageCode)!==null&&r!==void 0?r:Jn.DEFAULT_LCID,l,u;if(t.type==="OneToMany"){if(!t.referencedEntity||!t.referencingEntity)throw new ge.InvalidArgumentError("OneToMany relationship requires referencedEntity and referencingEntity");let f=(n=t.lookupSchemaName)!==null&&n!==void 0?n:`${tg(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:Jl((i=t.lookupRequired)!==null&&i!==void 0?i:"None"),DisplayName:et((o=t.lookupDisplayName)!==null&&o!==void 0?o:t.referencedEntity,s)}}}else{if(!t.entity1||!t.entity2)throw new ge.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,_e.ensureSuccess)(await e.post(c,l),e.apiUrl(c));return{schemaName:t.schemaName,metadataId:Yl(d),lookupLogicalName:u}}ie.createRelationship=l9;async function u9(e,t){let r=`/EntityDefinitions(LogicalName='${(0,te.odataPathLiteral)(t)}')`;(0,_e.ensureSuccess)(await e.delete(r),e.apiUrl(r))}ie.deleteTable=u9;async function kS(e,t,r,n){var i,o;let a=(i=n.languageCode)!==null&&i!==void 0?i:Jn.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,_e.ensureSuccess)(await e.get(l),e.apiUrl(l)).body,d=KG[(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 ge.InvalidArgumentError(`cannot update column '${r}' on '${t}' (${g})`)}let f=(0,te.normalizeGuid)(c.MetadataId,"MetadataId"),m=`${s}(${f})/${d}`,p=(0,_e.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=et(n.displayName,a)),n.description!==void 0&&(p.Description=et(n.description,a)),n.required!==void 0&&(p.RequiredLevel=Jl(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 ge.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 ge.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),TS(p,n);let h=`${s}(${f})`;(0,_e.ensureSuccess)(await e.put(h,p,{headers:{"MSCRM.MergeLabels":"true"}}),e.apiUrl(h))}ie.updateColumn=kS;async function c9(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,_e.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||n===void 0?void 0:n.MetadataId;if(!s)throw new ge.InvalidArgumentError(`column '${r}' not found on '${t}'`);let l=`${i}(${(0,te.normalizeGuid)(s,"MetadataId")})`;(0,_e.ensureSuccess)(await e.delete(l),e.apiUrl(l))}ie.deleteColumn=c9;async function d9(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,_e.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 ge.InvalidArgumentError(`relationship '${t}' not found`);let l=`/RelationshipDefinitions(${(0,te.normalizeGuid)(s,"MetadataId")})`;(0,_e.ensureSuccess)(await e.delete(l),e.apiUrl(l))}ie.deleteRelationship=d9;async function SS(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,_e.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 f9(e,t){var r;let n=t.name.toLowerCase(),i=await SS(e,n);if(i)return{name:n,metadataId:i};let o=(r=t.languageCode)!==null&&r!==void 0?r:Jn.DEFAULT_LCID,a={"@odata.type":"Microsoft.Dynamics.CRM.OptionSetMetadata",Name:n,DisplayName:et(t.displayName,o),IsGlobal:!0,OptionSetType:"Picklist",Options:t.options.map(l=>({Value:l.value,Label:et(l.label,o)}))};t.description&&(a.Description=et(t.description,o));let s="/GlobalOptionSetDefinitions";try{let l=(0,_e.ensureSuccess)(await e.post(s,a),e.apiUrl(s));return{name:n,metadataId:Yl(l)}}catch(l){let u;try{u=await SS(e,n)}catch{u=void 0}if(u)return{name:n,metadataId:u};throw l}}ie.createGlobalOptionSet=f9;async function p9(e,t){let r=`/GlobalOptionSetDefinitions(Name='${(0,te.odataPathLiteral)(t.toLowerCase())}')`;(0,_e.ensureSuccess)(await e.delete(r),e.apiUrl(r))}ie.deleteGlobalOptionSet=p9;async function m9(e,t,r){var n;let i=(n=r.languageCode)!==null&&n!==void 0?n:Jn.DEFAULT_LCID,o={"@odata.type":"Microsoft.Dynamics.CRM.EntityKeyMetadata",SchemaName:r.schemaName,DisplayName:et(r.displayName,i),KeyAttributes:r.keyAttributes},a=`/EntityDefinitions(LogicalName='${(0,te.odataPathLiteral)(t)}')/Keys`,s=(0,_e.ensureSuccess)(await e.post(a,o),e.apiUrl(a));return{logicalName:r.schemaName.toLowerCase(),metadataId:Yl(s)}}ie.createAlternateKey=m9;async function h9(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,_e.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||n===void 0?void 0:n.MetadataId;if(!s)throw new ge.InvalidArgumentError(`alternate key '${r}' not found on '${t}'`);let l=`${i}(${(0,te.normalizeGuid)(s,"MetadataId")})`;(0,_e.ensureSuccess)(await e.delete(l),e.apiUrl(l))}ie.deleteAlternateKey=h9;async function g9(e,t,r){var n;let i=(n=r.languageCode)!==null&&n!==void 0?n:Jn.DEFAULT_LCID,o=`/EntityDefinitions(LogicalName='${(0,te.odataPathLiteral)(t)}')`,s=(0,_e.ensureSuccess)(await e.get(o),e.apiUrl(o)).body,l=s.MetadataId;if(!l)throw new ge.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=et(r.displayName,i)),r.pluralName!==void 0&&(s.DisplayCollectionName=et(r.pluralName,i)),r.description!==void 0&&(s.Description=et(r.description,i)),r.auditEnabled!==void 0&&ES(s,"IsAuditEnabled",r.auditEnabled),r.duplicateDetectionEnabled!==void 0&&ES(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,_e.ensureSuccess)(await e.put(c,s,{headers:{"MSCRM.MergeLabels":"true"}}),e.apiUrl(c))}ie.updateTable=g9});var so=v(Nr=>{"use strict";Object.defineProperty(Nr,"__esModule",{value:!0});Nr.rebuildRaw=Nr.assembleChildren=Nr.spliceChildren=Nr.mergeAttrs=Nr.rawFromNode=Nr.emptyBag=void 0;var ao=Q(),LS=1e6,wd=512;function y9(){return{a:[],c:[]}}Nr.emptyBag=y9;function $S(e,t=0){if(t>wd)throw new ao.InvalidArgumentError(`Artifact node tree exceeds the maximum depth of ${wd}`);return{n:e.getNodeName(),a:e.getAllProperties().map(r=>[r.key,r.value]),c:e.getAllChildren().map(r=>$S(r,t+1))}}Nr.rawFromNode=$S;function b9(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}Nr.mergeAttrs=b9;function vd(e,t){let r=new Set;for(let s of e){let l=s.i;if(!Number.isInteger(l)||l<0||l>LS)throw new ao.InvalidArgumentError(`Bag child index must be an integer in [0, ${LS}] (got ${String(l)})`);if(r.has(l))throw new ao.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}Nr.spliceChildren=vd;function v9(e,t){if(e.w){let r={n:e.w.n,a:e.w.a.map(n=>[n[0],n[1]]),c:vd(e.w.c,t)};return vd(e.c,[r])}return vd(e.c,t)}Nr.assembleChildren=v9;function xS(e,t,r,n=0){if(n>wd)throw new ao.InvalidArgumentError(`Artifact node tree exceeds the maximum depth of ${wd}`);w9(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,xS(o,t,i,n+1));return i}Nr.rebuildRaw=xS;function w9(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new ao.InvalidArgumentError(`Malformed hybrid node at depth ${t}: expected a JSON object`);let r=e;if(typeof r.n!="string")throw new ao.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 ao.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 ao.InvalidArgumentError(`Malformed hybrid node '${r.n}': each attribute must be a [string, string] pair`)}});var lo=v(Cd=>{"use strict";Object.defineProperty(Cd,"__esModule",{value:!0});Cd.installDomShim=void 0;var FS=ns(),MS=!1,C9={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 E9(){if(MS)return;let e=globalThis;typeof e.DOMParser>"u"&&(e.DOMParser=FS.DOMParser),typeof e.XMLSerializer>"u"&&(e.XMLSerializer=FS.XMLSerializer),typeof e.Node>"u"&&(e.Node=C9),MS=!0}Cd.installDomShim=E9});var uo=v(tt=>{"use strict";Object.defineProperty(tt,"__esModule",{value:!0});tt.projectElementBag=tt.serializeNode=tt.domEngine=tt.nodeLikeFromDom=tt.parseXmlRoot=tt.EMPTY_FORM_SENTINEL=tt.TEXT_SENTINEL=void 0;var A9=so(),us=Q(),S9=lo();tt.TEXT_SENTINEL="#text";tt.EMPTY_FORM_SENTINEL="#empty";var Ad=new WeakSet;function N9(e,t){(0,S9.installDomShim)();let r=e&&e.trim()!==""?e:t,n=new DOMParser().parseFromString(r,"text/xml"),i=n.documentElement;if(!i)throw new us.InvalidArgumentError("XML source has no root element (empty or malformed input)");return _9(r),D9(n),O9(i),P9(i),L9(i,r),i}tt.parseXmlRoot=N9;function _9(e){let t=e.search(/\S/);if(t!==-1&&e[t]!=="<")throw BS(3)}var T9=["http://www.mozilla.org/newlayout/xml/parsererror.xml","http://www.w3.org/1999/xhtml"];function D9(e){var t;for(let r of T9){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 us.InvalidArgumentError(`XML source is not well-formed (${i||"the XML parser reported an error"}), so it cannot be round-tripped`)}}}var I9=new Set([1,3]);function O9(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(!I9.has(o.nodeType))throw new us.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 P9(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 BS(a.nodeType)}}function BS(e){return new us.InvalidArgumentError(`Unsupported document-level XML node (type ${e}: declaration / comment / processing-instruction outside the root element) cannot be round-tripped`)}function R9(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 k9(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 qS(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 L9(e,t){let r=R9(t),n=k9(e),i=Math.min(r.length,n.length);for(let o=0;o<i;o+=1){if(r[o])continue;let a=n[o];qS(a)||Ad.add(a)}}function ng(e){let t=e.nodeType===3;return{getNodeName:()=>t?tt.TEXT_SENTINEL:e.tagName,getAllProperties:()=>{var r;if(t)return[{key:tt.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 Ad.has(e)&&!qS(e)&&i.push({key:tt.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(ng(o))}return r}}}tt.nodeLikeFromDom=ng;function $9(e){return{make:t=>t===tt.TEXT_SENTINEL?e.createTextNode(""):e.createElement(t),setProp:(t,r,n)=>{t.nodeType===3?t.nodeValue=n:r===tt.EMPTY_FORM_SENTINEL?Ad.add(t):t.setAttribute(r,n)},addChild:(t,r)=>{t.appendChild(r)}}}tt.domEngine=$9;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 Ed(r);if(r>=55296&&r<=56319){let n=e.charCodeAt(t+1);if(!(n>=56320&&n<=57343))throw Ed(r);t+=1;continue}if(r>=56320&&r<=57343)throw Ed(r)}}function Ed(e){let t=e.toString(16).toUpperCase().padStart(4,"0");return new us.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 x9(e){return VS(e),String(e).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/\r/g,"
").replace(/\n/g,"
").replace(/\t/g,"	")}function F9(e){return VS(e),String(e).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}function M9(e){return GS(e,0)}tt.serializeNode=M9;var US=512;function GS(e,t){var r;if(t>US)throw new us.InvalidArgumentError(`XML nesting exceeds the maximum supported depth of ${US}`);if(e.nodeType===3)return F9((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+'="'+x9(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 Ad.has(n)?i+"></"+n.tagName+">":i+" />";i+=">";for(let l of a)i+=GS(l,t+1);return i+"</"+n.tagName+">"}function U9(e){let t=ng(e);return{a:t.getAllProperties().map(r=>[r.key,r.value]),c:t.getAllChildren().map((r,n)=>({i:n,node:(0,A9.rawFromNode)(r)}))}}tt.projectElementBag=U9});var rn=v(Jt=>{"use strict";Object.defineProperty(Jt,"__esModule",{value:!0});Jt.rejectUnknownKeys=Jt.childObjects=Jt.optionalGuidId=Jt.optionalEnum=Jt.eachObject=Jt.issue=Jt.isJsonObject=void 0;function WS(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}Jt.isJsonObject=WS;function cs(e,t,r,n){return n?{pointer:e,rule:t,message:r,fatal:n}:{pointer:e,rule:t,message:r}}Jt.issue=cs;function zS(e,t,r,n){if(!Array.isArray(e))return[];let i=[];return e.forEach((o,a)=>{WS(o)?i.push({node:o,index:a}):n.push(cs(`${t}/${a}`,`${r}-must-be-object`,`a ${r} must be a JSON object, got ${o===null?"null":typeof o}`))}),i}Jt.eachObject=zS;function B9(e,t,r,n,i,o){let a=e[t];a!==void 0&&(typeof a!="string"||!r.includes(a))&&o.push(cs(`${n}/${t}`,i,`${t} must be one of ${r.map(s=>`'${s}'`).join(", ")}, got ${JSON.stringify(a)}`))}Jt.optionalEnum=B9;var q9=/^(?:\{[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 V9(e,t,r,n,i){let o=e[t];typeof o=="string"&&o!==""&&!q9.test(o)&&i.push(cs(`${r}/${t}`,n,`${t} must be a GUID or empty, got '${o}'`))}Jt.optionalGuidId=V9;function G9(e,t,r,n,i){let o=e[t],a=`${r}/${t}`;return o===void 0?[]:Array.isArray(o)?zS(o,a,n,i):(i.push(cs(a,`${n}-list-must-be-array`,`${t} must be an array when present, got ${typeof o}`)),[])}Jt.childObjects=G9;function W9(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(cs(`${r}/${l}`,`${n}-unknown-key`,`'${l}' is not a ${n} property, and would be SILENTLY DROPPED at serialization.${d}`))}}Jt.rejectUnknownKeys=W9});var Dd=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 z9=ns(),j9=Ma(),ig=pt(),nn=rn();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 H9=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function _r(e){if(typeof e!="string")return"";let t=e.trim().toLowerCase();return t.startsWith("{")&&t.endsWith("}")&&(t=t.slice(1,-1)),H9.test(t)?t:""}B.normGuid=_r;function co(e,t){let r=Se(e?.a).find(n=>Array.isArray(n)&&n[0]===t);return r?r[1]:void 0}B.rawAttr=co;function Xl(e){return Se(e?.c).filter(t=>typeof t?.n=="string"&&t.n.startsWith("<")).map(t=>t.n.slice(1)).join("")}B.rawText=Xl;function Se(e){return Array.isArray(e)?e:[]}function cg(e,t){let r=Se(e?.a).find(n=>Array.isArray(n)&&n[0]===t);return r?r[1]:void 0}function KS(e){return typeof e=="string"?e.trim().replace(/^\{|\}$/g,"").toUpperCase():""}function JS(e){return Sn(e).map(t=>t.cell)}B.typedCells=JS;function Sn(e){let t=[];return Se(e?.tabs).forEach((r,n)=>{Se(Re(r)?r.columns:void 0).forEach((i,o)=>{Se(Re(i)?i.sections:void 0).forEach((a,s)=>{Se(Re(a)?a.rows:void 0).forEach((l,u)=>{Se(Re(l)?l.cells:void 0).forEach((c,d)=>{Re(c)&&t.push({cell:c,pointer:`/tabs/${n}/columns/${o}/sections/${s}/rows/${u}/cells/${d}`})})})})})}),t}B.typedCellSites=Sn;function Oi(e){return Re(e)?_r(cg(e.bag,"uniqueid")):""}B.controlUniqueId=Oi;function K9(e){let t=new Set;for(let{cell:r}of Sn(e)){let n=Zo(r.control)?Oi(r.control):"";n&&t.add(n)}return t}function J9(e){let t=new Map;for(let{cell:r}of Sn(e)){let n=Re(r.control)?Oi(r.control):"";n&&!t.has(n)&&t.set(n,r.control)}return t}function Y9(e){return e!==void 0&&e.genPage===void 0&&(pg(e)!==B.CUSTOM_CONTROL_CLASS_ID||!Td(e))}function og(e,t){if(Re(e)){t(e);for(let r of Se(e.c))og(r,t)}}function Qo(e,t){var r;if(Re(e)){for(let n of Se(e.c))og(n?.node,t);for(let n of Se((r=e.w)===null||r===void 0?void 0:r.c))og(n?.node,t)}}function Nd(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(_r(co(i,"uniqueid")))};return Qo(e?.bag,n),Se(e?.tabs).forEach(i=>{Re(i)&&(Qo(i.bag,n),Se(i.columns).forEach(o=>{Re(o)&&(Qo(o.bag,n),Se(o.sections).forEach(a=>{Re(a)&&(Qo(a.bag,n),Se(a.rows).forEach(s=>{Re(s)&&(Qo(s.bag,n),Se(s.cells).forEach(l=>{Re(l)&&(Qo(l.bag,n),Re(l.control)&&(r(Oi(l.control)),Qo(l.control.bag,n)))}))}))}))}))}),t}B.controlUniqueIds=Nd;function ds(e){return Se(e?.c).find(t=>{var r;return((r=t?.node)===null||r===void 0?void 0:r.n)==="controlDescriptions"})}B.descriptionsRegion=ds;function Xo(e,t){var r;let n=_r(t);if(n)return Se((r=ds(e))===null||r===void 0?void 0:r.node.c).find(i=>i?.n==="controlDescription"&&_r(co(i,"forControl"))===n)}B.descriptionFor=Xo;function Zl(e){return Se(e.c).filter(YS)}B.pageEntries=Zl;function YS(e){return e?.n==="customControl"&&co(e,"name")===B.GENPAGE_CONTROL_NAME}function ag(e,t){let r=Se(e.c).find(n=>n?.n==="parameters");return Se(r?.c).find(n=>n?.n===t)}B.entryParameter=ag;function sg(e){return co(e,"static")==="true"}B.isStaticParameter=sg;function eu(e){let t=Zl(e);if(t.length===0)return{kind:"none"};let r,n;for(let i=0;i<t.length;i+=1){let o=ag(t[i],"RefId");if(!o||!sg(o))return{kind:"unsupported"};let a=_r(Xl(o));if(!a)return{kind:"unsupported"};let s=ag(t[i],"PageInput");if(s&&!sg(s))return{kind:"unsupported"};let l=s?Xl(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=eu;function Re(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function dg(e){if(e===void 0)return;let t;try{t=JSON.parse(e)}catch{return}return Re(t)&&Re(t.data)?t.data:void 0}B.inputDataFrom=dg;function fg(e){var t;return(t=e.formType)!==null&&t!==void 0?t:"Main"}B.effectiveFormType=fg;function pg(e){return KS(e.classId!==void 0?e.classId:cg(e.bag,"classid"))}B.effectiveClassId=pg;function Td(e){return!e.fieldName}B.isUnbound=Td;function mg(e,t){if(fg(e)!=="Main"||!Td(t)||pg(t)!==B.CUSTOM_CONTROL_CLASS_ID)return!1;let r=Oi(t),n=r?Xo(e.bag,r):void 0;return n!==void 0&&eu(n).kind==="projectable"}B.isRecognizedEmbed=mg;function Q9(e){for(let t of JS(e)){let r=t.control;if(!r||!mg(e,r))continue;let n=eu(Xo(e.bag,Oi(r)));if(n.kind!=="projectable")continue;let i=dg(n.pageInputRaw);r.genPage=i===void 0?{pageId:n.pageId}:{pageId:n.pageId,inputData:i}}}B.projectGenPageEmbeds=Q9;var X9=new Set(["pageId","inputData"]);function Ql(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 Z9(e){var t;let r=[],n=c=>d=>r.push(`${c}: ${d}`),i=new z9.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=_r(s[c].getAttribute("uniqueid"));d&&a.add(d)}let l=Ql(o).find(c=>c.nodeName==="controlDescriptions"),u=new Map;for(let c of l?Ql(l):[]){let d=_r(c.getAttribute("forControl"));if(!(c.nodeName!=="controlDescription"||!d||!a.has(d)))for(let f of Ql(c)){if(f.nodeName!=="customControl"||f.getAttribute("name")!==B.GENPAGE_CONTROL_NAME)continue;let m=Ql(f).find(g=>g.nodeName==="parameters"),p=m?Ql(m).find(g=>g.nodeName==="RefId"):void 0,h=p&&p.getAttribute("static")==="true"?_r(p.textContent):"";h&&u.set(`${d}|${h}`,[d,h])}}return[...u.values()]}B.activeEmbedBindings=Z9;function Sd(e){return{n:`<${e}`,a:[],c:[]}}function lg(e,t){return{n:e,a:[["type","SingleLine.Text"],["static","true"]],c:[Sd(t)]}}function ug(e,t){let r={};if(t!==void 0)try{let n=JSON.parse(t);Re(n)&&(r=n)}catch{}return JSON.stringify({...r,data:e})}function eW(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:[lg("RefId",t),...r===void 0?[]:[lg("PageInput",ug(r))]]}]}))}}function _d(e,t){if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((r,n)=>_d(r,t[n]));if(Re(e)&&Re(t)){let r=Object.keys(e);return r.length===Object.keys(t).length&&r.every(n=>n in t&&_d(e[n],t[n]))}return e===t}function tW(e,t,r){let n=Se(e.c).find(u=>u?.n==="parameters");if(!n||!Array.isArray(n.c))return;let i=n.c.find(u=>u?.n==="RefId");i&&_r(Xl(i))!==t&&(i.c=[Sd(t)]);let o=n.c.findIndex(u=>u?.n==="PageInput"),a=o>=0?n.c[o]:void 0,s=a?Xl(a):void 0;if(_d(dg(s),r))return;if(r!==void 0){a?a.c=[Sd(ug(r,s))]:n.c.push(lg("PageInput",ug(r)));return}let l=JSON.parse(s);delete l.data,Object.keys(l).length===0?n.c.splice(o,1):a.c=[Sd(JSON.stringify(l))]}function hg(e){let t=Se(e?.c),r=t.reduce((n,i)=>i.i>n?i.i:n,-1);return Math.max(r,t.length)+1}B.embedAppendIndex=hg;function rW(e,t){var r;let n=e.bag,i=ds(n);if(i&&t){let o=Nd(t),a=Nd(e),s=K9(t),l=J9(e),u=Se(i.node.c),c=[];for(let d of u){let f=d?.n==="controlDescription"&&Zl(d).length>0?_r(co(d,"forControl")):"";if(!f||!o.has(f))c.push(d);else if(a.has(f))if(s.has(f)&&Y9(l.get(f))&&_d(d,Xo(t.bag,f))){let m=Se(d.c).filter(p=>!YS(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 Sn(e)){let a=o.control;if(!Zo(a)||!Re(a.genPage))continue;let s=_r(a.genPage.pageId),l=a.genPage.inputData,u=Oi(a);if(!u){if(tu(a)!==void 0)continue;u=gg(a)}let c=Xo(n,u);if(c){for(let m of Zl(c))tW(m,s,l);continue}i||(i={i:hg(n),node:{n:"controlDescriptions",a:[],c:[]}},n.c.push(i));let d=((r=cg(a.bag,"uniqueid"))!==null&&r!==void 0?r:"").trim(),f=d.startsWith("{")?d:`{${u}}`;i.node.c.push(eW(f,s,l))}}B.reconcileEmbedDescriptions=rW;function nW(e,t){let r=ds(e.bag),n=t!==void 0&&(r===void 0||JSON.stringify(r.node)!==JSON.stringify(t)),i=Sn(e).some(({cell:a})=>Zo(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=ds(o.bag);s?s.node=a:(o.bag=Re(o.bag)?o.bag:{a:[],c:[]},o.bag.c=Se(o.bag.c),o.bag.c.push({i:hg(e.bag),node:a}))}for(let{cell:a}of Sn(o))Zo(a.control)&&(QS(a.control),XS(a));return o}B.commitEmbedState=nW;function iW(e){if(Sn(e).some(({cell:r})=>Zo(r.control)))return!0;let t=ds(e.bag);return Se(t?.node.c).some(r=>r?.n==="controlDescription"&&Zl(r).length>0)}B.mayCommitEmbedState=iW;function QS(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=QS;function XS(e){e.rowspan===void 0&&(e.rowspan=B.GENPAGE_EMBED_ROWSPAN)}B.applyEmbedCellDefaults=XS;function Zo(e){return Re(e)&&e.genPage!==void 0}B.hasGenPage=Zo;function jS(e){return Zo(e.control)&&(!e.control.id||!e.id||tu(e.control)===void 0)}function tu(e){let t=Se(Re(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=tu;function oW(e){if(!Sn(e).some(({cell:r})=>jS(r)))return e;let t=JSON.parse(JSON.stringify(e));for(let{cell:r}of Sn(t)){if(!jS(r))continue;let n=r.control;n.id||(n.id=(0,ig.newId)()),r.id||(r.id=(0,ig.newId)()),tu(n)===void 0&&gg(n)}return t}B.mintEmbedIdentity=oW;function gg(e){let t=(0,ig.newId)(),r=`{${t}}`;if(!Re(e.bag))return e.bag={a:[["uniqueid",r]],c:[]},t;let n=Se(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=Se(e.bag.c),t}B.setUniqueId=gg;function HS(e){return e===null?"null":Array.isArray(e)?"an array":typeof e}function aW(e){let t=Se(e.c).filter(r=>r?.n==="customControl").map(r=>{var n,i;return(i=(n=co(r,"name"))!==null&&n!==void 0?n:co(r,"id"))!==null&&i!==void 0?i:"unnamed"});return[...new Set(t)].join(", ")||"no custom control"}function sW(e){let t=[],r;for(let{cell:n,pointer:i}of Sn(e)){let o=n.control;if(!Re(o))continue;let a=`${i}/control`;if(o.genPage===void 0){lW(e,o,a,t);continue}r=r??Nd(e),uW(e,o,a,r,t)}return t}B.genPageEmbedIssues=sW;function lW(e,t,r,n){if(!mg(e,t))return;let i=eu(Xo(e.bag,Oi(t)));n.push((0,nn.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 uW(e,t,r,n,i){var o;let a=`${r}/genPage`,s=t.genPage;if(!Re(s))i.push((0,nn.issue)(a,"genpage-embed-shape",`genPage must be an object { pageId, inputData? }, got ${HS(s)}.`+(s===null?" To remove an embed, remove the cell (or set the cell's control to null).":"")));else{(typeof s.pageId!="string"||!_r(s.pageId))&&i.push((0,nn.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&&!Re(s.inputData)&&i.push((0,nn.issue)(`${a}/inputData`,"genpage-embed-shape",`genPage.inputData must be a JSON object \u2014 the page reads it as pageInput.data \u2014 got ${HS(s.inputData)}`));for(let m of Object.keys(s))X9.has(m)||i.push((0,nn.issue)(j9.JsonPointer.append(a,m),"genpage-embed-unknown-key",`'${m}' is not a genPage property (pageId, inputData), and would be SILENTLY DROPPED at serialization.`))}Td(t)||i.push((0,nn.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&&KS(t.classId)!==B.CUSTOM_CONTROL_CLASS_ID&&i.push((0,nn.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=fg(e);l!=="Main"&&i.push((0,nn.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=tu(t);u!==void 0&&!_r(u)&&i.push((0,nn.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=Oi(t);if(!c)return;let d=Xo(e.bag,c),f=d?eu(d):void 0;d&&f?.kind==="none"?i.push((0,nn.issue)(a,"genpage-embed-other-control",`this control is already bound to another custom control (${aW(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,nn.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,nn.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 bg=v(fo=>{"use strict";Object.defineProperty(fo,"__esModule",{value:!0});fo.findMissingGenPages=fo.GENPAGE_LOOKUP_CHUNK=void 0;var cW=Lt(),yg=le();fo.GENPAGE_LOOKUP_CHUNK=50;async function dW(e,t,r){let n=[...new Set(t.map(o=>(0,yg.normalizeGuid)(o,"uxagentprojectid")))],i=new Set;for(let o=0;o<n.length;o+=fo.GENPAGE_LOOKUP_CHUNK){let a=n.slice(o,o+fo.GENPAGE_LOOKUP_CHUNK),s="/uxagentprojects/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,yg.odataQuery)([["$select","uxagentprojectid"],["$filter",a.map(u=>`uxagentprojectid eq ${u}`).join(" or ")]]),l=await(0,cW.collectPages)(e,s,r);for(let u of l){let c=u.uxagentprojectid;typeof c=="string"&&c.trim()!==""&&i.add((0,yg.normalizeGuid)(c,"uxagentprojectid"))}}return n.filter(o=>!i.has(o))}fo.findMissingGenPages=dW});var ru=v(_t=>{"use strict";Object.defineProperty(_t,"__esModule",{value:!0});_t.assertSystemFormKind=_t.readSystemFormType=_t.decodeCode=_t.assertSystemFormRecordKind=_t.describeSystemFormType=_t.systemFormKindOf=_t.SYSTEMFORM_KIND_MISMATCH_CODE=void 0;var eN=Q(),fW=ye(),ZS=le();_t.SYSTEMFORM_KIND_MISMATCH_CODE="SYSTEMFORM_KIND_MISMATCH";var pW={0:"dashboard",10:"dashboard",2:"form",6:"form",7:"form",11:"form"},mW={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 Id(e){return Number.isInteger(e)?pW[e]:void 0}_t.systemFormKindOf=Id;function tN(e){var t;return Number.isFinite(e)?`a ${(t=mW[e])!==null&&t!==void 0?t:"systemform"} (type ${e})`:"a systemform whose type could not be read"}_t.describeSystemFormType=tN;function rN(e,t,r,n){let i=tN(r),o=Id(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 hW(e,t,r,n){let i=vg(e?.type);if(Id(i)!==r)throw new eN.SdkError(_t.SYSTEMFORM_KIND_MISMATCH_CODE,rN(t,r,i,n));return i}_t.assertSystemFormRecordKind=hW;function vg(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}_t.decodeCode=vg;async function gW(e,t){return await nN(e,t,!1)}_t.readSystemFormType=gW;async function yW(e,t){return nN(e,t,!0)}async function nN(e,t,r){var n;let o=`/systemforms(${(0,ZS.normalizeGuid)(t,"formId")})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,ZS.odataQuery)([["$select","type"]]),a=await e.get(o);if(!(r&&a.status===404))return(0,fW.ensureSuccess)(a,e.apiUrl(o)),vg((n=a.body)===null||n===void 0?void 0:n.type)}async function bW(e,t,r){let n=await yW(e,t);if(!(n===void 0||Id(n)===r))throw new eN.SdkError(_t.SYSTEMFORM_KIND_MISMATCH_CODE,rN(t,r,n,"delete"))}_t.assertSystemFormKind=bW});var Cg=v(Wr=>{"use strict";Object.defineProperty(Wr,"__esModule",{value:!0});Wr.patchSystemForm=Wr.assertSystemFormContentUnchanged=Wr.readSystemFormRowEtag=Wr.unpublishedSystemFormPath=Wr.FORM_TYPE_IMMUTABLE_CODE=void 0;var on=ye(),vW=le(),Od=Q(),po=ru();Wr.FORM_TYPE_IMMUTABLE_CODE="FORM_TYPE_IMMUTABLE";function wg(e,t="formid"){return`/systemforms(${e})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,vW.odataQuery)([["$select",t]])}Wr.unpublishedSystemFormPath=wg;function iN(e,t){return(0,on.readRowEtag)(e,"systemforms","formid",t)}Wr.readSystemFormRowEtag=iN;async function oN(e,t,r,n,i){(0,on.requireEtag)(i,r,t);let o=(0,on.ensureSuccess)(await e.get(n),e.apiUrl(n)),a=(0,po.assertSystemFormRecordKind)(o.body,t,r,"write"),s=(0,on.readEtag)(o);if(s===null)throw new Od.SdkError(on.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 Od.SdkError(on.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}Wr.assertSystemFormContentUnchanged=oN;async function wW(e,t,r,n,i,o){(0,on.requireEtag)(i,r,t);let a=await iN(e,t);if(a===null)throw new Od.SdkError(on.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 oN(e,t,r,wg(t,"formid,type"),i);if(n.type!==void 0&&(0,po.decodeCode)(n.type)!==s)throw new Od.SdkError(Wr.FORM_TYPE_IMMUTABLE_CODE,`Refusing to push ${r} '${t}': it would change it from ${(0,po.describeSystemFormType)(s)} to ${(0,po.describeSystemFormType)((0,po.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,on.echoWrite)("formid",{"If-Match":a}),u=`/systemforms(${t})${l.query}`;return(0,on.ensureSuccess)(await e.patch(u,n,l.options),e.apiUrl(u)),CW(e,t,r,o)}Wr.patchSystemForm=wW;async function CW(e,t,r,n){let i;try{let o=wg(t,n.select),a=(0,on.ensureSuccess)(await e.get(o),e.apiUrl(o)),s=a.body,l=(0,on.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,po.decodeCode)(s?.type),m=(0,po.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,po.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 _g=v($t=>{"use strict";Object.defineProperty($t,"__esModule",{value:!0});$t.getFormSecurityRoles=$t.setFormSecurityRoles=$t.formApi=$t.readPrimaryCreateRefusal=$t.FORM_GENPAGE_TARGET_UNVERIFIABLE=$t.FORM_GENPAGE_TARGET_NOT_FOUND=void 0;var EW=Lt(),Tt=ye(),an=le(),ea=Q(),Eg=uo(),sN=Dd(),AW=bg(),Ag=Cg(),nu=ru();$t.FORM_GENPAGE_TARGET_NOT_FOUND="FORM_GENPAGE_TARGET_NOT_FOUND";$t.FORM_GENPAGE_TARGET_UNVERIFIABLE="FORM_GENPAGE_TARGET_UNVERIFIABLE";var lN="formid,formxml,name,type,objecttypecode,formpresentation,formactivationstate,uniquename,description,versionnumber",SW={select:lN,required:["name","type","objecttypecode"]},NW="formid,name,type,objecttypecode",_W=2,TW={Main:_W,QuickView:6,QuickCreate:7,Card:11},uN=new WeakMap;function DW(e){return typeof e=="object"&&e!==null?uN.get(e):void 0}$t.readPrimaryCreateRefusal=DW;$t.formApi={async get(e,t){let r=(0,an.normalizeGuid)(t,"id"),n=`/systemforms(${r})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,an.odataQuery)([["$select",lN]]),i=(0,Tt.ensureSuccess)(await e.get(n),e.apiUrl(n));return(0,nu.assertSystemFormRecordKind)(i.body,r,"form","fetch"),{raw:i.body,etag:(0,Tt.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=>TW[u]))],a=[i.length===1?`type eq ${i[0]}`:`(${i.map(u=>`type eq ${u}`).join(" or ")})`];t?.entityLogicalName&&a.push(`objecttypecode eq '${(0,an.odataLiteral)(t.entityLogicalName)}'`);let s=`/systemforms${(0,an.odataQuery)([["$select",NW],["$filter",a.join(" and ")]])}`;return(await(0,EW.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=aN(t);n!==void 0&&await cN(e,Ng(n,"payload"),[]);let i=(0,Tt.echoWrite)("formid"),o=`/systemforms${i.query}`,a=(0,Tt.withClientMintedId)(t,"formid",r),s=Object.freeze({...a}),l=await(0,Tt.resendDeadlockVictim)(()=>e.post(o,{...s},i.options));try{(0,Tt.ensureSuccess)(l,e.apiUrl(o))}catch(u){throw typeof u=="object"&&u!==null&&uN.set(u,{status:l.status,sent:s,desiredId:r}),u}return{id:(0,Tt.resolveCreatedId)(l,"formid","form",r),etag:(0,Tt.readEtag)(l)}},async update(e,t,r,n){let i=(0,an.normalizeGuid)(t,"id"),o=aN(r);return o!==void 0&&await OW(e,i,o,n),(0,Ag.patchSystemForm)(e,i,"form",r,n,SW)},readContentThenToken(e,t){return $t.formApi.get(e,t)},async delete(e,t){let r=(0,an.normalizeGuid)(t,"id");return await(0,nu.assertSystemFormKind)(e,r,"form"),(0,Tt.deleteRecord)(e,"systemforms",r)}};var Sg="DisplayConditions";async function IW(e,t,r){var n,i,o,a;if(r.everyone&&r.roleIds&&r.roleIds.length>0)throw new ea.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,an.normalizeGuid)(t,"formId"),l=`/systemforms(${s})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,an.odataQuery)([["$select","formid,formxml,type"]]),u=(0,Tt.ensureSuccess)(await e.get(l),e.apiUrl(l));(0,nu.assertSystemFormRecordKind)(u.body,s,"form","set the security roles of");let c=(0,Tt.readEtag)(u),d=u.body,f=d?.formxml;if(!f)throw new ea.InvalidArgumentError(`form '${s}' returned no formxml, so its roles cannot be set`);let m=(0,Eg.parseXmlRoot)(f,"<form/>"),p=m.ownerDocument;if(!p)throw new ea.InvalidArgumentError(`form '${s}' produced no owner document`);let h=dN(m,Sg),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 ea.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(Sg),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,an.normalizeGuid)(x,"roleId")}}`),I.appendChild(K)}m.appendChild(I)}let S=(0,Eg.serializeNode)(m);await(0,Ag.assertSystemFormContentUnchanged)(e,s,"form",l,c);let O=await(0,Ag.readSystemFormRowEtag)(e,s),k=`/systemforms(${s})`;(0,Tt.ensureSuccess)(await e.patch(k,{formxml:S},{headers:{"Content-Type":"application/json","If-Match":(0,Tt.requireEtag)(O,"form",s)}}),e.apiUrl(k))}$t.setFormSecurityRoles=IW;function aN(e){let t=e?.formxml;return typeof t=="string"&&t.includes(sN.GENPAGE_CONTROL_NAME)?t:void 0}function Ng(e,t){try{return(0,sN.activeEmbedBindings)(e)}catch(r){throw new ea.SdkError($t.FORM_GENPAGE_TARGET_UNVERIFIABLE,`Refusing to push the form: the ${t} formxml could not be parsed, so the generative pages it embeds cannot be verified (${r instanceof Error?r.message:String(r)}).`)}}async function cN(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,AW.findMissingGenPages)(e,i,"form generative-page preflight");if(o.length>0)throw new ea.SdkError($t.FORM_GENPAGE_TARGET_NOT_FOUND,`Refusing to push the form: it embeds generative page(s) ${o.map(a=>`'${a}'`).join(", ")} that do not exist in this environment. Push the page before the form that embeds it.`)}async function OW(e,t,r,n){var i;(0,Tt.requireEtag)(n,"form",t);let o=`/systemforms(${t})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,an.odataQuery)([["$select","formid,formxml,type"]]),a=(0,Tt.ensureSuccess)(await e.get(o),e.apiUrl(o));(0,nu.assertSystemFormRecordKind)(a.body,t,"form","write");let s=(0,Tt.readEtag)(a);if(s===null||s!==n)throw new ea.SdkError(Tt.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!==""?Ng(l,"server"):[];await cN(e,Ng(r,"payload"),u)}function dN(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 PW(e,t){var r,n;let i=(0,an.normalizeGuid)(t,"formId"),o=`/systemforms(${i})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,an.odataQuery)([["$select","formid,formxml,type"]]),a=(0,Tt.ensureSuccess)(await e.get(o),e.apiUrl(o));(0,nu.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,Eg.parseXmlRoot)(s,"<form/>"),u=dN(l,Sg);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)}:{}}}$t.getFormSecurityRoles=PW});var Tg=v(be=>{"use strict";Object.defineProperty(be,"__esModule",{value:!0});be.deleteSolution=be.getDeploymentSettingsTemplate=be.importSolution=be.exportSolution=be.removeSolutionComponent=be.addSolutionComponent=be.setSolutionVersion=be.createSolution=be.createPublisher=be.getSolution=be.fetchSolutionComponents=be.resolveGenPageComponentType=be.SolutionComponentType=void 0;var RW=Lt(),Ft=ye(),ur=le(),kW=pt(),Yt=Q();be.SolutionComponentType={SavedQuery:26,Workflow:29,SavedQueryVisualization:59,SystemForm:60,AppModule:80};var LW=[be.SolutionComponentType.SavedQuery,be.SolutionComponentType.Workflow,be.SolutionComponentType.SavedQueryVisualization,be.SolutionComponentType.SystemForm,be.SolutionComponentType.AppModule],fN="uxagentproject",pN=new WeakMap;async function vN(e){var t;let r=pN.get(e);if(r!==void 0)return r;let n=`/EntityDefinitions(LogicalName='${fN}')${(0,ur.odataQuery)([["$select","ObjectTypeCode"]])}`,i=await e.get(n);if(i.status===404)return;(0,Ft.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 Yt.SdkError("GENPAGE_COMPONENT_TYPE_UNRESOLVED",`A generative page's solution component type \u2014 the ObjectTypeCode of '${fN}' \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 pN.set(e,o),o}be.resolveGenPageComponentType=vN;var mN=1,hN=0;async function $W(e,t){let r=(0,ur.normalizeGuid)(t,"solutionId"),n=await vN(e),o=[mN,...LW,...n===void 0?[]:[n]].map(c=>`componenttype eq ${c}`).join(" or "),a=`/solutioncomponents${(0,ur.odataQuery)([["$select","objectid,componenttype,rootcomponentbehavior"],["$filter",`_solutionid_value eq ${r} and (${o})`]])}`,s=await(0,RW.collectPages)(e,a,"fetchSolutionComponents"),l=[];for(let c of s){if(typeof c.objectid!="string")continue;let d=Number(c.componenttype);if(d===mN){let f=c.rootcomponentbehavior;(f===hN||f===String(hN))&&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))}be.fetchSolutionComponents=$W;function xW(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 FW(e,t){var r,n,i,o,a,s,l,u,c,d;let f=String(t??"").trim();if(!f)throw new Yt.InvalidArgumentError("getSolution: a solution unique name or id is required.");let m=xW(f)?`solutionid eq ${(0,ur.normalizeGuid)(f,"solutionId")}`:`uniquename eq '${(0,ur.odataLiteral)(f)}'`,p=`/solutions${(0,ur.odataQuery)([["$select","solutionid,uniquename,friendlyname,version,ismanaged"],["$expand","publisherid($select=publisherid,uniquename,customizationprefix,customizationoptionvalueprefix)"],["$filter",m]])}`,b=((n=(r=(0,Ft.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 Yt.InvalidArgumentError(`No solution found for '${t}'.`);let w=b.publisherid;if(!w?.publisherid)throw new Yt.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 Yt.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,ur.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,ur.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}}be.getSolution=FW;async function MW(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,Ft.ensureSuccess)(await(0,Ft.resendDeadlockVictim)(()=>e.post("/publishers",{...n})),e.apiUrl("/publishers")),o=(0,Ft.readCreatedId)(i,"publisherid");if(!o)throw new Yt.InvalidArgumentError(`Dataverse did not return an id for publisher '${t.uniqueName}'`);return{id:o,uniqueName:t.uniqueName}}be.createPublisher=MW;async function UW(e,t){var r;let n=(0,ur.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,Ft.ensureSuccess)(await e.post("/solutions",i),e.apiUrl("/solutions")),a=(0,Ft.readCreatedId)(o,"solutionid");if(!a)throw new Yt.InvalidArgumentError(`Dataverse did not return an id for solution '${t.uniqueName}'`);return{id:a,uniqueName:t.uniqueName}}be.createSolution=UW;async function BW(e,t,r){let i=`/solutions(${(0,ur.normalizeGuid)(t,"solutionId")})`;(0,Ft.ensureSuccess)(await e.patch(i,{version:r}),e.apiUrl(i))}be.setSolutionVersion=BW;async function qW(e,t){var r;let i={ComponentId:(0,ur.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,Ft.ensureSuccess)(await e.post("/AddSolutionComponent",i),e.apiUrl("/AddSolutionComponent"))}be.addSolutionComponent=qW;async function VW(e,t,r,n){let o={SolutionComponent:{"@odata.type":"Microsoft.Dynamics.CRM.solutioncomponent",solutioncomponentid:(0,ur.normalizeGuid)(t,"componentId")},ComponentType:r,SolutionUniqueName:n};(0,Ft.ensureSuccess)(await e.post("/RemoveSolutionComponent",o),e.apiUrl("/RemoveSolutionComponent"))}be.removeSolutionComponent=VW;async function GW(e,t){var r,n;let i={SolutionName:t.solutionName,Managed:(r=t.managed)!==null&&r!==void 0?r:!1},a=(n=(0,Ft.ensureSuccess)(await e.post("/ExportSolution",i),e.apiUrl("/ExportSolution")).body)===null||n===void 0?void 0:n.ExportSolutionFile;if(!a)throw new Yt.InvalidArgumentError(`ExportSolution returned no file for '${t.solutionName}'`);return{base64:a}}be.exportSolution=GW;async function WW(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 Yt.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:t5(t.deploymentSettings),i={OverwriteUnmanagedCustomizations:t.overwriteUnmanagedCustomizations,PublishWorkflows:t.publishWorkflows,CustomizationFile:t.base64,ImportJobId:t.importJobId?(0,ur.normalizeGuid)(t.importJobId,"importJobId"):(0,kW.newId)()};if(!n)return(0,Ft.ensureSuccess)(await e.post("/ImportSolution",i),e.apiUrl("/ImportSolution")),{};if(n.variables.length===0&&n.references.length===0)return(0,Ft.ensureSuccess)(await e.post("/ImportSolution",i),e.apiUrl("/ImportSolution")),{appliedSettings:{environmentVariables:[],connectionReferences:[]}};let o=[];try{let a=await wN(e,t.base64,iu,o),{parameters:s,applied:l}=r5(a,n);return i.ComponentParameters=s,(0,Ft.ensureSuccess)(await e.post("/ImportSolution",i),e.apiUrl("/ImportSolution")),{appliedSettings:l,...o.length>0?{warnings:o}:{}}}catch(a){throw(0,Yt.withCleanupWarnings)(a,o)}}be.importSolution=WW;var iu="importSolution",gN="getDeploymentSettingsTemplate";async function zW(e,t){var r;let n=t?.base64;if(typeof n!="string"||n.length===0)throw new Yt.InvalidArgumentError(`${gN}: '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 wN(e,n,gN,i),a=Pd(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=Pd(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,Yt.withCleanupWarnings)(o,i)}}be.getDeploymentSettingsTemplate=zW;function Pd(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 ta(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function xt(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 wN(e,t,r,n){var i;let a=(i=(0,Ft.ensureSuccess)(await e.post("/StageSolution",{CustomizationFile:t}),e.apiUrl("/StageSolution")).body)===null||i===void 0?void 0:i.StageSolutionResults;try{return HW(a,r)}finally{await jW(e,ta(a)?a.StageSolutionUploadId:void 0,n)}}async function jW(e,t,r){let n;try{n=(0,ur.normalizeGuid)(t,"StageSolutionUploadId")}catch{r.push(`StageSolution's reply named no usable staging upload id (${xt(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,Ft.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 lr(e,t){return new Yt.SdkError("SOLUTION_STAGING_UNREADABLE",`${e}: StageSolution's reply could not be read \u2014 ${t}.${e===iu?" Nothing was imported.":""}`)}function yN(e){return!Array.isArray(e)||e.length===0?"none":`${e.slice(0,5).map(r=>ta(r)&&typeof r.Message=="string"?r.Message:xt(r,200)).join("; ")}${e.length>5?` (+${e.length-5} more)`:""}`}function HW(e,t){if(!ta(e))throw lr(t,`it holds no StageSolutionResults (${xt(e,60)})`);let r=e.StageSolutionStatus;if(r==="Failed"||r===0)throw new Yt.SdkError("SOLUTION_STAGING_FAILED",`${t}: the package did not pass StageSolution in this environment (status ${xt(r)}). Missing dependencies: ${yN(e.MissingDependencies)}. Validation: ${yN(e.SolutionValidationResults)}.${t===iu?" 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 lr(t,`StageSolutionStatus is ${xt(r)}, neither "Passed" nor "Failed"`);let n=e.SolutionComponentsDetails;if(!Array.isArray(n))throw lr(t,`SolutionComponentsDetails is not a list (${xt(n,60)})`);let i=[],o=[],a=new Set,s=new Set;return n.forEach((l,u)=>{let c=`SolutionComponentsDetails[${u}]`;if(!ta(l))throw lr(t,`${c} is not an object`);if(typeof l.ComponentTypeName!="string")throw lr(t,`${c}.ComponentTypeName is not a string`);let d=l.ComponentTypeName.toLowerCase();if(d!=="environmentvariabledefinition"&&d!=="connectionreference")return;let f=KW(l.Attributes,`${c}.Attributes`,t),m=(p,h)=>{let g=f.get(p);if(g==null){if(h)throw lr(t,`${c}.${p} is missing`);return}if(typeof g!="string"||h&&g.length===0)throw lr(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 lr(t,`${c}.schemaname '${p}' is listed twice`);a.add(p.toLowerCase());let h=m("defaultvalue",!1),g=JW(f.get("type"),`${c}.type`,t),b=YW(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 lr(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 KW(e,t,r){if(!ta(e)||!Array.isArray(e.Keys)||!Array.isArray(e.Values))throw lr(r,`${t} is not { Keys: [...], Values: [...] }`);let{Keys:n,Values:i}=e;if(n.length!==i.length)throw lr(r,`${t} has ${n.length} keys but ${i.length} values`);let o=new Map;return n.forEach((a,s)=>{if(typeof a!="string")throw lr(r,`${t}.Keys[${s}] is not a string`);if(o.has(a))throw lr(r,`${t}.Keys lists '${a}' twice`);o.set(a,i[s])}),o}function JW(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 lr(r,`${t} is not a whole number (${xt(e,40)})`)}}function YW(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 lr(r,`${t} is not true or false (${xt(e,40)})`)}}var QW=new Set(["EnvironmentVariables","ConnectionReferences","Workflows","CanvasApps","CopilotAgents","$schema"]),XW=["Workflows","CanvasApps","CopilotAgents"],ZW=new Set(["SchemaName","Value","DefaultValue","TypeId","IsRequired","Name"]),e5=new Set(["LogicalName","ConnectionId","ConnectorId"]);function sr(e,t){return new Yt.InvalidArgumentError(`${iu}: deploymentSettings is not a deployment-settings file this SDK applies \u2014 ${e} ${t}. Nothing was imported.`)}function t5(e){let t="deploymentSettings";if(!ta(e))throw sr(t,`must be an object \u2014 the settings file, parsed (it was ${xt(e,40)})`);for(let l of Object.keys(e))if(!QW.has(l))throw sr(`${t}.${l}`,"is not part of the format (EnvironmentVariables, ConnectionReferences; Workflows, CanvasApps and CopilotAgents only empty; $schema)");for(let l of XW){let u=e[l];if(u!==void 0&&!(Array.isArray(u)&&u.length===0))throw sr(`${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 sr(`${t}.$schema`,"must be a string");let r=l=>{let u=e[l];if(u===void 0)return[];if(!Array.isArray(u))throw sr(`${t}.${l}`,`must be a list (it was ${xt(u,40)})`);return u.map((c,d)=>{if(!ta(c))throw sr(`${t}.${l}[${d}]`,`must be an object (it was ${xt(c,40)})`);return c})},n=(l,u,c)=>{let d=l[u];if(typeof d!="string"||d.length===0)throw sr(c,`must be a non-empty string (it was ${xt(d,40)})`);if(d.trim()!==d)throw sr(c,`must not begin or end with whitespace (it was ${xt(d,60)})`);return d},i=(l,u,c)=>{if(l.has(u.toLowerCase()))throw sr(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(!ZW.has(f))throw sr(`${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 sr(`${c}.Value`,`must be a string \u2014 empty to override nothing (it was ${xt(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(!e5.has(m))throw sr(`${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 sr(`${c}.ConnectionId`,`must be a string \u2014 empty to bind nothing (it was ${xt(f,40)})`);if(f.trim()!==f)throw sr(`${c}.ConnectionId`,`must not begin or end with whitespace (it was ${xt(f,60)})`);if(l.ConnectorId!==void 0&&typeof l.ConnectorId!="string")throw sr(`${c}.ConnectorId`,`must be a string (it was ${xt(l.ConnectorId,40)})`);f.length>0&&o.references.push({name:d,connectionId:f,...l.ConnectorId?{connectorId:l.ConnectorId}:{}})}),o}function bN(e,t=20){return e.length===0?"none":`${e.slice(0,t).join(", ")}${e.length>t?` (+${e.length-t} more)`:""}`}function r5(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=bN(Pd(e.variables,d=>d.SchemaName).map(d=>d.SchemaName)),c=bN(Pd(e.references,d=>d.LogicalName).map(d=>d.LogicalName));throw new Yt.InvalidArgumentError(`${iu}: 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 n5(e,t){let n=`/solutions(${(0,ur.normalizeGuid)(t,"solutionId")})`;(0,Ft.ensureSuccess)(await e.delete(n),e.apiUrl(n))}be.deleteSolution=n5});var _N=v(mt=>{"use strict";Object.defineProperty(mt,"__esModule",{value:!0});mt.recoverFormCreate=mt.solutionMembershipProblem=mt.formWriteMismatches=mt.validateExistingForm=mt.formExistsAtId=mt.isFormRecordAt=mt.MAIN_FORM_TYPE=void 0;var fs=le(),CN=Lt(),EN=Tg();mt.MAIN_FORM_TYPE=2;function Rd(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function kd(e){return e instanceof Error?e.message:String(e)}function Dg(e,t){if(typeof e!="string"||typeof t!="string")return!1;try{return(0,fs.normalizeGuid)(e,"a GUID")===(0,fs.normalizeGuid)(t,"a GUID")}catch{return!1}}function Ig(e,t){return Rd(e)&&Dg(e.formid,t)}mt.isFormRecordAt=Ig;async function i5(e,t){try{return Ig((await e()).raw,t)}catch{return!1}}mt.formExistsAtId=i5;function AN(e,t){let r=e.raw;if(!Rd(r))return{problem:"it is not a record"};if(!Ig(r,t))return{problem:"its formid is not the id this create sent"};if(r.type!==mt.MAIN_FORM_TYPE)return{problem:`its type is not ${mt.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}}mt.validateExistingForm=AN;function SN(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}mt.formWriteMismatches=SN;async function NN(e,t){let r=e.solutionName;if(r)try{let n=await(0,CN.collectPages)(e,`/solutions${(0,fs.odataQuery)([["$select","solutionid,uniquename"],["$filter",`uniquename eq '${(0,fs.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 Rd(i)&&typeof i.uniquename=="string"&&typeof i.solutionid=="string"&&i.uniquename.toLowerCase()===r.toLowerCase()&&(o=(0,fs.normalizeGuid)(i.solutionid,"solutionid")),o===void 0?`the configured solution '${r}' did not resolve to a valid solution of that name`:(await(0,CN.collectPages)(e,`/solutioncomponents${(0,fs.odataQuery)([["$select","objectid,componenttype,_solutionid_value"],["$filter",`_solutionid_value eq ${o} and componenttype eq ${EN.SolutionComponentType.SystemForm} and objectid eq ${t}`]])}`,"createRecovery solution membership")).some(l=>Rd(l)&&l.componenttype===EN.SolutionComponentType.SystemForm&&Dg(l.objectid,t)&&Dg(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 (${kd(n)})`}}mt.solutionMembershipProblem=NN;async function o5(e){try{return await a5(e)}catch(t){return{refused:`the recovery could not be completed (${kd(t)})`}}}mt.recoverFormCreate=o5;async function a5(e){let{client:t,read:r,sent:n,authoredFormType:i,project:o}=e;if(i!=="Main"||n.type!==mt.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 (${kd(f)})`}}let l=AN(s,a);if("problem"in l)return{refused:`the existing row cannot be trusted: ${l.problem}`};let u=SN(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 (${kd(f)})`}}let d=await NN(t,a);return d!==void 0?{refused:d}:{adopted:{artifact:c,etag:l.etag}}}});var $d=v(Ke=>{"use strict";Object.defineProperty(Ke,"__esModule",{value:!0});Ke.disassociateRecords=Ke.associateRecords=Ke.createRecordsBulk=Ke.upsertRecord=Ke.queryAllRecords=Ke.queryRecords=Ke.getRecord=Ke.deleteRecord=Ke.updateRecord=Ke.createRecord=void 0;var Og=Lt(),Nn=ye(),Qt=le(),ps=Q(),Yn=bd();function Ld(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 s5(e,t,r){let i=`/${await(0,Yn.resolveEntitySetName)(e,t)}`,o=(0,Nn.ensureSuccess)(await e.post(i,Ld(r)),e.apiUrl(i)),a=(0,Nn.readCreatedId)(o,`${t}id`);if(!a)throw new ps.InvalidArgumentError(`Dataverse did not return an id for the created '${t}' row`);return{id:a,entityType:t}}Ke.createRecord=s5;async function l5(e,t,r,n){let i=(0,Qt.normalizeGuid)(r,"id"),a=`/${await(0,Yn.resolveEntitySetName)(e,t)}(${i})`;(0,Nn.ensureSuccess)(await e.patch(a,Ld(n)),e.apiUrl(a))}Ke.updateRecord=l5;async function u5(e,t,r){let n=(0,Qt.normalizeGuid)(r,"id"),o=`/${await(0,Yn.resolveEntitySetName)(e,t)}(${n})`;(0,Nn.ensureSuccess)(await e.delete(o),e.apiUrl(o))}Ke.deleteRecord=u5;async function c5(e,t,r,n){let i=(0,Qt.normalizeGuid)(r,"id"),o=await(0,Yn.resolveEntitySetName)(e,t),a=(0,Qt.odataQuery)([["$select",n&&n.length>0?n.join(","):void 0]]),s=`/${o}(${i})${a}`,l=(0,Nn.ensureSuccess)(await e.get(s),e.apiUrl(s)),u=l.body;if(u===null||typeof u!="object"||Array.isArray(u))throw new ps.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,Og.describeMalformedValue)(u)}; refusing to read it as a row.`);return u}Ke.getRecord=c5;function d5(e){return e?.fetchXml?(0,Qt.odataQuery)([["fetchXml",e.fetchXml]]):(0,Qt.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 TN(e,t,r){var n;if(r?.paginate){if(r.top!==void 0)throw new ps.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 ps.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,Yn.resolveEntitySetName)(e,t)}${d5(r)}`;if(r?.paginate)return(0,Og.collectPages)(e,o,"queryRecords");let a=(0,Nn.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 ps.ConnectionError(e.apiUrl(o),a.status,`queryRecords: read returned a malformed page \u2014 expected an OData 'value' array but got ${(0,Og.describeMalformedValue)(s)}; refusing to read it as rows.`);return s}Ke.queryRecords=TN;async function f5(e,t,r){return TN(e,t,{...r,paginate:!0})}Ke.queryAllRecords=f5;function p5(e){if("id"in e)return`(${(0,Qt.normalizeGuid)(e.id,"id")})`;let t=typeof e.value=="string"?`'${(0,Qt.odataPathLiteral)(e.value)}'`:e.value;return`(${(0,Qt.assertODataName)(e.key,"alternate key name")}=${t})`}async function m5(e,t,r,n){let i=p5(r),a=`/${await(0,Yn.resolveEntitySetName)(e,t)}${i}`,s=(0,Nn.ensureSuccess)(await e.patch(a,Ld(n)),e.apiUrl(a)),l=s.status===201,u=(0,Nn.readCreatedId)(s,`${t}id`);return{id:u??("id"in r?(0,Qt.normalizeGuid)(r.id,"id"):""),created:l}}Ke.upsertRecord=m5;async function h5(e,t,r){var n,i;if(r.length===0)return[];let o=await(0,Yn.resolveEntitySetName)(e,t),a=r.map(c=>({"@odata.type":`Microsoft.Dynamics.CRM.${t}`,...Ld(c)})),s=`/${o}/Microsoft.Dynamics.CRM.CreateMultiple`,u=(i=(n=(0,Nn.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 ps.InvalidArgumentError(`CreateMultiple on '${t}' returned ${u.length} id(s) for ${r.length} row(s)`);return u}Ke.createRecordsBulk=h5;async function g5(e,t,r,n){let i=(0,Qt.normalizeGuid)(r,"id"),o=(0,Qt.normalizeGuid)(n.targetId,"targetId"),a=await(0,Yn.resolveEntitySetName)(e,t),s=await(0,Yn.resolveEntitySetName)(e,n.targetEntity),l=(0,Qt.assertODataName)(n.relationshipName,"relationshipName"),u=`/${a}(${i})/${l}/$ref`,c={"@odata.id":e.apiUrl(`/${s}(${o})`)};(0,Nn.ensureSuccess)(await e.post(u,c),e.apiUrl(u))}Ke.associateRecords=g5;async function y5(e,t,r,n,i){let o=(0,Qt.normalizeGuid)(r,"id"),a=(0,Qt.normalizeGuid)(i,"targetId"),s=await(0,Yn.resolveEntitySetName)(e,t),l=(0,Qt.assertODataName)(n,"relationshipName"),u=`/${s}(${o})/${l}(${a})/$ref`;(0,Nn.ensureSuccess)(await e.delete(u),e.apiUrl(u))}Ke.disassociateRecords=y5});var xd=v(sn=>{"use strict";Object.defineProperty(sn,"__esModule",{value:!0});sn.base64ToUtf8=sn.base64ToBytes=sn.bytesToBase64=sn.utf8ToBase64=sn.utf8ToBytes=void 0;var Pg=32768,Tr="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";function ou(){return globalThis}function DN(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 b5(e){let t="";for(let r=0;r<e.length;r+=Pg)t+=String.fromCharCode(...e.subarray(r,r+Pg));return t}function v5(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+="/":Tr.indexOf(n)>=0&&(t+=n)}for(t.length%4===1&&(t=t.slice(0,-1));t.length%4!==0;)t+="=";return t}function w5(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+=Tr[i>>18&63]+Tr[i>>12&63]+Tr[i>>6&63]+Tr[i&63]}let n=e.length-r;if(n===1){let i=e[r]<<16;t+=`${Tr[i>>18&63]}${Tr[i>>12&63]}==`}else if(n===2){let i=e[r]<<16|e[r+1]<<8,o=Tr[i>>18&63],a=Tr[i>>12&63],s=Tr[i>>6&63];t+=`${o}${a}${s}=`}return t}function C5(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=Tr.indexOf(e[o])<<18|Tr.indexOf(e[o+1])<<12|(e[o+2]==="="?0:Tr.indexOf(e[o+2]))<<6|(e[o+3]==="="?0:Tr.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 E5(e){let t=ou();if(t.Buffer)return new Uint8Array(t.Buffer.from(e,"utf8"));let r=t.TextEncoder;return r?new r().encode(e):DN(e)}sn.utf8ToBytes=E5;function A5(e){let t=ou();if(t.Buffer)return t.Buffer.from(e,"utf8").toString("base64");let r=t.TextEncoder;return IN(r?new r().encode(e):DN(e))}sn.utf8ToBase64=A5;function IN(e){let t=ou();return t.Buffer?t.Buffer.from(e).toString("base64"):t.btoa?t.btoa(b5(e)):w5(e)}sn.bytesToBase64=IN;function ON(e){let t=ou();if(t.Buffer)return new Uint8Array(t.Buffer.from(e,"base64"));let r=v5(e);if(t.atob){let n=t.atob(r);return Uint8Array.from(n,i=>i.charCodeAt(0))}return C5(r)}sn.base64ToBytes=ON;function S5(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>=Pg&&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 N5(e){let t=ou();return t.Buffer?t.Buffer.from(e,"base64").toString("utf8"):S5(ON(e))}sn.base64ToUtf8=N5});var $N=v(Qn=>{"use strict";Object.defineProperty(Qn,"__esModule",{value:!0});Qn.deleteWebResource=Qn.getWebResource=Qn.updateWebResource=Qn.createWebResource=void 0;var _5=Qr(),ra=ye(),au=le(),Rg=xd(),ms=Q(),T5={html:1,css:2,js:3,xml:4,png:5,jpg:6,gif:7,xsl:9,ico:10,svg:11,resx:12};function PN(e){if(e.contentBase64!==void 0)return e.contentBase64;if(e.content!==void 0)return(0,Rg.utf8ToBase64)(e.content)}async function RN(e,t){return(0,_5.publishWebResourceById)(e,t)}async function kN(e,t,r){try{await RN(e,t)}catch(n){let i=r?`Web resource '${r.name}' (${t})`:`Web resource ${t}`,o=`write its content again with updateWebResource('${t}', \u2026), which publishes and verifies again`+(r?" \u2014 it exists, and a second create of this name is refused":""),a=(0,ra.isConcurrencyLockRefusalError)(n)?`Another customization operation holds the environment's lock, and content has been observed missing after a publish the lock refused, so publishing again alone may not recover it: once the lock frees, ${o}.`:`Resolve that failure first, then ${o}.`;throw(0,ms.attachCause)(new ms.WebResourceUnverifiedError(t,r?.name,`${i} was written, but publishing it failed, so whether its published content is what was sent is unconfirmed (${n instanceof Error?n.message:String(n)}). ${a}`),n)}}function D5(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(e[r]!==t[r])return!1;return!0}async function LN(e,t,r,n){var i;let o=n?`Web resource '${n.name}' (${t})`:`Web resource ${t}`,a=n?`It exists: write its content again with updateWebResource('${t}', \u2026), which publishes and verifies again \u2014 a second create of this name is refused.`:"Writing it again is safe.",s=c=>new ms.WebResourceUnverifiedError(t,n?.name,`${o} ${c} ${a}`),l=`/webresourceset(${t})${(0,au.odataQuery)([["$select","content"]])}`,u;try{u=(i=(0,ra.ensureSuccess)(await e.get(l),e.apiUrl(l)).body)===null||i===void 0?void 0:i.content}catch(c){throw(0,ms.attachCause)(s("was written and published, but reading its published content back failed, so whether the write applied is unknown."),c)}if(typeof u!="string")throw s("was written and published, but the read-back carried no content, so whether the write applied is unknown.");if(!D5((0,Rg.base64ToBytes)(u),(0,Rg.base64ToBytes)(r)))throw s("was written and published, but the published content is not what was sent, so the write did not apply.")}async function I5(e,t){var r;let n=PN(t);if(n===void 0)throw new ms.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:T5[t.type],content:n};t.description&&(i.description=t.description);let o=(0,ra.ensureSuccess)(await e.post("/webresourceset",i),e.apiUrl("/webresourceset")),a=(0,ra.readCreatedId)(o,"webresourceid");if(!a)throw new ms.InvalidArgumentError(`Dataverse did not return an id for web resource '${t.name}'`);return t.publish!==!1&&(await kN(e,a,{name:t.name}),await LN(e,a,n,{name:t.name})),{id:a,name:t.name}}Qn.createWebResource=I5;async function O5(e,t,r){let n=(0,au.normalizeGuid)(t,"id"),i={},o=PN(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,ra.ensureSuccess)(await e.patch(a,i),e.apiUrl(a)),r.publish!==!1&&(o!==void 0?(await kN(e,n,void 0),await LN(e,n,o,void 0)):await RN(e,n))}Qn.updateWebResource=O5;async function P5(e,t){var r;let i=`/webresourceset(${(0,au.normalizeGuid)(t,"id")})${(0,au.odataQuery)([["$select","name,displayname,webresourcetype,content,description"]])}`;return(r=(0,ra.ensureSuccess)(await e.get(i),e.apiUrl(i)).body)!==null&&r!==void 0?r:{}}Qn.getWebResource=P5;async function R5(e,t){let n=`/webresourceset(${(0,au.normalizeGuid)(t,"id")})`;(0,ra.ensureSuccess)(await e.delete(n),e.apiUrl(n))}Qn.deleteWebResource=R5});var Fd=v(Dt=>{"use strict";Object.defineProperty(Dt,"__esModule",{value:!0});Dt.applyAppSettings=Dt.setAppSetting=Dt.readAppSettings=Dt.resolveSettingDefinitions=Dt.APP_SETTING_UNSET=Dt.APP_SETTING_OFF=Dt.APP_SETTING_ON=Dt.HEADER_AND_NAVIGATION_REFRESH=void 0;var hs=ye(),Pi=le();Dt.HEADER_AND_NAVIGATION_REFRESH="HeaderAndNavigationRefresh";Dt.APP_SETTING_ON="2";Dt.APP_SETTING_OFF="1";Dt.APP_SETTING_UNSET="0";function MN(e,t){return"/appsettings/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,Pi.odataQuery)([["$select",e],["$filter",t]])}async function UN(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,Pi.odataLiteral)(c)}'`).join(" or "),s=`/settingdefinitions${(0,Pi.odataQuery)([["$select","settingdefinitionid,uniquename,displayname"],["$filter",a]])}`,u=((n=(r=(0,hs.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}Dt.resolveSettingDefinitions=UN;async function k5(e,t){var r,n,i,o;let a=(0,Pi.normalizeGuid)(t,"App id"),s=MN("appsettingid,value,_settingdefinitionid_value",`_parentappmoduleid_value eq ${a}`),u=((n=(r=(0,hs.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,Pi.normalizeGuid)(h,"Setting definition id")}`).join(" or "),m=`/settingdefinitions${(0,Pi.odataQuery)([["$select","settingdefinitionid,uniquename,displayname"],["$filter",f]])}`,p=(0,hs.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}:{}}})}Dt.readAppSettings=k5;async function xN(e,t,r){var n,i,o;let a=MN("appsettingid,value",`_parentappmoduleid_value eq ${t} and _settingdefinitionid_value eq ${r}`),l=((i=(n=(0,hs.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 BN(e,t,r,n){let i=(0,Pi.normalizeGuid)(t,"App id"),a=(await UN(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,Pi.normalizeGuid)(s,"Setting definition id"),u=await xN(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,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 xN(e,i,l)}catch{p=void 0}if(p)return FN(e,p,n);throw f&&(0,hs.ensureSuccess)(f,e.apiUrl(c)),m}Dt.setAppSetting=BN;async function FN(e,t,r){if(t.value===r)return"unchanged";let n=`/appsettings(${(0,Pi.normalizeGuid)(t.id,"App setting id")})`;return(0,hs.ensureSuccess)(await e.patch(n,{value:r}),e.apiUrl(n)),"updated"}async function L5(e,t,r){var n;let i=[];for(let[o,a]of Object.entries(r??{}))try{await BN(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}Dt.applyAppSettings=L5});var Ud=v(Md=>{"use strict";Object.defineProperty(Md,"__esModule",{value:!0});Md.HEADER_NAV_BOOLEAN_RULE=void 0;Md.HEADER_NAV_BOOLEAN_RULE="headerAndNavigationRefresh-must-be-boolean"});var $g=v(ke=>{"use strict";Object.defineProperty(ke,"__esModule",{value:!0});ke.compileGenPage=ke.legacyEnumsNeeded=ke.createGenPageTypeScriptLoader=ke.acceptGenPageTypeScript=ke.isLoadableGenPageOutput=ke.runtimeTypesImportSpans=ke.GENPAGE_RUNTIME_TYPES_END=ke.GENPAGE_RUNTIME_TYPES_BEGIN=ke.GENPAGE_TYPESCRIPT_VERSION=void 0;var gs=Q();ke.GENPAGE_TYPESCRIPT_VERSION="5.8.3";ke.GENPAGE_RUNTIME_TYPES_BEGIN="// --- BEGIN GENERATED RUNTIME TYPES ---";ke.GENPAGE_RUNTIME_TYPES_END="// --- END GENERATED RUNTIME TYPES ---";var _n="./RuntimeTypes",$5="'\"`",qN=/\s/;function x5(e){return e===10||e===13||e===8232||e===8233}function F5(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 zN(e){let t=[],r=_n.length;for(let l=e.indexOf(_n);l!==-1;l=e.indexOf(_n,l+1)){let u=l-1;u>=0&&$5.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&&qN.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&&qN.test(e[d]);)d+=1;n.push({start:l,end:d}),u=d}}l=e.indexOf("import",u)}return n}ke.runtimeTypesImportSpans=zN;var M5=/\b(?:import\s*['"]|export\s)/;function U5(e){let t=F5(/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&&!x5(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 B5(e){return e!==void 0&&e!==""&&(M5.test(e)||U5(e))}ke.isLoadableGenPageOutput=B5;var VN=["transpileModule","createSourceFile","createProgram","getParseTreeNode","flattenDiagnosticMessageText","forEachChild","getModifiers","canHaveModifiers","isImportDeclaration","isExportDeclaration","isExportAssignment","isStringLiteral"];function jN(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?VN.filter(s=>typeof n?.[s]!="function"):[...VN];if(!n||i.length>0)throw new gs.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@${ke.GENPAGE_TYPESCRIPT_VERSION}'s lib/typescript.js.`);let o=typeof n.version=="string"?n.version:"",a=ke.GENPAGE_TYPESCRIPT_VERSION.split(".").slice(0,2).join(".");if(o.split(".").slice(0,2).join(".")!==a)throw new gs.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 (${ke.GENPAGE_TYPESCRIPT_VERSION}). Another version can emit different JavaScript for the same page. Supply typescript@${ke.GENPAGE_TYPESCRIPT_VERSION}.`);return n}ke.acceptGenPageTypeScript=jN;function q5(e){let t;return()=>{if(!t){if(e===void 0)return Promise.reject(new gs.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@${ke.GENPAGE_TYPESCRIPT_VERSION}'s lib/typescript.js. Nothing was written.`));t=Promise.resolve().then(()=>typeof e=="function"?e():e).then(jN).catch(r=>{throw t=void 0,r instanceof gs.SdkError?r:new gs.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}}ke.createGenPageTypeScriptLoader=q5;var HN=e=>`${e.kind}:${e.pos}:${e.end}`;function V5(e,t){return()=>r=>{let n=i=>{let o=e.getParseTreeNode(i);o&&t.add(HN(o)),e.forEachChild(i,n)};return n(r),r}}function Lg(e){return{target:e.ScriptTarget.ES5,module:e.ModuleKind.ES2020,jsx:e.JsxEmit.React}}var G5=2301;function GN(e,t,r){var n;let i=e.transpileModule(t,{compilerOptions:Lg(e),reportDiagnostics:!0,...r?{transformers:{after:[V5(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 WN=e=>e.startsWith(".")||e.startsWith("/"),Bd={line:1,column:1};function kg(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):Bd},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 Bd}}}function W5(e,t,r,n){var i,o;let a=[],s=kg(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===_n?l(s.statement(C,"export"),d,"a page cannot re-export from './RuntimeTypes': that module does not exist at runtime"):C!==void 0&&WN(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!==_n){WN(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(Bd,"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 KN(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===G5&&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===_n},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 z5(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=KN(e,t,Lg(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(HN(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 j5(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===_n)}function JN(e,t){return t.statements.filter(r=>e.isImportDeclaration(r)&&e.isStringLiteral(r.moduleSpecifier)&&r.moduleSpecifier.text===_n).map(r=>r.getStart(t))}function H5(e,t){let r=e.createSourceFile("page.js",t,e.ScriptTarget.ES2020,!0,e.ScriptKind.JS),n=JN(e,r),i=new Set(n),o,a="",s=0;for(let l of zN(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 K5(e,t,r){let n=new Set(JN(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 Bd}function YN(e,t,r){if(!r||r.size===0)return[];let n=KN(e,t,{...Lg(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===_n&&((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))}ke.legacyEnumsNeeded=YN;function J5(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 Y5(e,t,r,n){var i;let o=new Set,a=GN(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=J5(r,n,YN(e,l,n)),c=[...W5(e,l,s,u),...z5(e,s,u,o)];if(!u?.text)return{code:a.code,diagnostics:c};let d=GN(e,u.text);if(d.diagnostics.length>0)throw new gs.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=H5(e,a.code),m=f.code;if(c.length===0&&(!((i=f.inexact)===null||i===void 0)&&i.swallows))c.push({...kg(e,s).statement(_n,"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({...K5(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&&j5(e,m)&&c.push({...kg(e,s).statement(_n,"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:[ke.GENPAGE_RUNTIME_TYPES_BEGIN,d.code,ke.GENPAGE_RUNTIME_TYPES_END,m].join(`+`}});var $k=C(wg=>{"use strict";Object.defineProperty(wg,"__esModule",{value:!0});wg.generateGenPageRuntimeTypes=void 0;var kk=yE(),Qu=Y(),Rk=new Set(["None","ColorsDefaultsConstraints","ColorsDefaultsConstraintsDescriptions"]),Xu="generateGenPageRuntimeTypes";async function eZ(e,t,n){let r=tZ(t),i=nZ(n),o=[];for(let a of r){let s=await e(a);if(s.columnDetailComplete!==!0)throw new Qu.SdkError("GENPAGE_DATA_SOURCE_INCOMPLETE",`${Xu}: 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,kk.renderGenPageAuthoringTypes)(o,i)}wg.generateGenPageRuntimeTypes=eZ;function tZ(e){if(!Array.isArray(e))throw new Qu.InvalidArgumentError(`${Xu}: dataSources must be an array of table logical names`);let t=new Set;for(let n of e){if(typeof n!="string"||!kk.TABLE_LOGICAL_NAME.test(n))throw new Qu.InvalidArgumentError(`${Xu}: a data source must be a table logical name (lowercase, e.g. 'account'), got '${String(n)}'`);if(t.has(n))throw new Qu.InvalidArgumentError(`${Xu}: data source '${n}' is listed twice; a page's dataSources hold each table once`);t.add(n)}return[...t]}function nZ(e){if(e===void 0)return"None";if(e===null||typeof e!="object"||Array.isArray(e))throw new Qu.InvalidArgumentError(`${Xu}: options must be an object`);let t=Object.keys(e).filter(r=>r!=="detail");if(t.length>0)throw new Qu.InvalidArgumentError(`${Xu}: unknown option '${t[0]}' (the only option is 'detail')`);let n=e.detail===void 0?"None":e.detail;if(typeof n!="string"||!Rk.has(n))throw new Qu.InvalidArgumentError(`${Xu}: detail must be one of ${[...Rk].map(r=>`'${r}'`).join(", ")}, got '${String(n)}'`);return n}});var vE=C(za=>{"use strict";Object.defineProperty(za,"__esModule",{value:!0});za.readProvisionedLanguages=za.getEnvironmentLanguages=za.ENVIRONMENT_LANGUAGES_UNREADABLE_CODE=void 0;var rZ=Y(),Mk=pe();za.ENVIRONMENT_LANGUAGES_UNREADABLE_CODE="ENVIRONMENT_LANGUAGES_UNREADABLE";var Lk="/organizations?$select=languagecode",xk="/RetrieveProvisionedLanguages()",iZ="/RetrieveAvailableLanguages()";function Fk(e,t){return new rZ.SdkError(za.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 Uk(e){return typeof e=="number"&&Number.isInteger(e)&&e>0}async function bE(e,t,n,r){let i=(0,Mk.ensureSuccess)(await e.get(t),e.apiUrl(t)).body,o=i?.[n];if(!Array.isArray(o)||o.length===0||!o.every(Uk))throw Fk(r,`answered no list of language codes in '${n}'`);return[...new Set(o)]}async function oZ(e){var t;let n=(0,Mk.ensureSuccess)(await e.get(Lk),e.apiUrl(Lk)).body,r=n?.value,i=Array.isArray(r)&&r.length===1?(t=r[0])===null||t===void 0?void 0:t.languagecode:void 0;if(!Uk(i))throw Fk("the organization read","did not answer one row with a language code");let o=await bE(e,xk,"RetrieveProvisionedLanguages","RetrieveProvisionedLanguages"),a=await bE(e,iZ,"LocaleIds","RetrieveAvailableLanguages");return{baseLanguage:i,available:a,provisioned:o}}za.getEnvironmentLanguages=oZ;function aZ(e){return bE(e,xk,"RetrieveProvisionedLanguages","RetrieveProvisionedLanguages")}za.readProvisionedLanguages=aZ});var Zf=C(gn=>{"use strict";Object.defineProperty(gn,"__esModule",{value:!0});gn.projectConnectorOperationSchema=gn.projectConnectorOperations=gn.validateConnectorSwagger=gn.CONNECTOR_SCHEMA_TOO_LARGE_CODE=gn.CONNECTOR_OPERATION_NOT_FOUND_CODE=gn.CONNECTOR_SWAGGER_UNSUPPORTED_CODE=gn.CONNECTIVITY_RESPONSE_UNREADABLE_CODE=void 0;var Xf=Y();gn.CONNECTIVITY_RESPONSE_UNREADABLE_CODE="CONNECTIVITY_RESPONSE_UNREADABLE";gn.CONNECTOR_SWAGGER_UNSUPPORTED_CODE="CONNECTOR_SWAGGER_UNSUPPORTED";gn.CONNECTOR_OPERATION_NOT_FOUND_CODE="CONNECTOR_OPERATION_NOT_FOUND";gn.CONNECTOR_SCHEMA_TOO_LARGE_CODE="CONNECTOR_SCHEMA_TOO_LARGE";var qk=64,Bk=128,Vk=2e5,Gk=4e6,sZ=new Set(["get","put","post","delete","patch","head","options"]),uZ=new Set(["query","header","path","formData","body"]);function Wi(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function yo(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Wn(e){return e===void 0?"absent":e===null?"null":Array.isArray(e)?"an array":`a ${typeof e}`}function an(e){return e.length>80?`'${e.slice(0,80)}\u2026'`:`'${e}'`}function Nt(e,t){return new Xf.SdkError(gn.CONNECTIVITY_RESPONSE_UNREADABLE_CODE,`The connector's swagger could not be read: ${e} ${t}. Nothing was skipped or assumed in its place.`)}function js(e,t){return new Xf.SdkError(gn.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 lZ(e,t){let n=e;for(let r of t.slice(2).split("/")){let i=r.replace(/~1/g,"/").replace(/~0/g,"~");if(typeof n!="object"||n===null||!yo(n,i))return{found:!1};n=n[i]}return{found:!0,value:n}}function AE(e,t,n){if(!t.startsWith("#/"))throw js(n,`has a $ref that is not a local '#/\u2026' pointer (${an(t)})`);if(t.includes("%"))throw js(n,`has a $ref with a percent-encoded character (${an(t)}), which is not decoded`);if(/~(?![01])/.test(t))throw Nt(n,`has a $ref with a malformed escape (${an(t)}): a '~' not followed by 0 or 1`);let r=lZ(e,t);if(!r.found)throw Nt(n,`has a $ref that does not resolve (${an(t)})`);return r.value}function Eg(e,t){if(yo(e,"$ref")){if(typeof e.$ref!="string")throw Nt(t,`has a $ref that is ${Wn(e.$ref)}, not a string`);return e.$ref}}function cZ(e,t,n){if(!Wi(t))throw Nt(n,`is ${Wn(t)}, not a parameter object`);let r=t,i=Eg(t,n);if(i!==void 0){let s=AE(e,i,n);if(!Wi(s))throw Nt(n,`has a $ref (${an(i)}) that resolves to ${Wn(s)}, not a parameter object`);if(Eg(s,`${n} \u2192 ${an(i)}`)!==void 0)throw js(n,`has a $ref (${an(i)}) to a parameter that is itself a $ref`);r=s}if(typeof r.name!="string")throw Nt(n,"has no string name");let o=r.in;if(typeof o!="string"||!uZ.has(o))throw Nt(n,`has an in that is ${typeof o=="string"?an(o):Wn(o)}, not one of query, header, path, formData or body`);if(yo(r,"required")&&typeof r.required!="boolean")throw Nt(n,`has a required that is ${Wn(r.required)}, not a boolean`);let a=r["x-ms-visibility"];if(yo(r,"x-ms-visibility")&&typeof a!="string")throw Nt(n,`has an x-ms-visibility that is ${Wn(a)}, not a string`);return{name:r.name,in:o,required:r.required===!0,internal:a==="internal"}}function wE(e){return`${e.in}:${e.name}`}function Wk(e,t,n){if(!yo(t,"parameters"))return[];let r=t.parameters;if(!Array.isArray(r))throw Nt(n,`has parameters that are ${Wn(r)}, not an array`);let i=new Set;return r.map((o,a)=>{let s=`${n} parameters[${a}]`,u=cZ(e,o,s),l=wE(u);if(i.has(l))throw Nt(s,`repeats the parameter ${an(u.name)} in ${an(u.in)}, which must be unique in its list`);return i.add(l),u})}function zk(e,t,n){let r=t.responses;if(!yo(r,"200"))return;let i=`${n} response 200`,o=r[200];if(!Wi(o))throw Nt(i,`is ${Wn(o)}, not a response object`);let a=o,s=Eg(o,i);if(s!==void 0){if(s.startsWith("#/")&&!/^#\/responses\/[^/]+$/.test(s))throw Nt(i,`has a $ref (${an(s)}) that does not name a response ('#/responses/<name>')`);let u=AE(e,s,i);if(!Wi(u))throw Nt(i,`has a $ref (${an(s)}) that resolves to ${Wn(u)}, not a response object`);if(Eg(u,`${i} \u2192 ${an(s)}`)!==void 0)throw js(i,`has a $ref (${an(s)}) to a response that is itself a $ref`);a=u}if(yo(a,"content"))throw js(i,"is an OpenAPI 3 response (it has content), not a Swagger 2.0 one");if(yo(a,"schema")){if(!Wi(a.schema))throw Nt(i,`has a schema that is ${Wn(a.schema)}, not an object`);return a.schema}}function jk(e,t,n){if(!yo(e,t))return;let r=e[t];if(typeof r!="string")throw Nt(n,`has a ${t} that is ${Wn(r)}, not a string`);return r}function dZ(e,t,n,r,i){if(!Wi(t))throw Nt(n,`is ${Wn(t)}, not an operation object`);let o=t.operationId;if(typeof o!="string")throw Nt(n,`has no string operationId (${Wn(o)})`);if(r.has(o))throw Nt(n,`repeats the operationId ${an(o)}, which must be unique in the document`);r.add(o);let a=jk(t,"summary",n),s=jk(t,"description",n),u=Wk(e,t,n);if(!Wi(t.responses))throw Nt(n,`has no responses object (${Wn(t.responses)})`);return zk(e,t,n),{id:o,summary:a,description:s,node:t,where:n,parameters:u,pathParameters:i}}function CE(e){if(!Wi(e))throw Nt("the document",`is ${Wn(e)}, not an object`);if(yo(e,"openapi"))throw js("the document","is OpenAPI 3 (it has an openapi member), not Swagger 2.0");if(!yo(e,"swagger"))throw Nt("the document","names no Swagger version");if(e.swagger!=="2.0")throw js("the document",`declares swagger ${an(String(e.swagger))}, not 2.0`);let t=e.paths;if(!Wi(t))throw Nt("the document",`has paths that are ${Wn(t)}, not an object`);let n=[],r=new Set;for(let i of Object.keys(t)){let o=t[i],a=`paths[${an(i)}]`;if(!Wi(o))throw Nt(a,`is ${Wn(o)}, not a path item object`);let s=[];for(let u of Object.keys(o))if(sZ.has(u.toLowerCase()))n.push(dZ(e,o[u],`${a}.${u}`,r,s));else if(u==="parameters")for(let l of Wk(e,o,a))s.push(l);else if(!u.startsWith("x-"))throw js(a,`has a ${an(u)} member; a path item may hold only HTTP methods, parameters and x- extensions`)}return{document:e,operations:n}}function fZ(e){CE(e)}gn.validateConnectorSwagger=fZ;var EE=class{constructor(t,n){this.root=t,this.where=n,this.nodes=0,this.characters=0,this.path=[]}run(t){return this.visit(t,0)}tooLarge(t){return new Xf.SdkError(gn.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>Vk)throw this.tooLarge(`more than ${Vk} nodes`)}text(t){if(this.characters+=t,this.characters>Gk)throw this.tooLarge(`more than ${Gk} characters of strings and keys`)}checkDepth(t){if(t>Bk)throw this.tooLarge(`nesting deeper than ${Bk} levels`)}visit(t,n){if(this.checkDepth(n),Array.isArray(t)){this.node();let r=[];for(let i of t)r.push(this.visit(i,n+1));return r}if(Wi(t)){if(typeof t.$ref=="string")return this.reference(t.$ref,n);this.node();let r={};for(let i of Object.keys(t))this.text(i.length),Object.defineProperty(r,i,{value:this.visit(t[i],n+1),enumerable:!0,writable:!0,configurable:!0});return r}return this.node(),typeof t=="string"&&this.text(t.length),t}reference(t,n){if(this.path.includes(t)){this.checkDepth(n+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>=qk)throw this.tooLarge(`a $ref chain of more than ${qk} references`);let r=AE(this.root,t,this.where);if(!Wi(r))throw Nt(this.where,`has a schema $ref (${an(t)}) that resolves to ${Wn(r)}, not a schema object`);this.path.push(t);let i=this.visit(r,n);return this.path.pop(),i}};function pZ(e){let{operations:t}=CE(e);return{operations:t.map(n=>{var r,i;return{name:n.id,summary:(i=(r=n.summary)!==null&&r!==void 0?r:n.description)!==null&&i!==void 0?i:null}})}}gn.projectConnectorOperations=pZ;function mZ(e,t){if(typeof t!="string"||t==="")throw new Xf.InvalidArgumentError("operationId must be a non-empty string.");let{document:n,operations:r}=CE(e),i=r.find(l=>l.id===t);if(!i)throw new Xf.SdkError(gn.CONNECTOR_OPERATION_NOT_FOUND_CODE,`The connector has no operation with the id ${an(t)} (ids are matched exactly, case included). List the connector\u2019s operations to see its ids.`);let o=new Set(i.parameters.map(wE)),a=[...i.parameters,...i.pathParameters.filter(l=>!o.has(wE(l)))].filter(l=>!l.internal).map(({name:l,required:c})=>({name:l,required:c})),s=zk(n,i.node,i.where),u=s===void 0?{}:new EE(n,`${i.where} (${an(i.id)})`).run(s);return{operation:i.id,parameters:a,response:u}}gn.projectConnectorOperationSchema=mZ});var Zu=C(se=>{"use strict";Object.defineProperty(se,"__esModule",{value:!0});se.readEnvironmentName=se.readConnection=se.connectorShortName=se.CONNECTOR_PREFIX=se.connectivityUnauthorized=se.errorCodeOf=se.messageOf=se.environmentFilter=se.unreadable=se.connectivityCloudOf=se.sameOrigin=se.parseUrl=se.bounded=se.kindOf=se.isObject=se.CONNECTOR_RUNTIME_UNSUPPORTED_CODE=se.CONNECTOR_NOT_TABULAR_CODE=se.CONNECTIVITY_ROUTE_DECOMMISSIONED_CODE=se.CONNECTIVITY_UNAUTHORIZED_CODE=se.CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE=se.CONNECTIVITY_CLOUD_UNSUPPORTED_CODE=se.CONNECTIVITY_NOT_CONFIGURED_CODE=void 0;var ep=Y(),hZ=pe(),gZ=Zf();se.CONNECTIVITY_NOT_CONFIGURED_CODE="CONNECTIVITY_NOT_CONFIGURED";se.CONNECTIVITY_CLOUD_UNSUPPORTED_CODE="CONNECTIVITY_CLOUD_UNSUPPORTED";se.CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE="CONNECTIVITY_ENVIRONMENT_UNVERIFIED";se.CONNECTIVITY_UNAUTHORIZED_CODE="CONNECTIVITY_UNAUTHORIZED";se.CONNECTIVITY_ROUTE_DECOMMISSIONED_CODE="CONNECTIVITY_ROUTE_DECOMMISSIONED";se.CONNECTOR_NOT_TABULAR_CODE="CONNECTOR_NOT_TABULAR";se.CONNECTOR_RUNTIME_UNSUPPORTED_CODE="CONNECTOR_RUNTIME_UNSUPPORTED";function si(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}se.isObject=si;function Nc(e){return e===void 0?"absent":e===null?"null":Array.isArray(e)?"an array":`a ${typeof e}`}se.kindOf=Nc;function _c(e,t=200){return e.length>t?`${e.slice(0,t)}\u2026`:e}se.bounded=_c;function Kk(e){try{let t=new URL(e);return{protocol:t.protocol,host:t.host,origin:t.origin}}catch{return}}se.parseUrl=Kk;function yZ(e,t){return e.protocol===t.protocol&&e.host.toLowerCase()===t.host.toLowerCase()}se.sameOrigin=yZ;var bZ=/^[a-z0-9-]+\.crm(\d*)\.dynamics\.com$/,vZ=/^[a-z0-9-]+\.crmtest\.dynamics\.com$/;function wZ(e){let t=Kk(e),n=t?t.host.toLowerCase():"";if(vZ.test(n))return"Test";let r=bZ.exec(n);return r&&r[1]!=="9"?"Public":"Unsupported"}se.connectivityCloudOf=wZ;function na(e,t){return new ep.SdkError(gZ.CONNECTIVITY_RESPONSE_UNREADABLE_CODE,`${e} could not be read: ${t}. Nothing was skipped or assumed in its place.`)}se.unreadable=na;function EZ(e){return encodeURIComponent(`environment eq '${e.replace(/'/g,"''")}'`)}se.environmentFilter=EZ;function AZ(e){if(typeof e=="string"&&e.length>0)return _c(e,500);if(si(e)){let t=si(e.error)?e.error.message:void 0;for(let n of[t,e.Message,e.message])if(typeof n=="string")return _c(n,500)}return"request failed"}se.messageOf=AZ;function Jk(e){return si(e)&&si(e.error)?e.error.code:void 0}se.errorCodeOf=Jk;function CZ(e){if(si(e)&&si(e.error)&&si(e.error.innererror))return e.error.innererror.code}function SZ(e,t,n){let r=[],i=Jk(t);typeof i=="string"&&i.length>0&&r.push(_c(i,80));let o=CZ(t);typeof o=="string"&&o.length>0&&r.push(_c(o,80));let a=r.length>0?` (${r.join("; ")})`:"";return(0,ep.attachCause)(new ep.SdkError(se.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.`),n)}se.connectivityUnauthorized=SZ;se.CONNECTOR_PREFIX="/providers/Microsoft.PowerApps/apis/";var NZ=/^[A-Za-z0-9_.-]{1,128}$/,_Z=new Set(["shared_logicflows","shared_powerflows","shared_pqogenericconnector"]);function IZ(e){if(typeof e=="string"){let n=e.slice(0,se.CONNECTOR_PREFIX.length).toLowerCase()===se.CONNECTOR_PREFIX.toLowerCase()?e.slice(se.CONNECTOR_PREFIX.length):e;if(NZ.test(n)&&!/^\.{1,2}$/.test(n))return n}throw new ep.InvalidArgumentError(`connector must be a connector's short name ('shared_office365users') or its full API id ('${se.CONNECTOR_PREFIX}shared_office365users'); got ${typeof e=="string"?`'${_c(e,80)}'`:Nc(e)}.`)}se.connectorShortName=IZ;function TZ(e,t,n){let r=`Connection row ${t}`;if(!si(e))throw na(r,`it is ${Nc(e)}, not an object`);let i=e.properties;if(!si(i))throw na(r,`its properties are ${Nc(i)}, not an object`);let o=i.apiId;if(typeof o!="string"||o.slice(0,se.CONNECTOR_PREFIX.length).toLowerCase()!==se.CONNECTOR_PREFIX.toLowerCase())throw na(r,`its apiId is not '${se.CONNECTOR_PREFIX}<connector>'`);let a=o.slice(se.CONNECTOR_PREFIX.length);if(a===""||a.includes("/"))throw na(r,"its apiId names no single connector");if(_Z.has(a.toLowerCase()))return;let s=e.name;if(typeof s!="string"||s==="")throw na(r,"it has no name");let u=i.environment,l=si(u)?u.name:void 0;if(typeof l!="string"||l.toLowerCase()!==n.toLowerCase())throw na(r,"it is not a connection of this environment (properties.environment.name)");let c=i.displayName;if(typeof c!="string")throw na(r,`its displayName is ${Nc(c)}, not a string`);let d=i.statuses;if(!Array.isArray(d))throw na(r,`its statuses are ${Nc(d)}, not an array`);return{connectionId:s,displayName:c,connectorId:o,connectorName:a,statuses:d.map(f=>{let p=si(f)?f.status:void 0;if(typeof p!="string")throw na(r,"one of its statuses has no string status");return p})}}se.readConnection=TZ;var Hk="/RetrieveCurrentOrganization(AccessType=@p1)?@p1=Microsoft.Dynamics.CRM.EndpointAccessType'Default'";async function OZ(e){let t=(0,hZ.ensureSuccess)(await e.get(Hk),e.apiUrl(Hk)).body,n=si(t)?t.Detail:void 0,r=si(n)?n.EnvironmentId:void 0;if(typeof r!="string"||r==="")throw new ep.SdkError(se.CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE,"The environment of this org could not be verified: the org answered no environment id (RetrieveCurrentOrganization, Detail.EnvironmentId).");return r}se.readEnvironmentName=OZ});var n$=C(ui=>{"use strict";Object.defineProperty(ui,"__esModule",{value:!0});ui.ConnectivityApi=ui.CONNECTIVITY_UNAUTHORIZED_CODE=ui.CONNECTIVITY_ROUTE_DECOMMISSIONED_CODE=ui.CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE=ui.CONNECTIVITY_CLOUD_UNSUPPORTED_CODE=ui.CONNECTIVITY_NOT_CONFIGURED_CODE=void 0;var gr=Y(),DZ=pe(),Cg=Zf(),np=Zu(),rp=Zu();Object.defineProperty(ui,"CONNECTIVITY_NOT_CONFIGURED_CODE",{enumerable:!0,get:function(){return rp.CONNECTIVITY_NOT_CONFIGURED_CODE}});Object.defineProperty(ui,"CONNECTIVITY_CLOUD_UNSUPPORTED_CODE",{enumerable:!0,get:function(){return rp.CONNECTIVITY_CLOUD_UNSUPPORTED_CODE}});Object.defineProperty(ui,"CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE",{enumerable:!0,get:function(){return rp.CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE}});Object.defineProperty(ui,"CONNECTIVITY_ROUTE_DECOMMISSIONED_CODE",{enumerable:!0,get:function(){return rp.CONNECTIVITY_ROUTE_DECOMMISSIONED_CODE}});Object.defineProperty(ui,"CONNECTIVITY_UNAUTHORIZED_CODE",{enumerable:!0,get:function(){return rp.CONNECTIVITY_UNAUTHORIZED_CODE}});var Yk="2016-11-01",PZ="2021-04-01",RZ="https://api.bap.microsoft.com",kZ="https://test.api.bap.microsoft.com",$Z=/^[a-z0-9-]+\.crm(\d*)\.dynamics\.com$/,LZ=/^[a-z0-9-]+\.crmtest\.dynamics\.com$/,Qk="/RetrieveCurrentOrganization(AccessType=@p1)?@p1=Microsoft.Dynamics.CRM.EndpointAccessType'Default'",Ha="/providers/Microsoft.PowerApps/apis/",MZ=/^[A-Za-z0-9_.-]{1,128}$/,xZ=new Set(["shared_logicflows","shared_powerflows","shared_pqogenericconnector"]),FZ="ServiceDecommissioned";function _n(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ws(e){return e===void 0?"absent":e===null?"null":Array.isArray(e)?"an array":`a ${typeof e}`}function ra(e,t=200){return e.length>t?`${e.slice(0,t)}\u2026`:e}function tp(e){try{let t=new URL(e);return{protocol:t.protocol,host:t.host,origin:t.origin}}catch{return}}function Xk(e,t){return e.protocol===t.protocol&&e.host.toLowerCase()===t.host.toLowerCase()}function UZ(e){return/^[a-z0-9][a-z0-9.-]*$/.test(e)&&(e==="api.powerapps.com"||e.endsWith(".api.powerapps.com"))}function zi(e,t){return new gr.SdkError(Cg.CONNECTIVITY_RESPONSE_UNREADABLE_CODE,`${e} could not be read: ${t}. Nothing was skipped or assumed in its place.`)}function Ag(e){return new gr.SdkError(np.CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE,`The environment of this org could not be verified: ${e}. The Power Apps service was not asked about it.`)}function Zk(e){return encodeURIComponent(`environment eq '${e.replace(/'/g,"''")}'`)}function e$(e){if(typeof e=="string"&&e.length>0)return ra(e,500);if(_n(e)){let t=_n(e.error)?e.error.message:void 0;for(let n of[t,e.Message,e.message])if(typeof n=="string")return ra(n,500)}return"request failed"}function qZ(e){return _n(e)&&_n(e.error)?e.error.code:void 0}function t$(e){if(typeof e=="string"){let n=e.slice(0,Ha.length).toLowerCase()===Ha.toLowerCase()?e.slice(Ha.length):e;if(MZ.test(n)&&!/^\.{1,2}$/.test(n))return n}throw new gr.InvalidArgumentError(`connector must be a connector's short name ('shared_office365users') or its full API id ('${Ha}shared_office365users'); got ${typeof e=="string"?`'${ra(e,80)}'`:Ws(e)}.`)}function BZ(e,t,n){let r=`Connection row ${t}`;if(!_n(e))throw zi(r,`it is ${Ws(e)}, not an object`);let i=e.properties;if(!_n(i))throw zi(r,`its properties are ${Ws(i)}, not an object`);let o=i.apiId;if(typeof o!="string"||o.slice(0,Ha.length).toLowerCase()!==Ha.toLowerCase())throw zi(r,`its apiId is not '${Ha}<connector>'`);let a=o.slice(Ha.length);if(a===""||a.includes("/"))throw zi(r,"its apiId names no single connector");if(xZ.has(a.toLowerCase()))return;let s=e.name;if(typeof s!="string"||s==="")throw zi(r,"it has no name");let u=i.environment,l=_n(u)?u.name:void 0;if(typeof l!="string"||l.toLowerCase()!==n.toLowerCase())throw zi(r,"it is not a connection of this environment (properties.environment.name)");let c=i.displayName;if(typeof c!="string")throw zi(r,`its displayName is ${Ws(c)}, not a string`);let d=i.statuses;if(!Array.isArray(d))throw zi(r,`its statuses are ${Ws(d)}, not an array`);return{connectionId:s,displayName:c,connectorId:o,connectorName:a,statuses:d.map(f=>{let p=_n(f)?f.status:void 0;if(typeof p!="string")throw zi(r,"one of its statuses has no string status");return p})}}var SE=class{constructor(t,n,r){this.org=t,this.instanceUrl=n,this.service=r,this.swaggers=new Map}async listConnections(){let t=this.requireService(),n=await this.resolveEnvironment(t),r=[],i=new Set,o=`${n.origin}/providers/Microsoft.PowerApps/connections?api-version=${Yk}&$filter=${Zk(n.id)}`,a=await this.send(t,o,!0),s=1,u=0;for(;;){let l=`Page ${s} of the connections`,c=a.body,d=c?.value;if(!Array.isArray(d))throw zi(l,`its value is ${Ws(d)}, not an array`);for(let p of d){let m=BZ(p,u,n.id);u+=1,m&&r.push(m)}let f=c?.nextLink;if(f==null)return r;if(typeof f!="string"||f.length===0)throw zi(l,`its nextLink is ${f===""?"an empty string":Ws(f)}, not a non-empty string`);if(i.has(f))throw new gr.InvalidArgumentError(`listConnections: aborting pagination \u2014 the server returned a repeated nextLink ('${ra(f)}'), which would loop indefinitely.`);i.add(f),this.assertSameOrigin(f,n.parsed),a=await this.send(t,f,!0),s+=1}}async listConnectorOperations(t){let n=this.requireService(),r=t$(t);return(0,Cg.projectConnectorOperations)(await this.swagger(n,r))}async getConnectorOperationSchema(t,n){let r=this.requireService(),i=t$(t);if(typeof n!="string"||n==="")throw new gr.InvalidArgumentError("operationId must be a non-empty string.");return(0,Cg.projectConnectorOperationSchema)(await this.swagger(r,i),n)}requireService(){if(!this.service)throw new gr.SdkError(np.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 n=this.verifyEnvironment(t);this.environment=n,n.catch(()=>{this.environment===n&&(this.environment=void 0)})}return this.environment}async verifyEnvironment(t){let n=this.candidateBapOrigin(),r=await this.readEnvironmentId(),i=`${n}/providers/Microsoft.BusinessAppPlatform/environments/${encodeURIComponent(r)}?api-version=${PZ}`,o=(await this.send(t,i,!1)).body,a=_n(o)?o.properties:void 0,s=_n(o)?o.name:void 0;if(typeof s!="string"||s.toLowerCase()!==r.toLowerCase())throw Ag(`BAP's environment row is not the one named '${ra(r,80)}' (its name)`);let u=_n(a)&&_n(a.linkedEnvironmentMetadata)?a.linkedEnvironmentMetadata.instanceUrl:void 0,l=typeof u=="string"?tp(u):void 0,c=tp(this.instanceUrl);if(!l||!c||!Xk(l,c))throw Ag("BAP's row is not linked to this org (its linkedEnvironmentMetadata.instanceUrl is another origin)");let d=_n(a)?a.runtimeEndpoints:void 0,f=_n(d)?d["microsoft.PowerApps"]:void 0,p=typeof f=="string"?tp(f):void 0;if(!p||p.protocol!=="https:"||!UZ(p.host.toLowerCase()))throw Ag("BAP's Power Apps runtime endpoint is not an https host of api.powerapps.com (runtimeEndpoints['microsoft.PowerApps'])");return{id:r,origin:p.origin.toLowerCase(),parsed:p}}candidateBapOrigin(){let t=tp(this.instanceUrl),n=t?t.host.toLowerCase():"",r=$Z.exec(n);if(r&&r[1]!=="9")return RZ;if(LZ.test(n))return kZ;throw new gr.SdkError(np.CONNECTIVITY_CLOUD_UNSUPPORTED_CODE,`The org's host is not one of the clouds this reads in (${t?`'${ra(t.host,80)}'`:`'${ra(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,DZ.ensureSuccess)(await this.org.get(Qk),this.org.apiUrl(Qk)).body,n=_n(t)?t.Detail:void 0,r=_n(n)?n.EnvironmentId:void 0;if(typeof r!="string"||r==="")throw Ag("the org answered no environment id (RetrieveCurrentOrganization, Detail.EnvironmentId)");return r}swagger(t,n){let r=n.toLowerCase(),i=this.swaggers.get(r);if(!i){let o=this.readSwagger(t,n);i=o,this.swaggers.set(r,o),o.catch(()=>{this.swaggers.get(r)===o&&this.swaggers.delete(r)})}return i}async readSwagger(t,n){let r=await this.resolveEnvironment(t),i=encodeURIComponent(n),o=`${r.origin}${Ha}${i}?api-version=${Yk}&$filter=${Zk(r.id)}`,a=(await this.send(t,o,!0)).body,s=_n(a)?a.properties:void 0,u=_n(s)?s.swagger:void 0;if(!_n(u))throw zi(`The connector '${ra(n,80)}'`,`its properties.swagger is ${Ws(u)}, not an object`);return(0,Cg.validateConnectorSwagger)(u),u}assertSameOrigin(t,n){let r=tp(t);if(!r)throw new gr.InvalidArgumentError(`Refusing to follow a malformed absolute URL: '${ra(t)}'`);if(!Xk(r,n))throw new gr.InvalidArgumentError(`Refusing to follow a cross-origin link ('${ra(r.origin,120)}' is not the environment's Power Apps endpoint '${n.origin}'); server-driven pagination must stay on that origin.`)}async send(t,n,r){let i;try{i=await t.get(n)}catch(o){throw o instanceof gr.ConnectionError&&typeof o.statusCode=="number"&&o.statusCode>0?this.mapNon2xx(n,o.statusCode,void 0,r,o):o instanceof gr.SdkError?o:new gr.ConnectionError(n,0,o instanceof Error?o.message:String(o),o)}if(!i||typeof i.status!="number")throw new gr.ConnectionError(n,0,"the transport returned no HTTP response");if(i.status>=200&&i.status<300)return i;throw this.mapNon2xx(n,i.status,i.body,r)}mapNon2xx(t,n,r,i,o){let a=o??new gr.ConnectionError(t,n,e$(r),r);return i&&n===410&&qZ(r)===FZ?(0,gr.attachCause)(new gr.SdkError(np.CONNECTIVITY_ROUTE_DECOMMISSIONED_CODE,`The Power Apps API this reads through is decommissioned for this environment: ${e$(r)} 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):n===401||n===403?(0,np.connectivityUnauthorized)(n,r,a):a}};ui.ConnectivityApi=SE});var OE=C(Pt=>{"use strict";Object.defineProperty(Pt,"__esModule",{value:!0});Pt.projectConnectorTableSchema=Pt.projectConnectorTables=Pt.tableSchemaSuffix=Pt.tablesSuffix=Pt.encodeTable=Pt.encodeDataset=Pt.checkTabularConnection=Pt.runtimeAuthority=Pt.tabularRevision=Pt.checkTableSchemaArguments=Pt.checkListTablesArguments=void 0;var el=Y(),z=Zu(),VZ=/^[A-Za-z0-9_.-]{1,128}$/,tl=/^\.{1,2}$/,GZ="shared_sharepointonline",jZ=/^[0-9]{1,9}$/,WZ=/^[A-Za-z0-9._~-]+$/,zZ=/^\/apim\/([A-Za-z0-9._-]+)\/?$/,HZ=/^\/connectors\/runtime\/invoke\/scalegroups\/([A-Za-z0-9._-]+)\/(scaleunits|shards)\/([A-Za-z0-9._-]+)\/apis\/([A-Za-z0-9._-]+)\/connections\/?$/,KZ=/^[A-Za-z0-9._~!'()*-]$/,JZ=/^[0-9A-Fa-f]{2}$/;function Ka(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function ip(e){return typeof e=="string"?`'${(0,z.bounded)(e,80)}'`:(0,z.kindOf)(e)}function NE(e,t){return new el.SdkError(z.CONNECTOR_NOT_TABULAR_CODE,`The connector '${(0,z.bounded)(e,80)}' has no tables: ${t}.`)}function Sg(e,t){return new el.SdkError(z.CONNECTOR_RUNTIME_UNSUPPORTED_CODE,`The connector '${(0,z.bounded)(e,80)}' runs where this SDK does not send a token: ${t}. Nothing was sent to it.`)}function YZ(e){if(typeof e=="string"&&VZ.test(e)&&!tl.test(e))return e;throw new el.InvalidArgumentError(`connectionId must be a connection's name (letters, digits, '_', '.', '-'; at most 128; not '.' or '..'); got ${ip(e)}.`)}function QZ(e){if(e!=null){if(typeof e=="string"&&e!==""&&e.split(",").find(n=>n===""||tl.test(n))===void 0)return e;throw new el.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 ${ip(e)}.`)}}function XZ(e){if(typeof e=="string"&&e!==""&&!tl.test(e))return e;throw new el.InvalidArgumentError(`table must be a non-empty string other than '.' and '..'; got ${ip(e)}.`)}function i$(e,t,n){return{short:(0,z.connectorShortName)(e),connectionId:YZ(t),dataset:QZ(n)}}Pt.checkListTablesArguments=i$;function ZZ(e,t,n,r){return{...i$(e,t,n),table:XZ(r)}}Pt.checkTableSchemaArguments=ZZ;function eee(e,t){let n=`The connector '${(0,z.bounded)(t,80)}'`,r=e.properties;if(!(0,z.isObject)(r))throw(0,z.unreadable)(n,`its properties are ${(0,z.kindOf)(r)}, not an object`);if(!Ka(r,"interfaces"))throw NE(t,"it declares no interfaces");let i=r.interfaces;if(!(0,z.isObject)(i))throw(0,z.unreadable)(n,`its properties.interfaces are ${(0,z.kindOf)(i)}, not an object`);if(!Ka(i,"CDPTabular1"))throw NE(t,"it declares no CDPTabular1 interface");let o=i.CDPTabular1;if(!(0,z.isObject)(o))throw(0,z.unreadable)(n,`its CDPTabular1 interface is ${(0,z.kindOf)(o)}, not an object`);let a=o.revisions;if(!(0,z.isObject)(a))throw(0,z.unreadable)(n,`its CDPTabular1 revisions are ${(0,z.kindOf)(a)}, not an object`);let s,u=new Map;for(let l of Object.keys(a)){let c=a[l],d=`its CDPTabular1 revision '${(0,z.bounded)(l,40)}'`;if(!(0,z.isObject)(c)||typeof c.status!="string")throw(0,z.unreadable)(n,`${d} is not an object with a string status`);if(c.status!=="Production")continue;if(!jZ.test(l))throw(0,z.unreadable)(n,`${d} is a Production revision whose key is not a decimal integer of 1\u20139 digits`);let f=tee(c.baseUrl);if(f===void 0)throw(0,z.unreadable)(n,`${d} has a baseUrl that is not '/' or '/'-separated [A-Za-z0-9._~-] segments`);let p=Number(l),m=u.get(p);if(m!==void 0)throw(0,z.unreadable)(n,`its Production revisions '${m}' and '${(0,z.bounded)(l,40)}' have the same number`);u.set(p,l),(!s||p>s.revisionNumber)&&(s={revisionNumber:p,revision:f})}if(!s)throw NE(t,"its CDPTabular1 interface has no Production revision");return s.revision}Pt.tabularRevision=eee;function tee(e){if(typeof e!="string")return;let t=e.replace(/^\/+/,"").replace(/\/+$/,"");return t===""?"":t.split("/").every(i=>WZ.test(i)&&!tl.test(i))?t:void 0}function nee(e,t,n){let r=(0,z.isObject)(e.properties)?e.properties:void 0,i=r?r.primaryRuntimeUrl:void 0;if(typeof i!="string")throw Sg(n,`its primaryRuntimeUrl is ${(0,z.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,z.parseUrl)(i);if(!s||s.protocol!=="https:"||s.origin.toLowerCase()!==a)throw Sg(n,`its runtime ('${(0,z.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 u=i.slice(0,a.length).toLowerCase()===a?i.slice(a.length):void 0;if(o){let c=u===void 0?null:zZ.exec(u);if(!c||tl.test(c[1]))throw Sg(n,`its runtime ('${(0,z.bounded)(i,120)}') is not <host>/apim/<connector>`);return{transport:"invoke",origin:a,path:`/apim/${c[1]}`}}let l=u===void 0?null:HZ.exec(u);if(!l||[l[1],l[3],l[4]].some(c=>tl.test(c)))throw Sg(n,`its runtime ('${(0,z.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/${l[1]}/${l[2]}/${l[3]}/apis/${l[4]}/connections`}}Pt.runtimeAuthority=nee;function ree(e,t,n,r){let i=`The connection '${(0,z.bounded)(t,128)}'`;if(!(0,z.isObject)(e))throw(0,z.unreadable)(i,`it is ${(0,z.kindOf)(e)}, not an object`);if(e.name!==t)throw(0,z.unreadable)(i,`its name is ${ip(e.name)}, not the requested connection`);let o=e.properties;if(!(0,z.isObject)(o))throw(0,z.unreadable)(i,`its properties are ${(0,z.kindOf)(o)}, not an object`);let a=o.apiId;if(typeof a!="string"||a.toLowerCase()!==`${z.CONNECTOR_PREFIX}${n}`.toLowerCase())throw(0,z.unreadable)(i,`its apiId is ${ip(a)}, not the connector '${(0,z.bounded)(n,80)}'`);let s=o.environment,u=(0,z.isObject)(s)?s.name:void 0;if(typeof u!="string"||u.toLowerCase()!==r.toLowerCase())throw(0,z.unreadable)(i,"it is not a connection of this environment (properties.environment.name)");return t}Pt.checkTabularConnection=ree;function r$(e){return encodeURIComponent(e).replace(/[!'()*]/g,t=>`%${t.charCodeAt(0).toString(16).toUpperCase()}`)}function iee(e){if(e==="")return!1;for(let t=0;t<e.length;t+=1)if(e[t]==="%"){if(!JZ.test(e.slice(t+1,t+3)))return!1;t+=2}else if(!KZ.test(e[t]))return!1;return!0}function o$(e,t){let n,r,i;try{n=r$(e),r=r$(n),i=decodeURIComponent(r)}catch{throw new el.InvalidArgumentError(`${t} is not well-formed Unicode (it has a lone surrogate), so it cannot be sent.`)}if(!iee(r)||tl.test(r)||i!==n)throw new el.InvalidArgumentError(`${t} cannot be sent as one path segment.`);return r}function TE(e){return e.split(",").map((t,n)=>o$(t,`dataset part ${n}`)).join(",")}Pt.encodeDataset=TE;function a$(e){return o$(e,"table")}Pt.encodeTable=a$;function oee(e,t){if(t===void 0)return"/tables";let n=e.toLowerCase()===GZ?"allTables":"tables";return`/datasets/${TE(t)}/${n}`}Pt.tablesSuffix=oee;function aee(e,t){return`/$metadata.json${e===void 0?"":`/datasets/${TE(e)}`}/tables/${a$(t)}`}Pt.tableSchemaSuffix=aee;function Ic(e,t){let n=t.toLowerCase();for(let r of Object.keys(e))if(r.toLowerCase()===n)return{found:!0,value:e[r]};return{found:!1}}function see(e){let t="The table list",n;if(Array.isArray(e))n=e;else if((0,z.isObject)(e)){for(let o of["nextLink","@odata.nextLink"])if(Ic(e,o).found)throw(0,z.unreadable)(t,`it carries a ${o} \u2014 a paged answer is refused, never read as a partial list`);let r=Ic(e,"value"),i=r.found?r:Ic(e,"tables");if(!i.found)throw(0,z.unreadable)(t,"it is an object with neither a value nor a tables member");if(!Array.isArray(i.value))throw(0,z.unreadable)(t,`its ${r.found?"value":"tables"} is ${(0,z.kindOf)(i.value)}, not an array`);n=i.value}else throw(0,z.unreadable)(t,`it is ${(0,z.kindOf)(e)}, not an array or an object`);return{tables:n.map((r,i)=>uee(r,i))}}Pt.projectConnectorTables=see;function uee(e,t){let n=`Table row ${t}`;if(!(0,z.isObject)(e))throw(0,z.unreadable)(n,`it is ${(0,z.kindOf)(e)}, not an object`);let r=Ic(e,"name");if(!r.found||typeof r.value!="string"||r.value==="")throw(0,z.unreadable)(n,"it has no non-empty string name");let i=Ic(e,"displayName");if(i.found&&typeof i.value!="string")throw(0,z.unreadable)(n,`its displayName is ${(0,z.kindOf)(i.value)}, not a string`);let o=Ic(e,"id");if(o.found&&(typeof o.value!="string"||o.value===""))throw(0,z.unreadable)(n,`its id is ${o.value===""?"an empty string":(0,z.kindOf)(o.value)}, not a non-empty string`);return{name:r.value,displayName:i.found?i.value:null,id:o.found?o.value:r.value}}function _E(e,t,n){if(!Ka(e,t))return;let r=e[t];if(!(0,z.isObject)(r))throw(0,z.unreadable)("The table schema",`its ${n} is ${(0,z.kindOf)(r)}, not an object`);return r}function IE(e,t,n){if(!Ka(e,t))return;let r=e[t];if(typeof r!="string")throw(0,z.unreadable)(n,`its ${t} is ${(0,z.kindOf)(r)}, not a string`);return r}function lee(e,t){var n,r;if(Ka(e,"$ref"))throw(0,z.unreadable)(t,"it is a $ref, whose type is not guessed");let i=IE(e,"type",t),o=IE(e,"format",t),a=(n=i??o)!==null&&n!==void 0?n:"object";if(!Ka(e,"items"))return a;let s=e.items;if(!(0,z.isObject)(s))throw(0,z.unreadable)(t,`its items are ${(0,z.kindOf)(s)}, not an object`);if(Ka(s,"$ref"))throw(0,z.unreadable)(t,"its items are a $ref, whose type is not guessed");return`${a}<${(r=IE(s,"type",`${t} items`))!==null&&r!==void 0?r:"object"}>`}function cee(e,t){let n="The table schema";if(!(0,z.isObject)(e))throw(0,z.unreadable)(n,`it is ${(0,z.kindOf)(e)}, not an object`);let r=_E(e,"items","items"),i=_E(e,"schema","schema"),o=i?_E(i,"items","schema.items"):void 0,a=[[e,"the answer"],[r,"items"],[i,"schema"],[o,"schema.items"]],s=new Set;for(let[c,d]of a)if(c&&Ka(c,"required")){let f=c.required;if(!Array.isArray(f))throw(0,z.unreadable)(n,`the required of ${d} is ${(0,z.kindOf)(f)}, not an array`);f.forEach(p=>{if(typeof p!="string")throw(0,z.unreadable)(n,`the required of ${d} has an entry that is ${(0,z.kindOf)(p)}, not a string`);s.add(p.toLowerCase())})}let u;for(let[c,d]of a)if(c&&Ka(c,"properties")){if(!(0,z.isObject)(c.properties))throw(0,z.unreadable)(n,`the properties of ${d} are ${(0,z.kindOf)(c.properties)}, not an object`);u=c.properties;break}if(!u)throw(0,z.unreadable)(n,"it has no properties, items.properties, schema.properties or schema.items.properties");let l=Object.keys(u).map(c=>{let d=`Column '${(0,z.bounded)(c,80)}'`,f=u[c];if(!(0,z.isObject)(f))throw(0,z.unreadable)(d,`it is ${(0,z.kindOf)(f)}, not an object`);return{name:c,type:lee(f,d),required:s.has(c.toLowerCase())}});return{table:t,columns:l}}Pt.projectConnectorTableSchema=cee});var s$=C(Ng=>{"use strict";Object.defineProperty(Ng,"__esModule",{value:!0});Ng.PowerPlatformApiDiscovery=void 0;var DE=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,n,r=""){if(!/^[a-zA-Z0-9\-]+$/g.test(t))throw new Error(`Cannot generate Power Platform API endpoint because the ${n} 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 ${n} 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),u=this._getEnvironmentApiHostNameSuffix();return`${r}${s}.${a}.${n}.${u}`}_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}`)}}};Ng.PowerPlatformApiDiscovery=DE});var u$=C(_g=>{"use strict";Object.defineProperty(_g,"__esModule",{value:!0});_g.PowerPlatformApiDiscovery=void 0;var dee=s$();Object.defineProperty(_g,"PowerPlatformApiDiscovery",{enumerable:!0,get:function(){return dee.PowerPlatformApiDiscovery}})});var f$=C(zs=>{"use strict";Object.defineProperty(zs,"__esModule",{value:!0});zs.platformTokenAudience=zs.platformEnvironment=zs.platformClusterOf=void 0;var l$=u$(),c$=Y(),d$=Zu(),fee=/^[a-z0-9-]+\.crm(\d*)\.dynamics\.com$/,pee=/^[a-z0-9-]+\.crmtest\.dynamics\.com$/,mee=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,hee=/^default-/i;function PE(e,t=80){return e.length>t?`${e.slice(0,t)}\u2026`:e}function gee(e){try{return new URL(e).host.toLowerCase()}catch{return}}function yee(e){let t=gee(e);if(t){if(pee.test(t))return{cloud:"Test",category:"test"};let n=fee.exec(t);if(n&&n[1]!=="9")return{cloud:"Public",category:"prod"}}throw new c$.SdkError(d$.CONNECTIVITY_CLOUD_UNSUPPORTED_CODE,`The Power Platform API route is built for the Test and Public clouds; this org (${t?`'${PE(t)}'`:`'${PE(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.`)}zs.platformClusterOf=yee;function bee(e,t){let n=hee.test(e)?e.slice(8):e;if(!mee.test(n))throw new c$.SdkError(d$.CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE,`The environment of this org could not be verified: its name ('${PE(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 l$.PowerPlatformApiDiscovery(t).getEnvironmentEndpoint(e)}`,guid:n.toLowerCase()}}zs.platformEnvironment=bee;function vee(e){return new l$.PowerPlatformApiDiscovery(e).getTokenAudience()}zs.platformTokenAudience=vee});var m$=C(Tc=>{"use strict";Object.defineProperty(Tc,"__esModule",{value:!0});Tc.PlatformConnectivityApi=Tc.assertTabularCloud=void 0;var bo=Y(),RE=Zf(),je=Zu(),p$=f$(),Ja=OE(),kE="1";function $E(e){let t=(0,je.connectivityCloudOf)(e);if(t!=="Test"&&t!=="Public")throw new bo.SdkError(je.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.")}Tc.assertTabularCloud=$E;var LE=class{constructor(t,n,r,i){this.org=t,this.instanceUrl=n,this.client=r,this.runtime=i,this.records=new Map,this.swaggers=new Map}async listConnections(){let t=await this.resolveEnvironment(),n=[],r=new Set,i=await this.send(this.client,"GET",`${t.origin}/connectivity/connections?api-version=${kE}`,[401,403]),o=1,a=0;for(;;){let s=`Page ${o} of the connections`,u=i.body,l=u?.value;if(!Array.isArray(l))throw(0,je.unreadable)(s,`its value is ${(0,je.kindOf)(l)}, not an array`);for(let d of l){let f=(0,je.readConnection)(d,a,t.name);a+=1,f&&n.push(f)}let c=u?.nextLink;if(c==null)return n;if(typeof c!="string"||c.length===0)throw(0,je.unreadable)(s,`its nextLink is ${c===""?"an empty string":(0,je.kindOf)(c)}, not a non-empty string`);if(r.has(c))throw new bo.InvalidArgumentError(`listConnections: aborting pagination \u2014 the server returned a repeated nextLink ('${(0,je.bounded)(c)}'), which would loop indefinitely.`);r.add(c),this.assertSameOrigin(c,t.parsed),i=await this.send(this.client,"GET",c,[401,403]),o+=1}}async listConnectorOperations(t){let n=(0,je.connectorShortName)(t);return(0,RE.projectConnectorOperations)(await this.swagger(n))}async getConnectorOperationSchema(t,n){let r=(0,je.connectorShortName)(t);if(typeof n!="string"||n==="")throw new bo.InvalidArgumentError("operationId must be a non-empty string.");return(0,RE.projectConnectorOperationSchema)(await this.swagger(r),n)}async listConnectorTables(t,n,r){$E(this.instanceUrl);let i=(0,Ja.checkListTablesArguments)(t,n,r),o=(0,Ja.tablesSuffix)(i.short,i.dataset);return(0,Ja.projectConnectorTables)(await this.invokeTabular(i,o))}async getConnectorTableSchema(t,n,r,i){$E(this.instanceUrl);let o=(0,Ja.checkTableSchemaArguments)(t,n,r,i),a=(0,Ja.tableSchemaSuffix)(o.dataset,o.table);return(0,Ja.projectConnectorTableSchema)(await this.invokeTabular(o,a),o.table)}async invokeTabular(t,n){let r=this.requireRuntime(),i=await this.resolveEnvironment(),o=await this.record(t.short),a=(0,Ja.tabularRevision)(o,t.short),s=(0,Ja.runtimeAuthority)(o,{cloud:i.cloud,name:i.name,origin:i.origin},t.short),u=`${i.origin}/connectivity/connectors/${encodeURIComponent(t.short)}/connections/${encodeURIComponent(t.connectionId)}?$filter=${(0,je.environmentFilter)(i.name)}&api-version=${kE}`,l=(await this.send(this.client,"GET",u,[401,403])).body,c=(0,Ja.checkTabularConnection)(l,t.connectionId,t.short,i.name),d=`${s.path}/${c}${a===""?"":`/${a}`}${n}`;return(s.transport==="invoke"?await this.send(r,"POST",`${s.origin}/invoke`,[401],{"X-Ms-Request-Url":d,"X-Ms-Request-Method":"GET"}):await this.send(r,"GET",`${s.origin}${d}`,[401])).body}requireRuntime(){if(!this.runtime)throw new bo.SdkError(je.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:n}=(0,p$.platformClusterOf)(this.instanceUrl),r=await(0,je.readEnvironmentName)(this.org),{origin:i,guid:o}=(0,p$.platformEnvironment)(r,n),a=(0,je.parseUrl)(i);if(!a)throw(0,je.unreadable)("The Power Platform API origin",`'${(0,je.bounded)(i)}' is not a URL`);return{cloud:t,origin:i,parsed:a,name:r,guid:o}}cached(t,n,r){let i=t.get(n);if(!i){let o=r();i=o,t.set(n,o),o.catch(()=>{t.get(n)===o&&t.delete(n)})}return i}record(t){return this.cached(this.records,t.toLowerCase(),()=>this.readRecord(t))}async readRecord(t){let n=await this.resolveEnvironment(),r=`${n.origin}/connectivity/connectors/${encodeURIComponent(t)}?$filter=${(0,je.environmentFilter)(n.name)}&api-version=${kE}`,i=(await this.send(this.client,"GET",r,[401,403])).body,o=(0,je.isObject)(i)?i.name:void 0;if(!(0,je.isObject)(i)||typeof o!="string"||o.toLowerCase()!==t.toLowerCase())throw(0,je.unreadable)(`The connector '${(0,je.bounded)(t,80)}'`,`the record's name is ${typeof o=="string"?`'${(0,je.bounded)(o,80)}'`:(0,je.kindOf)(o)}, not the requested connector`);return i}swagger(t){return this.cached(this.swaggers,t.toLowerCase(),async()=>{let r=(await this.record(t)).properties,i=(0,je.isObject)(r)?r.swagger:void 0;if(!(0,je.isObject)(i))throw(0,je.unreadable)(`The connector '${(0,je.bounded)(t,80)}'`,`its properties.swagger is ${(0,je.kindOf)(i)}, not an object`);return(0,RE.validateConnectorSwagger)(i),i})}assertSameOrigin(t,n){let r=(0,je.parseUrl)(t);if(!r)throw new bo.InvalidArgumentError(`Refusing to follow a malformed absolute URL: '${(0,je.bounded)(t)}'`);if(!(0,je.sameOrigin)(r,n))throw new bo.InvalidArgumentError(`Refusing to follow a cross-origin link ('${(0,je.bounded)(r.origin,120)}' is not the environment's Power Platform API origin '${n.origin}'); server-driven pagination must stay on that origin.`)}async send(t,n,r,i,o){let a;try{a=n==="GET"?await t.get(r):await t.post(r,void 0,{headers:o})}catch(s){throw s instanceof bo.ConnectionError&&typeof s.statusCode=="number"&&s.statusCode>0?this.non2xx(r,s.statusCode,void 0,i,s):s instanceof bo.SdkError?s:new bo.ConnectionError(r,0,s instanceof Error?s.message:String(s),s)}if(!a||typeof a.status!="number")throw new bo.ConnectionError(r,0,"the transport returned no HTTP response");if(a.status>=200&&a.status<300)return a;throw this.non2xx(r,a.status,a.body,i)}non2xx(t,n,r,i,o){let a=o??new bo.ConnectionError(t,n,(0,je.messageOf)(r),r);return i.includes(n)?(0,je.connectivityUnauthorized)(n,r,a):a}};Tc.PlatformConnectivityApi=LE});var g$=C(Tg=>{"use strict";Object.defineProperty(Tg,"__esModule",{value:!0});Tg.ConnectivityRouter=void 0;var ME=Y(),wee=n$(),Ig=Zu(),h$=OE(),xE=m$(),FE=class{constructor(t,n,r){this.org=t,this.instanceUrl=n,this.clients=r}async listConnections(){return this.route().listConnections()}async listConnectorOperations(t){return this.route().listConnectorOperations(t)}async getConnectorOperationSchema(t,n){return this.route().getConnectorOperationSchema(t,n)}async listConnectorTables(t,n,r){return(0,xE.assertTabularCloud)(this.instanceUrl),(0,h$.checkListTablesArguments)(t,n,r),this.tabularRoute().listConnectorTables(t,n,r)}async getConnectorTableSchema(t,n,r,i){return(0,xE.assertTabularCloud)(this.instanceUrl),(0,h$.checkTableSchemaArguments)(t,n,r,i),this.tabularRoute().getConnectorTableSchema(t,n,r,i)}route(){return this.delegate||(this.delegate=this.select()),this.delegate}platformRoute(t){return this.platform||(this.platform=new xE.PlatformConnectivityApi(this.org,this.instanceUrl,t,this.clients.connectorRuntimeClient)),this.platform}tabularRoute(){let{powerPlatformApiClient:t,connectorRuntimeClient:n}=this.clients,r=[t?void 0:"powerPlatformApiClient (the Power Platform API)",n?void 0:"connectorRuntimeClient (API Hub, https://apihub.azure.com)"].filter(i=>i!==void 0);if(r.length>0||!t)throw new ME.SdkError(Ig.CONNECTIVITY_NOT_CONFIGURED_CODE,`Connector tables are read through the Power Platform API and the connector runtime: this SDK was created without MakerSdkOptions.${r.join(" or MakerSdkOptions.")}, an HttpClient that does not follow redirects. Nothing was requested.`);return this.platformRoute(t)}select(){let t=(0,Ig.connectivityCloudOf)(this.instanceUrl),{powerAppsServiceClient:n,powerPlatformApiClient:r}=this.clients;if(t==="Unsupported")throw new ME.SdkError(Ig.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(r)return this.platformRoute(r);if(t==="Public"&&n)return new wee.ConnectivityApi(this.org,this.instanceUrl,n);throw new ME.SdkError(Ig.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.")}};Tg.ConnectivityRouter=FE});var ia=C(ci=>{"use strict";Object.defineProperty(ci,"__esModule",{value:!0});ci.bytesToUtf8=ci.base64ToUtf8=ci.base64ToBytes=ci.bytesToBase64=ci.utf8ToBase64=ci.utf8ToBytes=void 0;var UE=32768,li="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";function Oc(){return globalThis}function y$(e){let t=[];for(let n=0;n<e.length;n+=1){let r=e.charCodeAt(n);if(r>=55296&&r<=56319){let i=n+1<e.length?e.charCodeAt(n+1):0;i>=56320&&i<=57343?(r=(r-55296<<10)+(i-56320)+65536,n+=1):r=65533}else r>=56320&&r<=57343&&(r=65533);r<128?t.push(r):r<2048?t.push(192|r>>6,128|r&63):r<65536?t.push(224|r>>12,128|r>>6&63,128|r&63):t.push(240|r>>18,128|r>>12&63,128|r>>6&63,128|r&63)}return Uint8Array.from(t)}function Eee(e){let t="";for(let n=0;n<e.length;n+=UE)t+=String.fromCharCode(...e.subarray(n,n+UE));return t}function Aee(e){let t="";for(let n=0;n<e.length;n+=1){let r=String.fromCharCode(e.charCodeAt(n)&255);if(r==="=")break;r==="-"?t+="+":r==="_"?t+="/":li.indexOf(r)>=0&&(t+=r)}for(t.length%4===1&&(t=t.slice(0,-1));t.length%4!==0;)t+="=";return t}function Cee(e){let t="",n=0;for(;n+2<e.length;n+=3){let i=e[n]<<16|e[n+1]<<8|e[n+2];t+=li[i>>18&63]+li[i>>12&63]+li[i>>6&63]+li[i&63]}let r=e.length-n;if(r===1){let i=e[n]<<16;t+=`${li[i>>18&63]}${li[i>>12&63]}==`}else if(r===2){let i=e[n]<<16|e[n+1]<<8,o=li[i>>18&63],a=li[i>>12&63],s=li[i>>6&63];t+=`${o}${a}${s}=`}return t}function See(e){let t=e.endsWith("==")?2:e.endsWith("=")?1:0,n=e.length/4*3-t,r=new Uint8Array(n>0?n:0),i=0;for(let o=0;o<e.length;o+=4){let a=li.indexOf(e[o])<<18|li.indexOf(e[o+1])<<12|(e[o+2]==="="?0:li.indexOf(e[o+2]))<<6|(e[o+3]==="="?0:li.indexOf(e[o+3]));i<n&&(r[i++]=a>>16&255),i<n&&(r[i++]=a>>8&255),i<n&&(r[i++]=a&255)}return r}function Nee(e){let t=Oc();if(t.Buffer)return new Uint8Array(t.Buffer.from(e,"utf8"));let n=t.TextEncoder;return n?new n().encode(e):y$(e)}ci.utf8ToBytes=Nee;function _ee(e){let t=Oc();if(t.Buffer)return t.Buffer.from(e,"utf8").toString("base64");let n=t.TextEncoder;return b$(n?new n().encode(e):y$(e))}ci.utf8ToBase64=_ee;function b$(e){let t=Oc();return t.Buffer?t.Buffer.from(e).toString("base64"):t.btoa?t.btoa(Eee(e)):Cee(e)}ci.bytesToBase64=b$;function v$(e){let t=Oc();if(t.Buffer)return new Uint8Array(t.Buffer.from(e,"base64"));let n=Aee(e);if(t.atob){let r=t.atob(n);return Uint8Array.from(r,i=>i.charCodeAt(0))}return See(n)}ci.base64ToBytes=v$;function w$(e){let t=[],n="",r=()=>{n+=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>=UE&&r()},o=0;for(;o<e.length;){let a=e[o],s=0,u=0,l=128,c=191;if(a<128){i(a),o+=1;continue}else if(a>=194&&a<=223)s=1,u=a&31;else if(a>=224&&a<=239)s=2,u=a&15,l=a===224?160:128,c=a===237?159:191;else if(a>=240&&a<=244)s=3,u=a&7,l=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<l||m>c){f=!1;break}l=128,c=191,u=u<<6|m&63}f?(i(u),o=d):(i(65533),o=d)}return r(),n}function Iee(e){let t=Oc();return t.Buffer?t.Buffer.from(e,"base64").toString("utf8"):w$(v$(e))}ci.base64ToUtf8=Iee;function Tee(e){let t=Oc();return t.Buffer?t.Buffer.from(e).toString("utf8"):w$(e)}ci.bytesToUtf8=Tee});var Ya=C(Le=>{"use strict";Object.defineProperty(Le,"__esModule",{value:!0});Le.originOf=Le.readEnvironment=Le.ReadBudget=Le.DEFAULT_LIMITS=Le.compareVersions=Le.parseVersion=Le.canonicalGuid=Le.ZERO_GUID=Le.byCodeUnit=Le.identityKey=Le.digestOf=Le.sha256Of=Le.canonicalJson=Le.safeDiagnostics=Le.promotionError=Le.promotionProblem=Le.PROMOTION_ERROR_CODES=void 0;var E$=Y(),Oee=ia(),qE={INVALID_ARGUMENT:"The promotion input is invalid",PROMOTION_CODEC_REQUIRED:"A host codec with callable inflateRaw and sha256 is required",PROMOTION_JOURNAL_REQUIRED:"A trusted atomic journal (begin, read, replace, release) is required to apply a plan",PROMOTION_JOURNAL_FAILED:"The attempt journal could not record this step; no further application write was sent and the reservation is kept",PROMOTION_PACKAGE_UNREADABLE:"The package is not a solution package this SDK reads safely",PROMOTION_PACKAGE_MODE_MISMATCH:"The selected import mode differs from the package's managed bit",PROMOTION_TARGET_MODE_MISMATCH:"The target's solution has the other managed bit; conversion is not an update",PROMOTION_ENVIRONMENT_MISMATCH:"The receiving environment is not the one the plan or receipt is bound to",PROMOTION_TENANT_MISMATCH:"The source and target environments are in different tenants",PROMOTION_SAME_ENVIRONMENT:"The source and target are the same organization",PROMOTION_SOURCE_PACKAGE_MISMATCH:"The package does not correspond to the named source solution as it is now",PROMOTION_APP_NOT_IN_PACKAGE:"The named app is not in the package",PROMOTION_COVERAGE_GAP:"A required component, file or field cannot be carried, matched or completely interpreted",PROMOTION_DEPENDENCY_MISSING:"A required component is neither in the package nor in the target",PROMOTION_DEPENDENCY_IDENTITY_UNRESOLVED:"A required component has no unambiguous supported identity",PROMOTION_COMPONENT_COLLISION:"An existing target component belongs to another owner, layer or identity",PROMOTION_DESTRUCTIVE_SCHEMA_CHANGE:"The import would change existing schema destructively",PROMOTION_VALUE_REQUIRED:"A required variable, or one with a packaged current value, needs a non-empty target value",PROMOTION_SECRET_VALUE:"Secret content would be uploaded, or a Secret input is not a reference",PROMOTION_CONNECTION_UNMAPPED:"A packaged connection reference has no target connection",PROMOTION_CONNECTION_NOT_IN_TARGET:"The mapped connection does not exist in the target",PROMOTION_CONNECTION_CONNECTOR_MISMATCH:"The mapped connection's connector differs from the reference's",PROMOTION_SETTING_UNAVAILABLE:"A required setting definition is neither incoming nor available in the target",PROMOTION_PUBLISH_REQUIRED:"A necessary additional app publication has not been authorized",PROMOTION_PUBLICATION_SCOPE_UNKNOWN:"The complete approved publication footprint cannot be established",PROMOTION_NON_ATOMIC_IMPORT_NOT_ACKNOWLEDGED:"acknowledgeNonAtomicImport must be exactly true",PROMOTION_READ_BUDGET_EXCEEDED:"A configured read budget was exhausted; the plan is incomplete",PROMOTION_VERIFICATION_UNAVAILABLE:"A required reader, condition or certified protocol is unavailable",PROMOTION_VERSION_REFUSED:"A fresh import of the same or an older version, or an unsupported version, is refused",PROMOTION_PUBLISHER_MISMATCH:"The target solution's publisher differs from the package's",PROMOTION_HOLDING_PRESENT:"A holding solution or patch on the target requires external reconciliation",PROMOTION_UPGRADE_NOT_SUPPORTED:"Upgrade, holding import and solution deletion are not supported",PROMOTION_PLAN_INVALID:"The plan is not a valid, unaltered plan for these package bytes",PROMOTION_PLAN_STALE:"A planned precondition changed on the target",PROMOTION_ATTEMPT_IN_PROGRESS:"Another promotion attempt holds this target",PROMOTION_RECEIPT_UNVERIFIED:"The attempt to resume cannot be authenticated against the journal",PROMOTION_STAGE_FAILED:"The package did not pass staging on the target; nothing was imported",PROMOTION_STAGE_UNKNOWN:"The staging outcome or its upload id could not be read; nothing was imported",PROMOTION_IMPORT_FAILED:"The import failed or was canceled",PROMOTION_IMPORT_UNKNOWN:"Whether the import was submitted or completed cannot be settled; it is never resent",PROMOTION_STEP_FAILED:"A planned step was refused or failed",PROMOTION_VERIFICATION_FAILED:"A required postcondition does not match, or could not be verified, after the import",PROMOTION_CLEANUP_FAILED:"The staged upload was not deleted; it remains in the target"};Le.PROMOTION_ERROR_CODES=Object.keys(qE);function A$(e,t,n={}){var r;return{code:e,phase:t,blocking:(r=n.blocking)!==null&&r!==void 0?r:!0,message:n.reason?`${qE[e]} (${n.reason}).`:`${qE[e]}.`,...n.subject?{subject:n.subject}:{},...n.stepId?{stepId:n.stepId}:{},...n.httpStatus!==void 0?{httpStatus:n.httpStatus}:{},...n.platformCode?{platformCode:n.platformCode}:{}}}Le.promotionProblem=A$;function ap(e,t,n={}){return new E$.PromotionError(A$(e,t,n))}Le.promotionError=ap;function C$(e){var t;let n={},r=e;r&&typeof r.statusCode=="number"&&r.statusCode>0&&(n.httpStatus=r.statusCode);let i=r?.cause,o=(t=i?.error)===null||t===void 0?void 0:t.code;return typeof o=="string"&&/^0x[0-9a-fA-F]{8}$/.test(o)&&(n.platformCode=o.toLowerCase()),n}Le.safeDiagnostics=C$;function sp(e){if(e===null)return"null";switch(typeof e){case"string":case"boolean":return JSON.stringify(e);case"number":if(!Number.isFinite(e))throw new TypeError("canonicalJson: a non-finite number");return JSON.stringify(e);case"object":{if(Array.isArray(e))return`[${e.map(r=>sp(r===void 0?null:r)).join(",")}]`;let t=e;return`{${Object.keys(t).filter(r=>t[r]!==void 0).sort((r,i)=>r<i?-1:r>i?1:0).map(r=>`${JSON.stringify(r)}:${sp(t[r])}`).join(",")}}`}default:throw new TypeError(`canonicalJson: a ${typeof e} is not JSON`)}}Le.canonicalJson=sp;async function S$(e,t){let n;try{n=await e.sha256(t)}catch{throw ap("PROMOTION_CODEC_REQUIRED","preflight",{reason:"sha256 failed"})}if(typeof n!="string"||!/^[0-9a-f]{64}$/.test(n))throw ap("PROMOTION_CODEC_REQUIRED","preflight",{reason:"sha256 did not return 64 lowercase hexadecimal characters"});return n}Le.sha256Of=S$;function Dee(e,t){return S$(e,(0,Oee.utf8ToBytes)(sp(t)))}Le.digestOf=Dee;function Pee(e){return sp(e)}Le.identityKey=Pee;function Ree(e,t){return e<t?-1:e>t?1:0}Le.byCodeUnit=Ree;var kee=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;Le.ZERO_GUID="00000000-0000-0000-0000-000000000000";function op(e){if(typeof e!="string")return;let t=e.trim().replace(/^\{([^}]*)\}$/,"$1").toLowerCase();return kee.test(t)?t:void 0}Le.canonicalGuid=op;function $ee(e){if(typeof e!="string")return;let t=e.split(".");if(t.length<2||t.length>4||t.some(r=>!/^\d{1,10}$/.test(r)))return;let n=t.map(Number);if(!n.some(r=>r>2147483647)){for(;n.length<4;)n.push(0);return n}}Le.parseVersion=$ee;function Lee(e,t){for(let n=0;n<4;n+=1)if(e[n]!==t[n])return e[n]<t[n]?-1:1;return 0}Le.compareVersions=Lee;Le.DEFAULT_LIMITS={maxCompressedBytes:50*1024*1024,maxExpandedBytes:256*1024*1024,maxEntries:1e4,maxComponents:1e3,maxGetAttempts:5e3,maxLayerPagesPerComponent:10,maxPlanMs:3e5};var BE=class{constructor(t,n,r){this.limits=t,this.now=n,this.timed=r,this.getAttempts=0,this.layerLookups=0,this.layerPages=0,this.components=0,this.exhausted=!1,this.started=n()}get elapsedMs(){return Math.max(0,this.now()-this.started)}exceeded(t){return this.exhausted=!0,ap("PROMOTION_READ_BUDGET_EXCEEDED","preflight",{reason:t})}checkTime(){if(this.timed&&this.elapsedMs>this.limits.maxPlanMs)throw this.exceeded("maxPlanMs")}spendGet(){if(this.checkTime(),this.getAttempts>=this.limits.maxGetAttempts)throw this.exceeded("maxGetAttempts");this.getAttempts+=1}spendLayerPage(t){if(t>=this.limits.maxLayerPagesPerComponent)throw this.exceeded("maxLayerPagesPerComponent");this.layerPages+=1}countComponents(t){if(this.components=t,t>this.limits.maxComponents)throw this.exceeded("maxComponents")}wrap(t){return{get:(r,i)=>(this.spendGet(),t.get(r,i)),post:(r,i,o)=>t.post(r,i,o),patch:(r,i,o)=>t.patch(r,i,o),delete:(r,i)=>t.delete(r,i)}}};Le.ReadBudget=BE;var Mee="/RetrieveCurrentOrganization(AccessType=@p1)?@p1=Microsoft.Dynamics.CRM.EndpointAccessType'Default'";async function xee(e){var t,n;let r=(l,c)=>c instanceof E$.PromotionError?c:ap("PROMOTION_VERIFICATION_UNAVAILABLE","preflight",{reason:l,...C$(c)}),i,o;try{let l=await e.get("/WhoAmI"),c=await e.get(Mee);if(l.status!==200||c.status!==200)throw r("the environment identity could not be read");i=l.body,o=(n=(t=c.body)===null||t===void 0?void 0:t.Detail)!==null&&n!==void 0?n:null}catch(l){throw r("the environment identity could not be read",l)}let a=op(i?.UserId),s=op(o?.OrganizationId),u=op(o?.TenantId);if(!a||!s||!u||op(i?.OrganizationId)!==s)throw r("the environment identity answers are incomplete or disagree");return{organizationId:s,tenantId:u,actorId:a,instanceUrl:N$(e)}}Le.readEnvironment=xee;function N$(e){let t=e.apiUrl("/"),n=/^([a-z][a-z0-9+.-]*:\/\/[^/?#]+)/i.exec(t);return(n?n[1]:t).toLowerCase()}Le.originOf=N$});var T$=C(Dc=>{"use strict";Object.defineProperty(Dc,"__esModule",{value:!0});Dc.readZip=Dc.crc32=void 0;var Fee=Y(),Uee=Ya(),qee=67324752,Bee=33639248,Vee=101010256,Gee=117853008,jee=134695760,Wee=1,_$=8,zee=64,Hee=2048;function We(e){return new Fee.PromotionError((0,Uee.promotionProblem)("PROMOTION_PACKAGE_UNREADABLE","preflight",{reason:e}))}var Og;function I$(e){if(!Og){Og=new Uint32Array(256);for(let n=0;n<256;n+=1){let r=n;for(let i=0;i<8;i+=1)r=r&1?3988292384^r>>>1:r>>>1;Og[n]=r>>>0}}let t=4294967295;for(let n=0;n<e.length;n+=1)t=Og[(t^e[n])&255]^t>>>8;return(t^4294967295)>>>0}Dc.crc32=I$;var Lr=(e,t)=>{if(t+2>e.length)throw We("a header runs past the end of the archive");return e[t]|e[t+1]<<8},tr=(e,t)=>{if(t+4>e.length)throw We("a header runs past the end of the archive");return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0};function Kee(e,t){let n=!0;for(let r of e)r>=128&&(n=!1);if(n)return String.fromCharCode(...Array.from(e));if(!t)throw We("an entry name is neither ASCII nor flagged UTF-8");try{return decodeURIComponent(Array.from(e,r=>`%${r.toString(16).padStart(2,"0")}`).join(""))}catch{throw We("an entry name is not valid UTF-8")}}function Jee(e){if(e.length===0||e.startsWith("/")||e.includes("\\")||/^[A-Za-z]:/.test(e)||/[\u0000-\u001f\u007f]/.test(e))throw We("an entry path is absolute, uses a backslash or drive, or carries a control character");if(e.replace(/\/$/,"").split("/").some(n=>n===""||n==="."||n===".."))throw We('an entry path has an empty, "." or ".." segment')}function Yee(e){let t=Math.max(0,e.length-22-65535);for(let n=e.length-22;n>=t;n-=1)if(tr(e,n)===Vee&&n+22+Lr(e,n+20)===e.length)return n;throw We("no end-of-central-directory record")}async function Qee(e,t,n){if(e.length>n.maxCompressedBytes)throw We("the package is larger than maxCompressedBytes");let r=Yee(e),i=Lr(e,r+4),o=Lr(e,r+6),a=Lr(e,r+8),s=Lr(e,r+10),u=tr(e,r+12),l=tr(e,r+16);if(i!==0||o!==0||a!==s)throw We("a multi-disk archive");if(s===65535||u===4294967295||l===4294967295||r>=20&&tr(e,r-20)===Gee)throw We("a ZIP64 archive");if(s>n.maxEntries)throw We("more entries than maxEntries");if(l+u!==r)throw We("the central directory does not end where the end record begins");let c=new Set,d=[],f=[],p=0,m=l;for(let h=0;h<s;h+=1){if(tr(e,m)!==Bee)throw We("a central directory header is missing");let g=Lr(e,m+8),y=Lr(e,m+10),b=tr(e,m+16),E=tr(e,m+20),w=tr(e,m+24),_=Lr(e,m+28),I=Lr(e,m+30),T=Lr(e,m+32),O=Lr(e,m+34),v=tr(e,m+42);if(m+46+_>r)throw We("a central directory header runs past the directory");let N=e.subarray(m+46,m+46+_);if(m+=46+_+I+T,m>r)throw We("a central directory header runs past the directory");if(g&(Wee|zee))throw We("an encrypted entry");if(O!==0)throw We("a multi-disk archive");if(E===4294967295||w===4294967295||v===4294967295)throw We("a ZIP64 entry");if(y!==0&&y!==8)throw We("an entry compressed by a method other than stored or deflate");if(y===0&&E!==w)throw We("a stored entry whose sizes differ");let S=Kee(N,(g&Hee)!==0);Jee(S);let R=S.toLowerCase();if(c.has(R))throw We("two entries share one path (case-insensitively)");if(c.add(R),tr(e,v)!==qee)throw We("a local header is missing");let x=Lr(e,v+6),G=Lr(e,v+8),U=Lr(e,v+26),M=Lr(e,v+28),q=e.subarray(v+30,v+30+U);if(x!==g||G!==y||U!==_||q.some((wt,Fn)=>wt!==N[Fn])||!(g&_$)&&(tr(e,v+14)!==b||tr(e,v+18)!==E||tr(e,v+22)!==w))throw We("a local header disagrees with its central directory header");let X=v+30+U+M,ye=X+E;if(g&_$){let wt=tr(e,ye)===jee,Fn=ye+(wt?4:0);if(tr(e,Fn)!==b||tr(e,Fn+4)!==E||tr(e,Fn+8)!==w)throw We("a data descriptor disagrees with its central directory header");ye=Fn+12}if(ye>l)throw We("an entry overlaps the central directory");if(d.push([v,ye]),S.endsWith("/")){if(w!==0)throw We("a directory entry carries data");continue}if(p+=w,p>n.maxExpandedBytes)throw We("the package expands past maxExpandedBytes");let Ve=e.subarray(X,X+E),_e;if(y===0)_e=Ve.slice();else{try{_e=await t.inflateRaw(Ve.slice(),w)}catch{throw We("an entry could not be inflated within its declared size")}if(!(_e instanceof Uint8Array))throw We("the codec did not return bytes")}if(_e.length!==w)throw We("an entry inflated to a size other than declared");if(I$(_e)!==b)throw We("an entry does not match its CRC");f.push({name:S,bytes:_e})}d.sort((h,g)=>h[0]-g[0]);for(let h=1;h<d.length;h+=1)if(d[h][0]<d[h-1][1])throw We("two entries overlap");return f}Dc.readZip=Qee});var Pg=C(it=>{"use strict";Object.defineProperty(it,"__esModule",{value:!0});it.pickFields=it.projectRow=it.columnsOf=it.SEARCH_FIELDS=it.SOLUTION_FIELDS=it.ADDRESS_FIELDS=it.PUBLISHER_FIELDS=it.REFERENCE_FIELDS=it.VARIABLE_FIELDS=it.APP_SETTING_FIELDS=it.APP_FIELDS=it.SITEMAP_FIELDS=it.ROLE_FIELDS=it.WEB_RESOURCE_FIELDS=void 0;var di=(e,t)=>({element:e,column:t,kind:"text"}),zn=(e,t)=>({element:e,column:t,kind:"int"}),O$=(e,t)=>({element:e,column:t,kind:"flag"}),Dg=(e,t)=>({element:e,column:t,kind:"word"}),Hs=(e,t)=>({element:e,column:t,kind:"managed"}),Qa=(e,t,n)=>({element:e,column:n,kind:"label",item:t});it.WEB_RESOURCE_FIELDS={displayName:di("DisplayName","displayname"),description:di("Description","description"),languageCode:zn("LanguageCode","languagecode"),introducedVersion:di("IntroducedVersion","introducedversion"),enabledForMobileClient:O$("IsEnabledForMobileClient","isenabledformobileclient"),availableForMobileOffline:O$("IsAvailableForMobileOffline","isavailableformobileoffline"),customizable:Hs("IsCustomizable","iscustomizable"),canBeDeleted:Hs("CanBeDeleted","canbedeleted"),hidden:Hs("IsHidden","ishidden")};it.ROLE_FIELDS={customizable:Hs("IsCustomizable","iscustomizable"),autoAssigned:zn("IsAutoAssigned","isautoassigned"),inherited:zn("IsInherited","isinherited"),description:di("Description","description")};it.SITEMAP_FIELDS={collapsibleGroups:Dg("EnableCollapsibleGroups","enablecollapsiblegroups"),showHome:Dg("ShowHome","showhome"),showPinned:Dg("ShowPinned","showpinned"),showRecents:Dg("ShowRecents","showrecents"),name:Qa("LocalizedNames","LocalizedName","sitemapname")};it.APP_FIELDS={name:Qa("LocalizedNames","LocalizedName","name"),description:Qa("Descriptions","Description","description"),introducedVersion:di("IntroducedVersion","introducedversion"),optimizedFor:di("OptimizedFor","optimizedfor"),stateCode:zn("statecode","statecode"),statusCode:zn("statuscode","statuscode"),formFactor:zn("FormFactor","formfactor"),clientType:zn("ClientType","clienttype"),navigationType:zn("NavigationType","navigationtype")};it.APP_SETTING_FIELDS={customizable:Hs("iscustomizable","iscustomizable")};it.VARIABLE_FIELDS={displayName:Qa("displayname","label","displayname"),description:Qa("description","label","description"),introducedVersion:di("introducedversion","introducedversion"),customizable:Hs("iscustomizable","iscustomizable"),secretStore:zn("secretstore","secretstore"),valueSchema:di("valueschema","valueschema")};it.REFERENCE_FIELDS={displayName:di("connectionreferencedisplayname","connectionreferencedisplayname"),description:di("description","description"),customizable:Hs("iscustomizable","iscustomizable"),promptingBehavior:zn("promptingbehavior","promptingbehavior"),stateCode:zn("statecode","statecode"),statusCode:zn("statuscode","statuscode")};it.PUBLISHER_FIELDS={friendlyName:Qa("LocalizedNames","LocalizedName","friendlyname"),description:Qa("Descriptions","Description","description"),email:di("EMailAddress","emailaddress"),website:di("SupportingWebsiteUrl","supportingwebsiteurl"),optionValuePrefix:zn("CustomizationOptionValuePrefix","customizationoptionvalueprefix")};var Xee=e=>({[`address${e}TypeCode`]:zn("AddressTypeCode",`address${e}_addresstypecode`),[`address${e}ShippingMethodCode`]:zn("ShippingMethodCode",`address${e}_shippingmethodcode`)});it.ADDRESS_FIELDS=Xee;it.SOLUTION_FIELDS={friendlyName:Qa("LocalizedNames","LocalizedName","friendlyname"),description:Qa("Descriptions","Description","description")};it.SEARCH_FIELDS={name:di("name","name"),appModuleUniqueName:di("appmoduleuniquename","appmoduleuniquename"),customizable:Hs("iscustomizable","iscustomizable"),searchType:zn("searchtype","searchtype"),stateCode:zn("statecode","statecode"),statusCode:zn("statuscode","statuscode")};function Zee(...e){let t=new Set;for(let n of e)for(let r of Object.values(n))t.add(r.column);return[...t].sort()}it.columnsOf=Zee;function ete(e,t){if(e===null)return null;switch(t){case"text":case"label":return typeof e=="string"?e===""?null:e:void 0;case"int":return typeof e=="number"&&Number.isSafeInteger(e)?e:void 0;case"flag":case"word":return typeof e=="boolean"?e:void 0;case"managed":{let n=typeof e=="object"?e.Value:e;return typeof n=="boolean"?n:void 0}default:return}}function tte(e,...t){let n={};for(let r of t)for(let i of Object.keys(r).sort()){let o=r[i];if(!(o.column in e))return;let a=ete(e[o.column],o.kind);if(a===void 0)return;n[i]=a}return n}it.projectRow=tte;function nte(e,t){let n={};for(let r of[...t].sort())r in e&&(n[r]=e[r]);return n}it.pickFields=nte});var kg=C(Rt=>{"use strict";Object.defineProperty(Rt,"__esModule",{value:!0});Rt.readPackage=Rt.canonicalSitemapText=Rt.canonicalElement=Rt.SECRET_TYPE=Rt.VARIABLE_TYPES=Rt.COMPONENT=Rt.PACKAGE_PROJECTION_VERSION=void 0;var rte=Ms(),VE=ia(),Qt=Ya(),ite=T$(),sn=Pg();Rt.PACKAGE_PROJECTION_VERSION="promotion-package-v2";Rt.COMPONENT={role:20,webResource:61,sitemap:62,app:80,variable:380};Rt.VARIABLE_TYPES=new Set([1e8,100000001,100000002,100000003,100000004,100000005]);Rt.SECRET_TYPE=100000005;function Ee(e){return(0,Qt.promotionError)("PROMOTION_PACKAGE_UNREADABLE","preflight",{reason:e})}var nl=(e,t)=>({kind:"unsupportedComponent",componentType:e,packageId:t}),Ki="a field this version does not verify",yr="an attribute this version does not interpret",ote="a localized label in another language";function up(e,t){let n=(0,VE.bytesToUtf8)(e).replace(/^\uFEFF/,"");if(/<!DOCTYPE|<!ENTITY/i.test(n))throw Ee(`${t} declares a document type or entity`);let r=[],i=s=>r.push(s),o=new rte.DOMParser({errorHandler:{warning:i,error:i,fatalError:i}}).parseFromString(n,"text/xml"),a=o?.documentElement;if(!a||r.length>0)throw Ee(`${t} is not well-formed XML`);return a}function qt(e){let t=[];for(let n=0;n<e.childNodes.length;n+=1){let r=e.childNodes[n];r.nodeType===1&&t.push(r)}return t}function $$(e){var t;return qt(e).length>0||e.attributes.length>0?!1:((t=e.textContent)!==null&&t!==void 0?t:"").trim()===""}function Mr(e,t){let n=qt(e).filter(r=>r.nodeName===t);if(n.length>1)throw Ee(`an element holds <${t}> twice`);return n[0]}function Ks(e,t){var n;let r=Mr(e,t);if(!r)return null;if(qt(r).length>0)throw Ee(`<${t}> is not a text element`);return(n=r.textContent)!==null&&n!==void 0?n:""}function Hi(e,t){let n=Ks(e,t);if(n===null||n.trim()==="")throw Ee(`a required <${t}> is missing or empty`);return n.trim()}function Js(e,t){if(e===null||e.trim()==="")return null;if(!/^-?\d{1,10}$/.test(e.trim()))throw Ee(`${t} is not a whole number`);return Number(e.trim())}function oa(e,t){return qt(e).some(n=>!t.has(n.nodeName))}function In(e,t){for(let n=0;n<e.attributes.length;n+=1)if(!t.includes(e.attributes[n].name))return!0;return!1}function D$(e,t){let n=e.trim().toLowerCase();if(n==="")return null;let[r,i]=t?["true","false"]:["1","0"];if(n===r)return!0;if(n===i)return!1;throw Ee(t?"a field is neither True nor False":"a field is neither 0 nor 1")}function vo(e,t,n,r){var i;let o={};for(let a of Object.keys(t).sort(Qt.byCodeUnit)){let s=t[a],u=Mr(e,s.element);if(!u)continue;if(s.kind==="label"){In(u,["default"])&&r(yr);let c=qt(u);if(c.some(p=>p.nodeName!==s.item))throw Ee("a localized label list holds another element");c.some(p=>In(p,["description","languagecode"]))&&r(yr),c.some(p=>p.getAttribute("languagecode")!==String(n))&&r(ote);let d=c.find(p=>p.getAttribute("languagecode")===String(n)),f=d?d.getAttribute("description"):u.getAttribute("default");o[a]=f===null||f===""?null:f;continue}if(In(u,["xsi:nil"])&&r(yr),qt(u).length>0)throw Ee("a field element is not a text element");let l=u.getAttribute("xsi:nil")==="true"?"":(i=u.textContent)!==null&&i!==void 0?i:"";switch(s.kind){case"text":o[a]=l===""?null:l;break;case"int":o[a]=Js(l,"a numeric field");break;case"word":o[a]=D$(l,!0);break;default:o[a]=D$(l,!1)}}return o}var aa=(e,...t)=>new Set([...e,...t.flatMap(n=>Object.values(n).map(r=>r.element))]);function Rg(e){var t,n;let r=[];for(let o=0;o<e.attributes.length;o+=1){let a=e.attributes[o];r.push(`${a.name}=${JSON.stringify(a.value)}`)}r.sort(Qt.byCodeUnit);let i=[];for(let o=0;o<e.childNodes.length;o+=1){let a=e.childNodes[o];a.nodeType===1?i.push(Rg(a)):(a.nodeType===3||a.nodeType===4)&&((t=a.nodeValue)!==null&&t!==void 0?t:"").trim()!==""&&i.push(JSON.stringify(((n=a.nodeValue)!==null&&n!==void 0?n:"").trim()))}return`<${e.nodeName}${r.length?` ${r.join(" ")}`:""}>${i.join("")}</${e.nodeName}>`}Rt.canonicalElement=Rg;function ate(e){try{return Rg(up((0,VE.utf8ToBytes)(e),"sitemap"))}catch{return}}Rt.canonicalSitemapText=ate;var ste=aa(["UniqueName","Version","Managed","Publisher","RootComponents","MissingDependencies"],sn.SOLUTION_FIELDS),ute=aa(["UniqueName","CustomizationPrefix","Addresses"],sn.PUBLISHER_FIELDS),P$="AddressNumber",R$={Entities:1,optionsets:9,EntityRelationships:10,Workflows:29,Templates:36,EntityMaps:46,FieldSecurityProfiles:70,OrganizationSettings:0,EntityDataProviders:0,CustomControls:66,SolutionPluginAssemblies:91,SdkMessageProcessingSteps:92},lte=new Set(["Assets","botcomponents","CanvasApps","connectionreferences","Controls","customapis","dvtablesearchs","environmentvariabledefinitions","Formulas","Other","PluginAssemblies","Reports","Templates","WebResources","Workflows"]),cte=aa(["RolePrivileges"],sn.ROLE_FIELDS),dte=aa(["WebResourceId","Name","WebResourceType","FileName"],sn.WEB_RESOURCE_FIELDS),fte=aa(["SiteMapUniqueName","SiteMap","Descriptions"],sn.SITEMAP_FIELDS),pte=aa(["UniqueName","WebResourceId","AppModuleComponents","AppModuleRoleMaps","appsettings"],sn.APP_FIELDS),mte=aa(["value"],sn.APP_SETTING_FIELDS),hte=aa(["connectorid"],sn.REFERENCE_FIELDS),gte=aa(["defaultvalue","isrequired","type"],sn.VARIABLE_FIELDS),yte=aa(["m365appmoduleid"],sn.SEARCH_FIELDS),bte=["GenPageId","Page","DefaultDashboard"],k$=/^\$webresource:/i;async function vte(e,t,n){var r,i,o,a,s,u;let l=await(0,Qt.sha256Of)(t,e),c=await(0,ite.readZip)(e,t,n),d=new Map(c.map(W=>[W.name,W])),f=new Set(["[Content_Types].xml"]),p=[],m=W=>{let Fe=d.get(W);if(!Fe)throw Ee("a file the package names is missing");return f.add(W),Fe.bytes},h=up(m("solution.xml"),"solution.xml");if(h.nodeName!=="ImportExportXml")throw Ee("solution.xml is not an ImportExportXml document");let g=Mr(h,"SolutionManifest");if(!g)throw Ee("solution.xml has no SolutionManifest");qt(g).forEach((W,Fe)=>{ste.has(W.nodeName)||p.push({subject:nl(0,`solution.xml#SolutionManifest/${Fe+1}`),reason:"an unrecognized manifest element"})});let y=(r=Js(h.getAttribute("languagecode"),"languagecode"))!==null&&r!==void 0?r:1033,b=Hi(g,"UniqueName"),E={kind:"solution",uniqueName:b},w=W=>Fe=>{p.some(Ie=>Ie.reason===Fe&&JSON.stringify(Ie.subject)===JSON.stringify(W))||p.push({subject:W,reason:Fe})},_=vo(g,sn.SOLUTION_FIELDS,y,w(E)),I=Hi(g,"Version");if(!(0,Qt.parseVersion)(I))throw Ee("the solution version is not a numeric version");let T=Hi(g,"Managed");if(T!=="0"&&T!=="1")throw Ee("the managed bit is neither 0 nor 1");let O=Mr(g,"Publisher");if(!O)throw Ee("the manifest has no Publisher");let v=Hi(O,"UniqueName"),N=Hi(O,"CustomizationPrefix"),S=w({kind:"publisher",uniqueName:v});(oa(O,ute)||In(O,[]))&&S(Ki);let R={...vo(O,sn.PUBLISHER_FIELDS,y,S),...wte(Mr(O,"Addresses"),S)},x=[],G=Mr(g,"RootComponents");for(let W of G?qt(G):[]){if(W.nodeName!=="RootComponent")throw Ee("RootComponents holds an element that is not a RootComponent");let Fe=Js(W.getAttribute("type"),"a root component type");if(Fe===null)throw Ee("a root component has no type");let Ie=W.getAttribute("id"),At=Ie&&(i=(0,Qt.canonicalGuid)(Ie))!==null&&i!==void 0?i:null;if(Ie&&!At)throw Ee("a root component id is not a GUID");let Ts=W.getAttribute("schemaName")||null;(In(W,["type","id","schemaName","behavior"])||((o=W.getAttribute("behavior"))!==null&&o!==void 0?o:"0")!=="0")&&p.push({subject:nl(Fe,At??Ts),reason:yr}),x.push({type:Fe,id:At,schemaName:Ts})}let U=[],M=Mr(g,"MissingDependencies");for(let W of M?qt(M):[]){let Fe=W.nodeName==="MissingDependency"?Mr(W,"Required"):void 0;if(!Fe)throw Ee("a MissingDependency has no Required");let Ie=Fe.getAttribute("id");U.push({type:(a=Fe.getAttribute("type"))!==null&&a!==void 0?a:"",schemaName:Fe.getAttribute("id.schemaname")||Fe.getAttribute("schemaName")||null,uniqueName:Fe.getAttribute("id.uniquename")||null,id:Ie&&(s=(0,Qt.canonicalGuid)(Ie))!==null&&s!==void 0?s:null})}let q=up(m("customizations.xml"),"customizations.xml");if(q.nodeName!=="ImportExportXml")throw Ee("customizations.xml is not an ImportExportXml document");let X=[],ye=[],Ve=[],_e=[],wt=[],Fn=new Set;qt(q).forEach((W,Fe)=>{let Ie=W.nodeName;if(Fn.has(Ie))throw Ee("customizations.xml holds one container twice");switch(Fn.add(Ie),Ie){case"Roles":for(let At of qt(W))wt.push(Ete(At,p,y));break;case"WebResources":for(let At of qt(W))Ve.push(Ate(At,p,m,y));break;case"AppModuleSiteMaps":for(let At of qt(W))ye.push(Nte(At,p,y));break;case"AppModules":for(let At of qt(W))X.push(_te(At,p,y));break;case"connectionreferences":for(let At of qt(W))_e.push(Ite(At,p,y));break;case"Languages":for(let At of qt(W))if(At.nodeName!=="Language"||Js(At.textContent,"a language")===null)throw Ee("Languages holds something other than a language code");break;default:if(!$$(W)){let At=Object.prototype.hasOwnProperty.call(R$,Ie),Ts=At?R$[Ie]:0;p.push({subject:nl(Ts,At?`customizations.xml#${Ie}`:`customizations.xml#${Fe+1}`),reason:Ts?"a component kind without a certified provider":"an unrecognized customizations element"})}}});let xe=[],Et=[];for(let W of c){let Fe=/^environmentvariabledefinitions\/([^/]+)\/environmentvariabledefinition\.xml$/.exec(W.name);Fe&&(f.add(W.name),xe.push(Tte(W.bytes,Fe[1],d,f,p,y)));let Ie=/^dvtablesearchs\/([^/]+)\/dvtablesearch\.xml$/.exec(W.name);Ie&&(f.add(W.name),Et.push(Ote(W.bytes,Ie[1],p,y)))}let zt=new Set;c.forEach((W,Fe)=>{if(!f.has(W.name)){let Ie=W.name.includes("/")?W.name.slice(0,W.name.indexOf("/")):"";zt.add(lte.has(Ie)?Ie:`entry#${Fe+1}`)}});for(let W of[...zt].sort(Qt.byCodeUnit))p.push({subject:nl(0,W),reason:"a package file no certified provider reads"});for(let W of Et)X.some(Fe=>Fe.uniqueName.toLowerCase()===W.appUniqueName.toLowerCase())||p.push({subject:{kind:"appSearch",packageId:W.id,appUniqueName:W.appUniqueName},reason:"a search row of an app outside the package"});for(let W of x)W.type===Rt.COMPONENT.role&&wt.some(Ie=>Ie.id===W.id)||W.type===Rt.COMPONENT.webResource&&Ve.some(Ie=>Ie.name===W.schemaName)||W.type===Rt.COMPONENT.sitemap&&ye.some(Ie=>Ie.uniqueName===W.schemaName)||W.type===Rt.COMPONENT.app&&X.some(Ie=>Ie.uniqueName===W.schemaName)||W.type===Rt.COMPONENT.variable&&xe.some(Ie=>Ie.schemaName===W.schemaName)||W.type>=1e4&&_e.some(Ie=>Ie.logicalName===W.schemaName)||p.push({subject:nl(W.type,(u=W.id)!==null&&u!==void 0?u:W.schemaName),reason:"a root component this version does not project, or one the package does not define"});let Ht=(W,Fe)=>W.sort((Ie,At)=>(0,Qt.byCodeUnit)(Fe(Ie),Fe(At)));return{sha256:l,solutionUniqueName:b,version:I,managed:T==="1",publisherUniqueName:v,publisherPrefix:N,languageCode:y,solutionFields:_,publisherFields:R,apps:Ht(X,W=>W.uniqueName),sitemaps:Ht(ye,W=>W.uniqueName),webResources:Ht(Ve,W=>W.name),variables:Ht(xe,W=>W.schemaName),references:Ht(_e,W=>W.logicalName),roles:Ht(wt,W=>W.id),searches:Ht(Et,W=>W.id),dependencies:U,gaps:p,componentCount:X.length+ye.length+Ve.length+xe.length+_e.length+wt.length+Et.length+p.length}}Rt.readPackage=vte;function wte(e,t){var n;if(!e)return{};In(e,[])&&t(yr);let r={};for(let i of qt(e)){let o=Js(Ks(i,P$),"an address number");if(i.nodeName!=="Address"||o!==1&&o!==2||In(i,[])){t(Ki);continue}let a=(0,sn.ADDRESS_FIELDS)(o),s=new Set([P$,...Object.values(a).map(u=>u.element)]);for(let u of qt(i)){let l=u.getAttribute("xsi:nil")==="true"&&((n=u.textContent)!==null&&n!==void 0?n:"")==="";!s.has(u.nodeName)&&!l&&t(Ki)}Object.assign(r,vo(i,a,0,t))}return r}function Ete(e,t,n){var r;if(e.nodeName!=="Role")throw Ee("Roles holds an element that is not a Role");let i=(0,Qt.canonicalGuid)(e.getAttribute("id"));if(!i)throw Ee("a Role has no GUID id");let o=u=>t.push({subject:nl(Rt.COMPONENT.role,i),reason:u});oa(e,cte)&&o(Ki),In(e,["id","name"])&&o(yr);let a=[],s=Mr(e,"RolePrivileges");for(let u of s?qt(s):[]){let l=u.getAttribute("name"),c=u.getAttribute("level");if(u.nodeName!=="RolePrivilege"||!l||!c)throw Ee("a RolePrivilege has no name or level");In(u,["name","level"])&&o(yr),a.push(`${l}:${c}`)}return{id:i,name:(r=e.getAttribute("name"))!==null&&r!==void 0?r:"",privileges:[...new Set(a)].sort(Qt.byCodeUnit),fields:vo(e,sn.ROLE_FIELDS,n,o)}}function Ate(e,t,n,r){if(e.nodeName!=="WebResource")throw Ee("WebResources holds an element that is not a WebResource");let i=(0,Qt.canonicalGuid)(Hi(e,"WebResourceId"));if(!i)throw Ee("a WebResourceId is not a GUID");let o=Hi(e,"Name"),a=Js(Hi(e,"WebResourceType"),"WebResourceType"),s=l=>t.push({subject:{kind:"webResource",name:o},reason:l});oa(e,dte)&&s(Ki),In(e,[])&&s(yr);let u=Hi(e,"FileName").replace(/^\//,"");return{id:i,name:o,type:a,fileName:u,bytes:n(u),fields:vo(e,sn.WEB_RESOURCE_FIELDS,r,s)}}function Cte(e){var t,n,r;let i=e.trim();if(k$.test(i)){let f=i.replace(k$,"").split("?")[0].trim();return f===""?{unsupported:!0}:{resource:f}}let o=i.indexOf("#"),a=o<0?i:i.slice(0,o),s=a.indexOf("?"),u=s<0?a:a.slice(0,s),l=s<0?"":a.slice(s+1),c=f=>{try{return decodeURIComponent(f)}catch{return}},d=u.toLowerCase();if(d.includes("webresources/")){let f=d.indexOf("/webresources/");if(f<0)return{unsupported:!0};let p=u.slice(0,f);if(p!==""&&!/^\/(\{[^/{}]*\}|%7b[^/]*%7d)$/i.test(p))return{unsupported:!0};let m=c(u.slice(f+14));return m===void 0||m.trim()===""?{unsupported:!0}:{resource:m}}if(/(^|\/)main\.aspx$/i.test(u)){let f=new Map;for(let h of l.split("&")){let g=h.indexOf("="),y=c(g<0?h:h.slice(0,g)),b=c(g<0?"":h.slice(g+1).replace(/\+/g," "));if(y===void 0||b===void 0)return{unsupported:!0};f.set(y.toLowerCase(),b)}let p=(t=f.get("pagetype"))===null||t===void 0?void 0:t.toLowerCase(),m=/^\/?main\.aspx$/i.test(u);if(p==="webresource"){let h=(n=f.get("webresourcename"))!==null&&n!==void 0?n:"";return h===""||!m?{unsupported:!0}:{resource:h}}if(p==="entitylist"||p==="entityrecord"||p===void 0&&f.has("etn")){let h=(r=f.get("etn"))!==null&&r!==void 0?r:"";return h===""||!m?{unsupported:!0}:{table:h.toLowerCase()}}return p===void 0?{}:{unsupported:!0}}return{}}function Ste(e){let t=new Set,n=new Set,r=!1,i=o=>{for(let a=0;a<o.attributes.length;a+=1){let{name:s,value:u}=o.attributes[a],l=Cte(u);l.resource!==void 0?t.add(l.resource):l.table!==void 0?n.add(l.table):l.unsupported?r=!0:s==="Entity"&&u.trim()!==""?n.add(u.trim().toLowerCase()):bte.includes(s)&&u.trim()!==""&&(r=!0)}qt(o).forEach(i)};return i(e),{webResources:[...t].sort(Qt.byCodeUnit),tables:[...n].sort(Qt.byCodeUnit),unsupported:r}}function Nte(e,t,n){if(e.nodeName!=="AppModuleSiteMap")throw Ee("AppModuleSiteMaps holds an element that is not an AppModuleSiteMap");let r=Hi(e,"SiteMapUniqueName"),i=u=>t.push({subject:{kind:"sitemap",uniqueName:r},reason:u});oa(e,fte)&&i(Ki),In(e,[])&&i(yr);let o=Mr(e,"Descriptions");o&&!$$(o)&&i(Ki);let a=Mr(e,"SiteMap");if(!a)throw Ee("an AppModuleSiteMap has no SiteMap");let s=Ste(a);return s.unsupported&&i("a sitemap link of a kind without a certified provider"),{uniqueName:r,canonicalXml:Rg(a),fields:vo(e,sn.SITEMAP_FIELDS,n,i),webResources:s.webResources,tables:s.tables}}function _te(e,t,n){var r,i,o;if(e.nodeName!=="AppModule")throw Ee("AppModules holds an element that is not an AppModule");let a=Hi(e,"UniqueName"),s={kind:"app",uniqueName:a},u=y=>t.push({subject:s,reason:y});oa(e,pte)&&u(Ki),In(e,[])&&u(yr);let l=Ks(e,"WebResourceId"),c=l&&l.trim()&&(r=(0,Qt.canonicalGuid)(l))!==null&&r!==void 0?r:null;if(l&&l.trim()&&!c)throw Ee("an app WebResourceId is not a GUID");let d=[],f=Mr(e,"AppModuleComponents");for(let y of f?qt(f):[]){let b=Js(y.getAttribute("type"),"an app component type"),E=y.getAttribute("schemaName");(y.nodeName!=="AppModuleComponent"||In(y,["type","schemaName","id"]))&&u(yr),b===Rt.COMPONENT.sitemap&&E?d.push(E):t.push({subject:nl(b??0,(o=(i=(0,Qt.canonicalGuid)(y.getAttribute("id")))!==null&&i!==void 0?i:E)!==null&&o!==void 0?o:null),reason:"an app component of a kind without a certified provider"})}let p=[],m=Mr(e,"AppModuleRoleMaps");for(let y of m?qt(m):[]){let b=(0,Qt.canonicalGuid)(y.getAttribute("id"));if(y.nodeName!=="Role"||!b)throw Ee("an AppModuleRoleMaps entry is not a Role with a GUID id");In(y,["id"])&&u(yr),p.push(b)}let h=[],g=Mr(e,"appsettings");for(let y of g?qt(g):[]){let b=y.getAttribute("settingdefinitionid.uniquename"),E=Ks(y,"value");if(y.nodeName!=="appsetting"||!b||E===null)throw Ee("an appsetting has no definition or value");let w=_=>t.push({subject:{kind:"appSetting",appUniqueName:a,settingUniqueName:b},reason:_});oa(y,mte)&&w(Ki),In(y,["settingdefinitionid.uniquename"])&&w(yr),h.push({definition:b,value:E,fields:vo(y,sn.APP_SETTING_FIELDS,n,w)})}if(new Set(h.map(y=>y.definition.toLowerCase())).size!==h.length)throw Ee("an app carries one setting definition twice");return{uniqueName:a,fields:vo(e,sn.APP_FIELDS,n,u),iconWebResourceId:c,sitemapNames:d.sort(Qt.byCodeUnit),roleIds:[...new Set(p)].sort(Qt.byCodeUnit),settings:h.sort((y,b)=>(0,Qt.byCodeUnit)(y.definition,b.definition))}}function Ite(e,t,n){let r=e.getAttribute("connectionreferencelogicalname");if(e.nodeName!=="connectionreference"||!r)throw Ee("a connectionreference has no logical name");let i=o=>t.push({subject:{kind:"connectionReference",logicalName:r},reason:o});return oa(e,hte)&&i(Ki),In(e,["connectionreferencelogicalname"])&&i(yr),{logicalName:r,connectorId:Hi(e,"connectorid"),fields:vo(e,sn.REFERENCE_FIELDS,n,i)}}function Tte(e,t,n,r,i,o){let a=up(e,"an environment variable definition"),s=a.getAttribute("schemaname");if(a.nodeName!=="environmentvariabledefinition"||!s)throw Ee("an environment variable definition has no schema name");if(s.toLowerCase()!==t.toLowerCase())throw Ee("an environment variable definition is filed under another name");let u=p=>i.push({subject:{kind:"environmentVariable",schemaName:s},reason:p});oa(a,gte)&&u(Ki),In(a,["schemaname"])&&u(yr);let l=Js(Ks(a,"type"),"a variable type");if(l===null||!Rt.VARIABLE_TYPES.has(l))throw Ee("a variable type is unknown, so its Secret classification is incomplete");let c=Ks(a,"isrequired"),d=`environmentvariabledefinitions/${t}/environmentvariablevalues.json`,f=n.get(d);if(f){r.add(d);let p;try{p=JSON.parse((0,VE.bytesToUtf8)(f.bytes).replace(/^\uFEFF/,""))}catch{throw Ee("a variable value file is not JSON")}if(typeof p!="object"||p===null||!("environmentvariablevalues"in p))throw Ee("a variable value file is not an environmentvariablevalues document")}return{schemaName:s,type:l,isRequired:c!==null&&c.trim()==="1",defaultValue:Ks(a,"defaultvalue"),hasCurrentValue:f!==void 0,fields:vo(a,sn.VARIABLE_FIELDS,o,u)}}function Ote(e,t,n,r){let i=up(e,"a search row"),o=(0,Qt.canonicalGuid)(i.getAttribute("dvtablesearchid"));if(i.nodeName!=="dvtablesearch"||!o)throw Ee("a search row has no GUID id");if((0,Qt.canonicalGuid)(t)!==o)throw Ee("a search row is filed under another id");let a=Mr(i,"m365appmoduleid"),s=a?Ks(a,"uniquename"):null;if(!a||!s||s.trim()==="")throw Ee("a search row names no app");let u={kind:"appSearch",packageId:o,appUniqueName:s},l=c=>n.push({subject:u,reason:c});return(oa(i,yte)||oa(a,new Set(["uniquename"])))&&l(Ki),(In(i,["dvtablesearchid"])||In(a,[]))&&l(yr),{id:o,appUniqueName:s,fields:vo(i,sn.SEARCH_FIELDS,r,l)}}});var il=C(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.resolveCustomApiComponentTypes=me.resolveAppPartComponentType=me.resolveConnectionReferenceComponentType=me.resolveGenPageComponentType=me.SolutionComponentType=void 0;var Dte=Ke(),rr=pe(),Ur=ae(),Pte=ft(),br=Y();me.SolutionComponentType={SavedQuery:26,Workflow:29,SavedQueryVisualization:59,SystemForm:60,AppModule:80,EnvironmentVariableDefinition:380,EnvironmentVariableValue:381,FieldSecurityProfile:70,DuplicateRule:4414,DuplicateRuleCondition:4416,DuplicateRuleClassic:44,DuplicateRuleConditionClassic:45};var Rte=[me.SolutionComponentType.SavedQuery,me.SolutionComponentType.Workflow,me.SolutionComponentType.SavedQueryVisualization,me.SolutionComponentType.SystemForm,me.SolutionComponentType.AppModule,me.SolutionComponentType.EnvironmentVariableDefinition,me.SolutionComponentType.EnvironmentVariableValue,me.SolutionComponentType.FieldSecurityProfile,me.SolutionComponentType.DuplicateRule,me.SolutionComponentType.DuplicateRuleCondition,me.SolutionComponentType.DuplicateRuleClassic,me.SolutionComponentType.DuplicateRuleConditionClassic],kte="uxagentproject",$te="connectionreference",GE=new WeakMap;async function Lg(e,t,n){var r,i;let o=(r=GE.get(e))===null||r===void 0?void 0:r.get(t);if(o!==void 0)return o;let a=`/EntityDefinitions(LogicalName='${t}')${(0,Ur.odataQuery)([["$select","ObjectTypeCode"]])}`,s=await e.get(a);if(s.status===404)return;(0,rr.ensureSuccess)(s,e.apiUrl(a));let u=(i=s.body)===null||i===void 0?void 0:i.ObjectTypeCode;if(typeof u!="number"||!Number.isInteger(u)||u<=0)throw new br.SdkError(n.errorCode,`${n.owner} solution component type \u2014 the ObjectTypeCode of '${t}' \u2014 could not be read: its metadata answered without a usable value (${JSON.stringify(u)}). Without it a solution's ${n.plural} cannot be told apart from other components. Retry.`);let l=GE.get(e);return l||(l=new Map,GE.set(e,l)),l.set(t,u),u}function q$(e){return Lg(e,kte,{errorCode:"GENPAGE_COMPONENT_TYPE_UNRESOLVED",owner:"A generative page's",plural:"generative pages"})}me.resolveGenPageComponentType=q$;function B$(e){return Lg(e,$te,{errorCode:"CONNECTION_REFERENCE_COMPONENT_TYPE_UNRESOLVED",owner:"A connection reference's",plural:"connection references"})}me.resolveConnectionReferenceComponentType=B$;function Lte(e,t){return Lg(e,t,{errorCode:"APP_PART_COMPONENT_TYPE_UNRESOLVED",owner:t==="appsetting"?"An app setting's":"An app search row's",plural:t==="appsetting"?"app settings":"app search rows"})}me.resolveAppPartComponentType=Lte;var Mte={api:"customapi",requestParameter:"customapirequestparameter",responseProperty:"customapiresponseproperty"};async function V$(e){let t={};for(let[n,r]of Object.entries(Mte)){let i=await Lg(e,r,{errorCode:"CUSTOM_API_COMPONENT_TYPE_UNRESOLVED",owner:"A custom API's",plural:"custom APIs"});i!==void 0&&(t[n]=i)}return t}me.resolveCustomApiComponentTypes=V$;var L$=1,M$=0;async function xte(e,t){let n=(0,Ur.normalizeGuid)(t,"solutionId"),r=await q$(e),i=await B$(e),o=await V$(e),a=new Map(Object.entries(o).map(([p,m])=>[m,p])),u=[L$,...Rte,...r===void 0?[]:[r],...i===void 0?[]:[i],...a.keys()].map(p=>`componenttype eq ${p}`).join(" or "),l=`/solutioncomponents${(0,Ur.odataQuery)([["$select","objectid,componenttype,rootcomponentbehavior"],["$filter",`_solutionid_value eq ${n} and (${u})`]])}`,c=await(0,Dte.collectPages)(e,l,"fetchSolutionComponents"),d=[];for(let p of c){if(typeof p.objectid!="string")continue;let m=Number(p.componenttype),h=m===me.SolutionComponentType.DuplicateRuleClassic?me.SolutionComponentType.DuplicateRule:m===me.SolutionComponentType.DuplicateRuleConditionClassic?me.SolutionComponentType.DuplicateRuleCondition:m;if(h===L$){let g=p.rootcomponentbehavior;(g===M$||g===String(M$))&&d.push({objectId:p.objectid,componentType:h,includesAllSubcomponents:!0});continue}d.push({objectId:p.objectid,componentType:h,...r!==void 0&&h===r?{genPage:!0}:{},...i!==void 0&&h===i?{connectionReference:!0}:{},...a.has(h)&&h!==r&&h!==i?{customApi:a.get(h)}:{}})}let f=p=>p.objectId.toLowerCase().replace(/^\{|\}$/g,"");return d.sort((p,m)=>p.componentType-m.componentType||(f(p)<f(m)?-1:f(p)>f(m)?1:0))}me.fetchSolutionComponents=xte;function Fte(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 Ute(e,t){var n,r,i,o,a,s,u,l,c,d;let f=String(t??"").trim();if(!f)throw new br.InvalidArgumentError("getSolution: a solution unique name or id is required.");let p=Fte(f)?`solutionid eq ${(0,Ur.normalizeGuid)(f,"solutionId")}`:`uniquename eq '${(0,Ur.odataLiteral)(f)}'`,m=`/solutions${(0,Ur.odataQuery)([["$select","solutionid,uniquename,friendlyname,version,ismanaged"],["$expand","publisherid($select=publisherid,uniquename,customizationprefix,customizationoptionvalueprefix)"],["$filter",p]])}`,y=((r=(n=(0,rr.ensureSuccess)(await e.get(m),e.apiUrl(m)).body)===null||n===void 0?void 0:n.value)!==null&&r!==void 0?r:[])[0];if(!y?.solutionid)throw new br.InvalidArgumentError(`No solution found for '${t}'.`);let b=y.publisherid;if(!b?.publisherid)throw new br.InvalidArgumentError(`Solution '${(i=y.uniquename)!==null&&i!==void 0?i:t}' returned no owning publisher, so its customization prefix cannot be determined; refusing to report an empty prefix that could be mistaken for "no prefix".`);if(!("customizationprefix"in b))throw new br.InvalidArgumentError(`Solution '${(o=y.uniquename)!==null&&o!==void 0?o:t}' returned a publisher without a customizationprefix property (partial expansion), so its prefix cannot be determined.`);return{solutionId:(0,Ur.normalizeGuid)(y.solutionid,"solutionId"),uniqueName:(a=y.uniquename)!==null&&a!==void 0?a:"",friendlyName:(s=y.friendlyname)!==null&&s!==void 0?s:"",version:(u=y.version)!==null&&u!==void 0?u:"",isManaged:!!y.ismanaged,publisherId:(0,Ur.normalizeGuid)(b.publisherid,"publisherId"),publisherUniqueName:(l=b.uniquename)!==null&&l!==void 0?l:"",publisherPrefix:(c=b.customizationprefix)!==null&&c!==void 0?c:"",publisherOptionValuePrefix:(d=b.customizationoptionvalueprefix)!==null&&d!==void 0?d:0}}me.getSolution=Ute;async function qte(e,t){var n;let r={uniquename:t.uniqueName,friendlyname:t.friendlyName,customizationprefix:t.prefix,customizationoptionvalueprefix:(n=t.optionValuePrefix)!==null&&n!==void 0?n:1e4};t.description&&(r.description=t.description);let i=(0,rr.ensureSuccess)(await(0,rr.resendDeadlockVictim)(()=>e.post("/publishers",{...r})),e.apiUrl("/publishers")),o=(0,rr.readCreatedId)(i,"publisherid");if(!o)throw new br.InvalidArgumentError(`Dataverse did not return an id for publisher '${t.uniqueName}'`);return{id:o,uniqueName:t.uniqueName}}me.createPublisher=qte;async function Bte(e,t){var n;let r=(0,Ur.normalizeGuid)(t.publisherId,"publisherId"),i={uniquename:t.uniqueName,friendlyname:t.friendlyName,version:(n=t.version)!==null&&n!==void 0?n:"1.0.0.0","[email protected]":`/publishers(${r})`};t.description&&(i.description=t.description);let o=(0,rr.ensureSuccess)(await e.post("/solutions",i),e.apiUrl("/solutions")),a=(0,rr.readCreatedId)(o,"solutionid");if(!a)throw new br.InvalidArgumentError(`Dataverse did not return an id for solution '${t.uniqueName}'`);return{id:a,uniqueName:t.uniqueName}}me.createSolution=Bte;async function Vte(e,t,n){let i=`/solutions(${(0,Ur.normalizeGuid)(t,"solutionId")})`;(0,rr.ensureSuccess)(await e.patch(i,{version:n}),e.apiUrl(i))}me.setSolutionVersion=Vte;async function Gte(e,t){var n;let i={ComponentId:(0,Ur.normalizeGuid)(t.componentId,"componentId"),ComponentType:t.componentType,SolutionUniqueName:t.solutionUniqueName,AddRequiredComponents:(n=t.addRequiredComponents)!==null&&n!==void 0?n:!1};t.doNotIncludeSubcomponents!==void 0&&(i.DoNotIncludeSubcomponents=t.doNotIncludeSubcomponents),(0,rr.ensureSuccess)(await e.post("/AddSolutionComponent",i),e.apiUrl("/AddSolutionComponent"))}me.addSolutionComponent=Gte;async function jte(e,t,n,r){let o={SolutionComponent:{"@odata.type":"Microsoft.Dynamics.CRM.solutioncomponent",solutioncomponentid:(0,Ur.normalizeGuid)(t,"componentId")},ComponentType:n,SolutionUniqueName:r};(0,rr.ensureSuccess)(await e.post("/RemoveSolutionComponent",o),e.apiUrl("/RemoveSolutionComponent"))}me.removeSolutionComponent=jte;async function Wte(e,t){var n,r;let i={SolutionName:t.solutionName,Managed:(n=t.managed)!==null&&n!==void 0?n:!1},a=(r=(0,rr.ensureSuccess)(await e.post("/ExportSolution",i),e.apiUrl("/ExportSolution")).body)===null||r===void 0?void 0:r.ExportSolutionFile;if(!a)throw new br.InvalidArgumentError(`ExportSolution returned no file for '${t.solutionName}'`);return{base64:a}}me.exportSolution=Wte;async function zte(e,t){let n=[["overwriteUnmanagedCustomizations","overwrote unmanaged customizations made over the solution's components"],["publishWorkflows","activated the solution's workflows"]];for(let[a,s]of n)if(typeof t?.[a]!="boolean")throw new br.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 r=t.deploymentSettings===void 0?void 0:rne(t.deploymentSettings),i={OverwriteUnmanagedCustomizations:t.overwriteUnmanagedCustomizations,PublishWorkflows:t.publishWorkflows,CustomizationFile:t.base64,ImportJobId:t.importJobId?(0,Ur.normalizeGuid)(t.importJobId,"importJobId"):(0,Pte.newId)()};if(!r)return(0,rr.ensureSuccess)(await e.post("/ImportSolution",i),e.apiUrl("/ImportSolution")),{};if(r.variables.length===0&&r.references.length===0)return(0,rr.ensureSuccess)(await e.post("/ImportSolution",i),e.apiUrl("/ImportSolution")),{appliedSettings:{environmentVariables:[],connectionReferences:[]}};let o=[];try{let a=await G$(e,t.base64,lp,o),{parameters:s,applied:u}=ine(a,r);return i.ComponentParameters=s,(0,rr.ensureSuccess)(await e.post("/ImportSolution",i),e.apiUrl("/ImportSolution")),{appliedSettings:u,...o.length>0?{warnings:o}:{}}}catch(a){throw(0,br.withCleanupWarnings)(a,o)}}me.importSolution=zte;var lp="importSolution",x$="getDeploymentSettingsTemplate";async function Hte(e,t){var n;let r=t?.base64;if(typeof r!="string"||r.length===0)throw new br.InvalidArgumentError(`${x$}: 'base64' must be the solution package \u2014 a non-empty base64 string, e.g. exportSolution's result (it was ${(n=JSON.stringify(r))!==null&&n!==void 0?n:String(r)})`);let i=[];try{let o=await G$(e,r,x$,i),a=$g(o.variables,u=>u.SchemaName).map(({SchemaName:u,DefaultValue:l,TypeId:c,IsRequired:d})=>({SchemaName:u,Value:"",...l!==void 0?{DefaultValue:l}:{},...c!==void 0?{TypeId:c}:{},...d!==void 0?{IsRequired:d}:{}})),s=$g(o.references,u=>u.LogicalName).map(({LogicalName:u,ConnectorId:l})=>({LogicalName:u,ConnectionId:"",...l!==void 0?{ConnectorId:l}:{}}));return{settings:{EnvironmentVariables:a,ConnectionReferences:s},...i.length>0?{warnings:i}:{}}}catch(o){throw(0,br.withCleanupWarnings)(o,i)}}me.getDeploymentSettingsTemplate=Hte;function $g(e,t){return[...e].sort((n,r)=>{let i=t(n).toLowerCase(),o=t(r).toLowerCase();return i<o?-1:i>o?1:0})}function rl(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function nr(e,t=120){var n;let r=(n=JSON.stringify(e))!==null&&n!==void 0?n:String(e);return r.length>t?`${r.slice(0,t)}\u2026`:r}async function G$(e,t,n,r){var i;let a=(i=(0,rr.ensureSuccess)(await e.post("/StageSolution",{CustomizationFile:t}),e.apiUrl("/StageSolution")).body)===null||i===void 0?void 0:i.StageSolutionResults;try{return Jte(a,n)}finally{await Kte(e,rl(a)?a.StageSolutionUploadId:void 0,r)}}async function Kte(e,t,n){let r;try{r=(0,Ur.normalizeGuid)(t,"StageSolutionUploadId")}catch{n.push(`StageSolution's reply named no usable staging upload id (${nr(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(${r})`;try{let o=await e.delete(i);o.status!==404&&(0,rr.ensureSuccess)(o,e.apiUrl(i))}catch(o){n.push(`The staged copy of the package (stagesolutionupload ${r}) could not be deleted: ${o instanceof Error?o.message:String(o)}. It stays until it is deleted (DELETE ${i}).`)}}function Fr(e,t){return new br.SdkError("SOLUTION_STAGING_UNREADABLE",`${e}: StageSolution's reply could not be read \u2014 ${t}.${e===lp?" Nothing was imported.":""}`)}function F$(e){return!Array.isArray(e)||e.length===0?"none":`${e.slice(0,5).map(n=>rl(n)&&typeof n.Message=="string"?n.Message:nr(n,200)).join("; ")}${e.length>5?` (+${e.length-5} more)`:""}`}function Jte(e,t){if(!rl(e))throw Fr(t,`it holds no StageSolutionResults (${nr(e,60)})`);let n=e.StageSolutionStatus;if(n==="Failed"||n===0)throw new br.SdkError("SOLUTION_STAGING_FAILED",`${t}: the package did not pass StageSolution in this environment (status ${nr(n)}). Missing dependencies: ${F$(e.MissingDependencies)}. Validation: ${F$(e.SolutionValidationResults)}.${t===lp?" Its components cannot be checked against deploymentSettings. Nothing was imported.":" Stage it in the environment it was exported from."}`);if(n!=="Passed"&&n!==1)throw Fr(t,`StageSolutionStatus is ${nr(n)}, neither "Passed" nor "Failed"`);let r=e.SolutionComponentsDetails;if(!Array.isArray(r))throw Fr(t,`SolutionComponentsDetails is not a list (${nr(r,60)})`);let i=[],o=[],a=new Set,s=new Set;return r.forEach((u,l)=>{let c=`SolutionComponentsDetails[${l}]`;if(!rl(u))throw Fr(t,`${c} is not an object`);if(typeof u.ComponentTypeName!="string")throw Fr(t,`${c}.ComponentTypeName is not a string`);let d=u.ComponentTypeName.toLowerCase();if(d!=="environmentvariabledefinition"&&d!=="connectionreference")return;let f=Yte(u.Attributes,`${c}.Attributes`,t),p=(m,h)=>{let g=f.get(m);if(g==null){if(h)throw Fr(t,`${c}.${m} is missing`);return}if(typeof g!="string"||h&&g.length===0)throw Fr(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 Fr(t,`${c}.schemaname '${m}' is listed twice`);a.add(m.toLowerCase());let h=p("defaultvalue",!1),g=Qte(f.get("type"),`${c}.type`,t),y=Xte(f.get("isrequired"),`${c}.isrequired`,t);i.push({SchemaName:m,...h!==void 0?{DefaultValue:h}:{},...g!==void 0?{TypeId:g}:{},...y!==void 0?{IsRequired:y}:{}})}else{let m=p("connectionreferencelogicalname",!0);if(s.has(m.toLowerCase()))throw Fr(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 Yte(e,t,n){if(!rl(e)||!Array.isArray(e.Keys)||!Array.isArray(e.Values))throw Fr(n,`${t} is not { Keys: [...], Values: [...] }`);let{Keys:r,Values:i}=e;if(r.length!==i.length)throw Fr(n,`${t} has ${r.length} keys but ${i.length} values`);let o=new Map;return r.forEach((a,s)=>{if(typeof a!="string")throw Fr(n,`${t}.Keys[${s}] is not a string`);if(o.has(a))throw Fr(n,`${t}.Keys lists '${a}' twice`);o.set(a,i[s])}),o}function Qte(e,t,n){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 Fr(n,`${t} is not a whole number (${nr(e,40)})`)}}function Xte(e,t,n){if(e!=null){if(typeof e=="boolean")return e;if(typeof e=="string"&&/^(true|false)$/i.test(e))return e.toLowerCase()==="true";throw Fr(n,`${t} is not true or false (${nr(e,40)})`)}}var Zte=new Set(["EnvironmentVariables","ConnectionReferences","Workflows","CanvasApps","CopilotAgents","$schema"]),ene=["Workflows","CanvasApps","CopilotAgents"],tne=new Set(["SchemaName","Value","DefaultValue","TypeId","IsRequired","Name"]),nne=new Set(["LogicalName","ConnectionId","ConnectorId"]);function xr(e,t){return new br.InvalidArgumentError(`${lp}: deploymentSettings is not a deployment-settings file this SDK applies \u2014 ${e} ${t}. Nothing was imported.`)}function rne(e){let t="deploymentSettings";if(!rl(e))throw xr(t,`must be an object \u2014 the settings file, parsed (it was ${nr(e,40)})`);for(let u of Object.keys(e))if(!Zte.has(u))throw xr(`${t}.${u}`,"is not part of the format (EnvironmentVariables, ConnectionReferences; Workflows, CanvasApps and CopilotAgents only empty; $schema)");for(let u of ene){let l=e[u];if(l!==void 0&&!(Array.isArray(l)&&l.length===0))throw xr(`${t}.${u}`,"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 xr(`${t}.$schema`,"must be a string");let n=u=>{let l=e[u];if(l===void 0)return[];if(!Array.isArray(l))throw xr(`${t}.${u}`,`must be a list (it was ${nr(l,40)})`);return l.map((c,d)=>{if(!rl(c))throw xr(`${t}.${u}[${d}]`,`must be an object (it was ${nr(c,40)})`);return c})},r=(u,l,c)=>{let d=u[l];if(typeof d!="string"||d.length===0)throw xr(c,`must be a non-empty string (it was ${nr(d,40)})`);if(d.trim()!==d)throw xr(c,`must not begin or end with whitespace (it was ${nr(d,60)})`);return d},i=(u,l,c)=>{if(u.has(l.toLowerCase()))throw xr(c,`names '${l}' a second time (names are case-insensitive)`);u.add(l.toLowerCase())},o={variables:[],references:[]},a=new Set;n("EnvironmentVariables").forEach((u,l)=>{let c=`${t}.EnvironmentVariables[${l}]`;for(let f of Object.keys(u))if(!tne.has(f))throw xr(`${c}.${f}`,"is not part of a variable (SchemaName, Value; DefaultValue, TypeId, IsRequired, Name)");let d=r(u,"SchemaName",`${c}.SchemaName`);if(i(a,d,`${c}.SchemaName`),typeof u.Value!="string")throw xr(`${c}.Value`,`must be a string \u2014 empty to override nothing (it was ${nr(u.Value,40)})`);u.Value.length>0&&o.variables.push({name:d,value:u.Value})});let s=new Set;return n("ConnectionReferences").forEach((u,l)=>{let c=`${t}.ConnectionReferences[${l}]`;for(let p of Object.keys(u))if(!nne.has(p))throw xr(`${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=r(u,"LogicalName",`${c}.LogicalName`);i(s,d,`${c}.LogicalName`);let f=u.ConnectionId;if(typeof f!="string")throw xr(`${c}.ConnectionId`,`must be a string \u2014 empty to bind nothing (it was ${nr(f,40)})`);if(f.trim()!==f)throw xr(`${c}.ConnectionId`,`must not begin or end with whitespace (it was ${nr(f,60)})`);if(u.ConnectorId!==void 0&&typeof u.ConnectorId!="string")throw xr(`${c}.ConnectorId`,`must be a string (it was ${nr(u.ConnectorId,40)})`);f.length>0&&o.references.push({name:d,connectionId:f,...u.ConnectorId?{connectorId:u.ConnectorId}:{}})}),o}function U$(e,t=20){return e.length===0?"none":`${e.slice(0,t).join(", ")}${e.length>t?` (+${e.length-t} more)`:""}`}function ine(e,t){var n;let r=new Map(e.variables.map(u=>[u.SchemaName.toLowerCase(),u])),i=new Map(e.references.map(u=>[u.LogicalName.toLowerCase(),u])),o=[],a=[],s={environmentVariables:[],connectionReferences:[]};for(let u of t.variables){let l=r.get(u.name.toLowerCase());if(!l){o.push(`EnvironmentVariables: '${u.name}' is not a variable of the package`);continue}a.push({"@odata.type":"Microsoft.Dynamics.CRM.environmentvariablevalue",schemaname:l.SchemaName,value:u.value}),s.environmentVariables.push(l.SchemaName)}for(let u of t.references){let l=i.get(u.name.toLowerCase());if(!l){o.push(`ConnectionReferences: '${u.name}' is not a connection reference of the package`);continue}if(u.connectorId!==void 0&&u.connectorId.toLowerCase()!==((n=l.ConnectorId)===null||n===void 0?void 0:n.toLowerCase())){o.push(`ConnectionReferences: '${u.name}' names connector '${u.connectorId}', but the package's reference is for ${l.ConnectorId?`'${l.ConnectorId}'`:"no connector"}`);continue}a.push({"@odata.type":"Microsoft.Dynamics.CRM.connectionreference",connectionreferencelogicalname:l.LogicalName,connectionid:u.connectionId,...l.ConnectorId!==void 0?{connectorid:l.ConnectorId}:{}}),s.connectionReferences.push(l.LogicalName)}if(o.length>0){let u=o.join("; "),l=U$($g(e.variables,d=>d.SchemaName).map(d=>d.SchemaName)),c=U$($g(e.references,d=>d.LogicalName).map(d=>d.LogicalName));throw new br.InvalidArgumentError(`${lp}: deploymentSettings does not match the package \u2014 ${u}. The package's variables: ${l}; its connection references: ${c}. Nothing was imported.`)}return{parameters:a,applied:s}}async function one(e,t){let r=`/solutions(${(0,Ur.normalizeGuid)(t,"solutionId")})`;(0,rr.ensureSuccess)(await e.delete(r),e.apiUrl(r))}me.deleteSolution=one});var zE=C(Mg=>{"use strict";Object.defineProperty(Mg,"__esModule",{value:!0});Mg.OrgReader=void 0;var ane=Ke(),sne=Y(),bt=ae(),une=ia(),tt=Ya(),lne=kg(),ve=Pg(),j$=il(),mt={state:"unreadable"},jE={state:"absent"},ir=e=>({state:"present",value:e});function Xa(e){if(e instanceof sne.PromotionError&&e.code==="PROMOTION_READ_BUDGET_EXCEEDED")throw e}var W$=["Basic","Local","Deep","Global"],WE=class{constructor(t,n,r){this.client=t,this.budget=n,this.codec=r,this.cache=new Map}once(t,n){let r=this.cache.get(t);return r||(r=n(),this.cache.set(t,r)),r}async get(t){return this.client.get(t)}async rows(t,n=Number.MAX_SAFE_INTEGER,r){let i=[],o=new Set,a=await this.get(t);for(let s=0;;s+=1){r?.(s);let u=a.body;if(a.status!==200||!Array.isArray(u?.value))return;i.push(...u?.value);let l=(0,ane.pageEnd)(u);if(l.kind==="end")return i;if(l.kind==="incomplete"||o.has(l.link))return;if(s+1>=n){r?.(s+1);return}o.add(l.link),a=await this.client.getAbsolute(l.link)}}async unique(t){try{let n=await this.rows(t);return!n||n.length>1?mt:n.length===0?jE:ir(n[0])}catch(n){return Xa(n),mt}}async byId(t,n,r){try{let i=await this.get(`/${t}(${n})${(0,bt.odataQuery)([["$select",r]])}`);if(i.status===404)return jE;let o=i.body;return i.status===200&&o&&typeof o=="object"?ir(o):mt}catch(i){return Xa(i),mt}}rootBusinessUnit(){return this.once("rootBu",async()=>{let t=await this.unique(`/businessunits${(0,bt.odataQuery)([["$select","businessunitid"],["$filter","_parentbusinessunitid_value eq null"]])}`);return t.state==="present"?(0,tt.canonicalGuid)(t.value.businessunitid):void 0})}solution(t){return this.once(`solution:${t.toLowerCase()}`,async()=>{let n=(0,ve.columnsOf)(ve.PUBLISHER_FIELDS,(0,ve.ADDRESS_FIELDS)(1),(0,ve.ADDRESS_FIELDS)(2)),r=await this.unique(`/solutions${(0,bt.odataQuery)([["$select",["solutionid","uniquename","version","ismanaged",...(0,ve.columnsOf)(ve.SOLUTION_FIELDS)].join(",")],["$expand",`publisherid($select=${["uniquename","customizationprefix",...n].join(",")})`],["$filter",`uniquename eq '${(0,bt.odataLiteral)(t)}'`]])}`);if(r.state!=="present")return r;let i=r.value,o=i.publisherid,a=(0,tt.canonicalGuid)(i.solutionid),s=(0,ve.projectRow)(i,ve.SOLUTION_FIELDS),u=o?(0,ve.projectRow)(o,ve.PUBLISHER_FIELDS,(0,ve.ADDRESS_FIELDS)(1),(0,ve.ADDRESS_FIELDS)(2)):void 0;return!a||typeof i.version!="string"||typeof i.ismanaged!="boolean"||typeof o?.uniquename!="string"||typeof i["@odata.etag"]!="string"||!s||!u?mt:ir({id:a,version:i.version,managed:i.ismanaged,publisherUniqueName:o.uniquename,publisherPrefix:typeof o.customizationprefix=="string"?o.customizationprefix:"",fields:s,publisherFields:u,etag:i["@odata.etag"]})})}async patches(t){try{let n=await this.rows(`/solutions${(0,bt.odataQuery)([["$select","solutionid"],["$filter",`_parentsolutionid_value eq ${t}`]])}`);return n?.map(r=>{var i;return(i=(0,tt.canonicalGuid)(r.solutionid))!==null&&i!==void 0?i:""}).sort(tt.byCodeUnit)}catch(n){Xa(n);return}}members(t){return this.once(`members:${t}`,async()=>{try{let n=await this.rows(`/solutioncomponents${(0,bt.odataQuery)([["$select","componenttype,objectid"],["$filter",`_solutionid_value eq ${t}`]])}`);if(!n)return;let r=[];for(let i of n){let o=(0,tt.canonicalGuid)(i.objectid);if(!o||typeof i.componenttype!="number")return;r.push({type:i.componenttype,id:o})}return r}catch(n){Xa(n);return}})}componentType(t){return this.once(`componenttype:${t}`,async()=>{try{let n=t==="connectionreference"?await(0,j$.resolveConnectionReferenceComponentType)(this.client):await(0,j$.resolveAppPartComponentType)(this.client,t);return n===void 0?jE:ir(n)}catch(n){return Xa(n),mt}})}async fieldById(t,n,r){let i=await this.byId(t,n,r);if(i.state!=="present")return i;let o=i.value[r];return typeof o=="string"?ir(o):mt}app(t,n){return this.once(`app:${n}:${t}`,async()=>{var r;let i=n?"/appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()":"/appmodules",o=await this.unique(`${i}${(0,bt.odataQuery)([["$select",["appmoduleid","appmoduleidunique","uniquename","webresourceid",...(0,ve.columnsOf)(ve.APP_FIELDS)].join(",")],["$filter",`uniquename eq '${(0,bt.odataLiteral)(t)}'`]])}`);if(o.state!=="present")return o;let a=o.value,s=(0,tt.canonicalGuid)(a.appmoduleid),u=(0,tt.canonicalGuid)(a.appmoduleidunique),l=(0,ve.projectRow)(a,ve.APP_FIELDS);if(!s||!u||!l||typeof a["@odata.etag"]!="string")return mt;try{let c=await this.rows(`/appmodules(${s})/appmoduleroles_association${(0,bt.odataQuery)([["$select","roleid"]])}`),d=await this.rows(`/appmodulecomponents${(0,bt.odataQuery)([["$select","componenttype,objectid"],["$filter",`_appmoduleidunique_value eq ${u}`]])}`),f=await this.appSettings(s,n);if(!c||!d||!f)return mt;let p=c.map(h=>(0,tt.canonicalGuid)(h.roleid)),m=d.map(h=>{let g=(0,tt.canonicalGuid)(h.objectid);return typeof h.componenttype=="number"&&g?`${h.componenttype}:${g}`:void 0});return p.some(h=>!h)||m.some(h=>!h)?mt:ir({id:s,unique:u,fields:l,webResourceId:(r=(0,tt.canonicalGuid)(a.webresourceid))!==null&&r!==void 0?r:null,etag:a["@odata.etag"],roles:p.sort(tt.byCodeUnit),components:m.sort(tt.byCodeUnit),settings:f})}catch(c){return Xa(c),mt}})}async appSettings(t,n){let r=n?"/appsettings/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()":"/appsettings",i=await this.rows(`${r}${(0,bt.odataQuery)([["$select",["appsettingid","value","_settingdefinitionid_value",...(0,ve.columnsOf)(ve.APP_SETTING_FIELDS)].join(",")],["$filter",`_parentappmoduleid_value eq ${t}`]])}`);if(!i)return;let o=[...new Set(i.map(u=>(0,tt.canonicalGuid)(u._settingdefinitionid_value)))];if(o.some(u=>!u))return;let a=new Map;if(o.length>0){let u=await this.rows(`/settingdefinitions${(0,bt.odataQuery)([["$select","settingdefinitionid,uniquename"],["$filter",o.map(l=>`settingdefinitionid eq ${l}`).join(" or ")]])}`);for(let l of u??[]){let c=(0,tt.canonicalGuid)(l.settingdefinitionid);c&&typeof l.uniquename=="string"&&a.set(c,l.uniquename)}}let s=[];for(let u of i){let l=a.get((0,tt.canonicalGuid)(u._settingdefinitionid_value)),c=(0,tt.canonicalGuid)(u.appsettingid),d=(0,ve.projectRow)(u,ve.APP_SETTING_FIELDS);if(!l||!c||!d||typeof u["@odata.etag"]!="string")return;s.push({definition:l,value:typeof u.value=="string"?u.value:"",fields:d,etag:u["@odata.etag"],id:c})}return s.sort((u,l)=>(0,tt.byCodeUnit)(u.definition,l.definition))}settingDefinition(t){return this.once(`settingdefinition:${t}`,async()=>{let n=await this.unique(`/settingdefinitions${(0,bt.odataQuery)([["$select","settingdefinitionid,uniquename"],["$filter",`uniquename eq '${(0,bt.odataLiteral)(t)}'`]])}`);if(n.state!=="present")return n;let r=(0,tt.canonicalGuid)(n.value.settingdefinitionid);return r?ir(r):mt})}sitemap(t,n){return this.once(`sitemap:${n}:${t}`,async()=>{let r=n?"/sitemaps/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()":"/sitemaps",i=await this.unique(`${r}${(0,bt.odataQuery)([["$select",["sitemapid","sitemapnameunique","sitemapxml",...(0,ve.columnsOf)(ve.SITEMAP_FIELDS)].join(",")],["$filter",`sitemapnameunique eq '${(0,bt.odataLiteral)(t)}'`]])}`);if(i.state!=="present")return i;let o=(0,tt.canonicalGuid)(i.value.sitemapid),a=i.value.sitemapxml,s=typeof a=="string"?(0,lne.canonicalSitemapText)(a):void 0,u=(0,ve.projectRow)(i.value,ve.SITEMAP_FIELDS);return!o||!s||!u||typeof i.value["@odata.etag"]!="string"?mt:ir({id:o,canonical:s,fields:u,etag:i.value["@odata.etag"]})})}webResource(t){return this.once(`webresource:${t}`,async()=>{let n=await this.unique(`/webresourceset${(0,bt.odataQuery)([["$select",["webresourceid","name","webresourcetype","content",...(0,ve.columnsOf)(ve.WEB_RESOURCE_FIELDS)].join(",")],["$filter",`name eq '${(0,bt.odataLiteral)(t)}'`]])}`);if(n.state!=="present")return n;let r=n.value,i=(0,tt.canonicalGuid)(r.webresourceid),o=(0,ve.projectRow)(r,ve.WEB_RESOURCE_FIELDS);if(!i||!o||typeof r.webresourcetype!="number"||typeof r["@odata.etag"]!="string")return mt;let a=typeof r.content=="string"?r.content:"";return ir({id:i,type:r.webresourcetype,sha256:await(0,tt.sha256Of)(this.codec,(0,une.base64ToBytes)(a)),fields:o,etag:r["@odata.etag"]})})}variable(t){return this.once(`variable:${t}`,async()=>{let n=await this.unique(`/environmentvariabledefinitions${(0,bt.odataQuery)([["$select",["environmentvariabledefinitionid","schemaname","type","isrequired","defaultvalue",...(0,ve.columnsOf)(ve.VARIABLE_FIELDS)].join(",")],["$filter",`schemaname eq '${(0,bt.odataLiteral)(t)}'`]])}`);if(n.state!=="present")return n;let r=n.value,i=(0,tt.canonicalGuid)(r.environmentvariabledefinitionid),o=(0,ve.projectRow)(r,ve.VARIABLE_FIELDS);if(!i||!o||typeof r.type!="number"||typeof r["@odata.etag"]!="string")return mt;try{let a=await this.rows(`/environmentvariablevalues${(0,bt.odataQuery)([["$select","environmentvariablevalueid,value"],["$filter",`_environmentvariabledefinitionid_value eq ${i}`]])}`);if(!a)return mt;let s=[];for(let u of a){let l=(0,tt.canonicalGuid)(u.environmentvariablevalueid);if(!l||typeof u["@odata.etag"]!="string")return mt;s.push({id:l,valueDigest:await(0,tt.digestOf)(this.codec,typeof u.value=="string"?u.value:null),etag:u["@odata.etag"]})}return ir({id:i,type:r.type,isRequired:r.isrequired===!0,defaultValue:typeof r.defaultvalue=="string"?r.defaultvalue:null,fields:o,etag:r["@odata.etag"],values:s.sort((u,l)=>(0,tt.byCodeUnit)(u.id,l.id))})}catch(a){return Xa(a),mt}})}reference(t){return this.once(`reference:${t}`,async()=>{let n=await this.unique(`/connectionreferences${(0,bt.odataQuery)([["$select",["connectionreferenceid","connectionreferencelogicalname","connectorid","connectionid",...(0,ve.columnsOf)(ve.REFERENCE_FIELDS)].join(",")],["$filter",`connectionreferencelogicalname eq '${(0,bt.odataLiteral)(t)}'`]])}`);if(n.state!=="present")return n;let r=n.value,i=(0,tt.canonicalGuid)(r.connectionreferenceid),o=(0,ve.projectRow)(r,ve.REFERENCE_FIELDS);return!i||!o||typeof r["@odata.etag"]!="string"?mt:ir({id:i,connectorId:typeof r.connectorid=="string"?r.connectorid:null,connectionId:typeof r.connectionid=="string"?r.connectionid:null,fields:o,etag:r["@odata.etag"]})})}role(t){return this.once(`role:${t}`,async()=>{var n,r;let i=await this.byId("roles",t,["roleid","name","_businessunitid_value","_roletemplateid_value",...(0,ve.columnsOf)(ve.ROLE_FIELDS)].join(","));if(i.state!=="present")return i;let o=i.value,a=(0,ve.projectRow)(o,ve.ROLE_FIELDS);return!a||typeof o["@odata.etag"]!="string"?mt:ir({id:t,name:typeof o.name=="string"?o.name:null,businessUnitId:(n=(0,tt.canonicalGuid)(o._businessunitid_value))!==null&&n!==void 0?n:null,templateId:(r=(0,tt.canonicalGuid)(o._roletemplateid_value))!==null&&r!==void 0?r:null,fields:a,etag:o["@odata.etag"]})})}rolePrivileges(t){return this.once(`privileges:${t}`,async()=>{var n;try{let r=await this.get(`/RetrieveRolePrivilegesRole(RoleId=${t})`),i=(n=r.body)===null||n===void 0?void 0:n.RolePrivileges;if(r.status!==200||!Array.isArray(i))return;let o=[];for(let a of i){let s=typeof a?.Depth=="number"?W$[a.Depth]:typeof a?.Depth=="string"?a.Depth:void 0;if(typeof a?.PrivilegeName!="string"||!s||!W$.includes(s))return;o.push(`${a.PrivilegeName}:${s}`)}return[...new Set(o)].sort(tt.byCodeUnit)}catch(r){Xa(r);return}})}templateRole(t){return this.once(`template:${t}`,async()=>{let n=await this.rootBusinessUnit();if(!n)return mt;let r=await this.unique(`/roles${(0,bt.odataQuery)([["$select","roleid"],["$filter",`_roletemplateid_value eq ${t} and _businessunitid_value eq ${n}`]])}`);if(r.state!=="present")return r;let i=(0,tt.canonicalGuid)(r.value.roleid);return i?ir(i):mt})}webResourceName(t){return this.once(`webresourcename:${t}`,()=>this.fieldById("webresourceset",t,"name"))}search(t){return this.once(`search:${t}`,async()=>{let n=await this.byId("dvtablesearchs",t,["dvtablesearchid",...(0,ve.columnsOf)(ve.SEARCH_FIELDS)].join(","));if(n.state!=="present")return n;let r=(0,ve.projectRow)(n.value,ve.SEARCH_FIELDS),i=n.value["@odata.etag"];return r&&typeof i=="string"?ir({id:t,fields:r,etag:i}):mt})}tableExists(t){return this.once(`table:${t}`,async()=>{let n=await this.byId("EntityDefinitions",`LogicalName='${(0,bt.odataLiteral)(t)}'`,"LogicalName");return n.state!=="present"?n:typeof n.value.LogicalName=="string"?ir(!0):mt})}async topLayer(t,n){this.budget.layerLookups+=1;try{let r=0,i=await this.rows(`/msdyn_componentlayers${(0,bt.odataQuery)([["$select","msdyn_order,msdyn_solutionname"],["$filter",`(msdyn_componentid eq '${n}' and msdyn_solutioncomponentname eq '${(0,bt.odataLiteral)(t)}')`]])}`,this.budget.limits.maxLayerPagesPerComponent,()=>{this.budget.spendLayerPage(r),r+=1});if(!i||i.length===0)return mt;let o=i.map(a=>{var s;return{order:Number(a.msdyn_order),name:String((s=a.msdyn_solutionname)!==null&&s!==void 0?s:"")}}).sort((a,s)=>s.order-a.order);return o.some(a=>!Number.isFinite(a.order))?mt:ir({top:o[0].name,digest:await(0,tt.digestOf)(this.codec,o.map(a=>[a.order,a.name]))})}catch(r){return Xa(r),mt}}async variableExists(t){let n=await this.variable(t);return n.state==="present"?ir(!0):n}};Mg.OrgReader=WE});var cp=C(kt=>{"use strict";Object.defineProperty(kt,"__esModule",{value:!0});kt.environmentVariablePushIssues=kt.environmentVariableShapeIssues=kt.environmentVariableMutationIssues=kt.requiredStringOrNull=kt.rowBagIssues=kt.valueTypeProblem=kt.isGuidText=kt.ENVIRONMENT_VARIABLE_BAG_COLUMNS=kt.ENVIRONMENT_VARIABLE_TYPES=void 0;kt.ENVIRONMENT_VARIABLE_TYPES=["string","number","boolean","json","dataSource","secret"];kt.ENVIRONMENT_VARIABLE_BAG_COLUMNS=["hint","learnmoreurl","inputcontrolconfig"];function cne(e){return/^-?\d+$/.test(e)||/^-?\d+\.\d+$/.test(e)||/^-?\.\d+$/.test(e)}var dne=/^\{?[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 yn(e,t,n){return{pointer:e,rule:t,message:n}}function KE(e){return typeof e=="string"&&dne.test(e)&&e.startsWith("{")===e.endsWith("}")}kt.isGuidText=KE;function H$(e,t){switch(e){case"number":return cne(t)?void 0:"is not a decimal number: write digits with an optional leading '-' and an optional '.' fraction, e.g. 42 or -1.5 (no exponent, no hex)";case"boolean":return t==="yes"||t==="no"?void 0:"is not a Boolean value: write 'yes' or 'no' (lower case, the platform's own form)";case"json":try{JSON.parse(t);return}catch{return"is not JSON text: it does not parse"}default:return}}kt.valueTypeProblem=H$;function Fg(e,t,n,r){if(typeof t!="string")return[];if(t==="")return[yn(n,"empty-string",`${r} is the empty string, which the platform stores as no value: use null for none`+(n==="/defaultValue"?"":", or set /currentValue to null to remove the value"))];if(!kt.ENVIRONMENT_VARIABLE_TYPES.includes(e))return[];let i=H$(e,t);return i===void 0?[]:[yn(n,"value-type",`${r} ${i} (type '${String(e)}')`)]}function K$(e,t){if(e===void 0)return[];let n=e?.a;if(!Array.isArray(n))return[yn("/bag","bag-column","bag must be { a: [[column, value], \u2026] }")];let r=[],i=new Set;return n.forEach((o,a)=>{let s=Array.isArray(o)&&o.length===2?o[0]:void 0;if(typeof s!="string"||!t.includes(s)||i.has(s)){r.push(yn(`/bag/a/${a}`,"bag-column",`a bag entry must be a [column, value] pair naming one of ${t.join(", ")}, each at most once (a typed field is edited through its own property)`));return}i.add(s)}),r}kt.rowBagIssues=K$;function xg(e,t){return e==null||typeof e=="string"?[]:[yn(t,"type","must be a string or null")]}function HE(e,t,n="a string"){return e===void 0?[yn(t,"required",`must be present: ${n}, or null for none (to clear it, set it to null \u2014 removing it is refused)`)]:e===null||typeof e=="string"?[]:[yn(t,"type",`must be ${n} or null`)]}kt.requiredStringOrNull=HE;function z$(e,t){return e==null||KE(e)?[]:[yn(t,"guid","must be a GUID or null")]}function J$(e){let t=e,n=[];KE(t.id)||n.push(yn("/id","guid","must be a GUID")),(typeof t.schemaName!="string"||t.schemaName.trim()==="")&&n.push(yn("/schemaName","required","must be a non-empty string")),typeof t.name!="string"&&n.push(yn("/name","type","must be a string")),n.push(...HE(t.description,"/description")),kt.ENVIRONMENT_VARIABLE_TYPES.includes(t.type)||n.push(yn("/type","type",`must be one of ${kt.ENVIRONMENT_VARIABLE_TYPES.join(", ")}`)),n.push(...HE(t.defaultValue,"/defaultValue"));let r=t.currentValue;if(r!==null&&(typeof r!="object"||Array.isArray(r)))n.push(yn("/currentValue","type","must be { value } or null"));else if(r!==null){let i=r;n.push(...xg(i.value,"/currentValue/value")),i.value===void 0&&n.push(yn("/currentValue/value","required","must be present (a string)")),i.id!==void 0&&n.push(...z$(i.id,"/currentValue/id"))}return typeof t.isRequired!="boolean"&&n.push(yn("/isRequired","type","must be true or false")),n.push(...xg(t.valueSchema,"/valueSchema")),n.push(...xg(t.connectorId,"/connectorId")),n.push(...xg(t.parameterKey,"/parameterKey")),n.push(...z$(t.parentId,"/parentId")),n.push(...K$(t.bag,kt.ENVIRONMENT_VARIABLE_BAG_COLUMNS)),n}function fne(e,t){var n;let r=J$(e);return t==="/defaultValue"?r.push(...Fg(e.type,e.defaultValue,"/defaultValue","defaultValue")):(t==="/currentValue"||t==="/currentValue/value")&&r.push(...Fg(e.type,(n=e.currentValue)===null||n===void 0?void 0:n.value,"/currentValue/value","currentValue.value")),r}kt.environmentVariableMutationIssues=fne;function pne(e){return J$(e)}kt.environmentVariableShapeIssues=pne;function mne(e,t){var n,r,i;let o=[];if(t){e.type!==t.type&&o.push(yn("/type","immutable-after-create","type is fixed once the variable exists (the platform ignores a change)")),e.schemaName!==t.schemaName&&o.push(yn("/schemaName","immutable-after-create","schemaName is fixed once the variable exists (the platform ignores a change)"));let u=(n=t.currentValue)===null||n===void 0?void 0:n.id,l=(r=e.currentValue)===null||r===void 0?void 0:r.id;u!==void 0&&l!==void 0&&l.toLowerCase()!==u.toLowerCase()&&o.push(yn("/currentValue/id","immutable-after-create","the value row's id is fixed: omit it (the SDK keeps the existing row's), or set /currentValue to null to delete the row"))}(!t||e.defaultValue!==t.defaultValue)&&o.push(...Fg(e.type,e.defaultValue,"/defaultValue","defaultValue"));let a=e.currentValue,s=(i=t?.currentValue)!==null&&i!==void 0?i:null;return a&&(a.value===null?(s===null||s.value!==null)&&o.push(yn("/currentValue/value","value-required","a value row needs a value: to remove the value, set /currentValue to null")):(s===null||a.value!==s.value)&&o.push(...Fg(e.type,a.value,"/currentValue/value","currentValue.value"))),e.parentId!=null&&e.type!=="dataSource"&&o.push(yn("/parentId","parent-not-data-source","parentId is accepted only on a 'dataSource' variable (and must name another 'dataSource' variable)")),o}kt.environmentVariablePushIssues=mne});var QE=C(ot=>{"use strict";Object.defineProperty(ot,"__esModule",{value:!0});ot.ROW_SUMMARY_TEMPLATE_NOT_FOUND_CODE=ot.ROW_SUMMARY_REMOVAL_UNCONFIRMED_CODE=ot.ROW_SUMMARY_MODEL_NOT_DELETED_CODE=ot.removeRowSummary=ot.configureRowSummary=ot.buildGptDynamicPrompt=ot.setAppAiFeatures=ot.getAiReadiness=ot.saveSettingValue=ot.retrieveSetting=ot.AI_GATE=void 0;var fi=Ke(),Ji=pe(),$t=ae(),Y$=ft(),st=Y(),dp="answered no row but says more rows exist, so it proves no absence";ot.AI_GATE={formFill:"FormFillBarUXEnabled",formFillSuggestions:"FormPredictEnabled",formFillSmartPaste:"FormPredictSmartPasteEnabled",formFillFiles:"FormFillFileUploadEnabled",nlSearch:"EnableNLGridSearch",nlChart:"NLChartVisualizationSetting",summaries:"EnableFormInsights",m365:"m365copilotmodelappenabled"};var nL={formFill:"FormFillBarUXEnabled",formFillSuggestions:"FormPredictEnabled",formFillSmartPaste:"FormPredictSmartPasteEnabledOnByDefault",formFillFiles:"FormFillFileUploadEnabled",nlSearch:"NLGridSearchSetting",nlChart:"NLChartDataVisualizationSetting",m365:"m365copilotmodelappenabled"},hne=new Set(Object.entries(ot.AI_GATE).filter(([e,t])=>nL[e]===t).map(([e])=>e)),gne={formFill:{enabled:"2",disabled:"1"},formFillSuggestions:{enabled:"2",disabled:"1"},formFillSmartPaste:{enabled:"2",disabled:"1"},formFillFiles:{enabled:"2",disabled:"1"}};function JE(e){return gne[e]}var Ug=1e6;function yne(e,t){let n=JE(t),r=()=>{throw new st.InvalidArgumentError(`setAppAiFeatures: '${t}' must be a boolean or an integer between 0 and ${Ug} (e.g. 0, 1, 2); got '${String(e)}'.`)},i=o=>n?o?n.enabled:n.disabled:o?"1":"0";if(typeof e=="boolean")return i(e);if(typeof e=="number")return!Number.isSafeInteger(e)||e<0||e>Ug?r():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(Ug).length||Number(s)>Ug?r():s}}return r()}function bne(e,t){let n=JE(t);return n?e===n.enabled:e!=="0"}async function vne(e,t){var n,r;let i=`/appmodules${(0,$t.odataQuery)([["$select","appmoduleid"],["$filter",`uniquename eq '${(0,$t.odataLiteral)(t)}'`]])}`,o=await e.get(i);if(o.status<200||o.status>=300)return;let a=(n=o.body)===null||n===void 0?void 0:n.value;if(!Array.isArray(a))throw new st.ConnectionError(e.apiUrl(i),o.status,`the app lookup for '${t}' returned a malformed answer \u2014 expected an OData 'value' array but got ${(0,fi.describeMalformedValue)(a)}`);if(!(0,fi.boundedPageComplete)(o.body,a.length))throw new st.ConnectionError(e.apiUrl(i),o.status,`the app lookup for '${t}' ${dp}`);return(r=a[0])===null||r===void 0?void 0:r.appmoduleid}async function wne(e,t){var n,r;let i=`/appmodules${(0,$t.odataQuery)([["$select","appmoduleid"],["$filter",`uniquename eq '${(0,$t.odataLiteral)(t)}'`]])}`,o;try{o=await e.get(i)}catch(u){throw new st.InvalidArgumentError(`setAppAiFeatures: cannot confirm that the supplied appModuleId belongs to app '${t}' \u2014 the lookup failed (${u.message}). Retry, or omit appModuleId to verify by name.`)}if(o.status<200||o.status>=300)throw new st.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=(n=o.body)===null||n===void 0?void 0:n.value;if(!Array.isArray(a))throw new st.InvalidArgumentError(`setAppAiFeatures: cannot confirm that the supplied appModuleId belongs to app '${t}' \u2014 the lookup returned a malformed body.`);if(!(0,fi.boundedPageComplete)(o.body,a.length))throw new st.InvalidArgumentError(`setAppAiFeatures: cannot confirm that the supplied appModuleId belongs to app '${t}' \u2014 the lookup ${dp}.`);if(a.length===0)return;let s=(r=a[0])===null||r===void 0?void 0:r.appmoduleid;if(!s)throw new st.InvalidArgumentError(`setAppAiFeatures: cannot confirm that the supplied appModuleId belongs to app '${t}' \u2014 the lookup returned a row with no appmoduleid.`);return s}var Q$=new WeakMap;async function Ene(e,t){var n,r;let i=Q$.get(e);if(i||(i=new Map,Q$.set(e,i)),i.has(t))return i.get(t);let o=`/settingdefinitions${(0,$t.odataQuery)([["$select","settingdefinitionid"],["$filter",`uniquename eq '${(0,$t.odataLiteral)(t)}'`]])}`,a=await e.get(o);if(a.status<200||a.status>=300)return;let s=(n=a.body)===null||n===void 0?void 0:n.value;if(!Array.isArray(s))throw new st.ConnectionError(e.apiUrl(o),a.status,`the setting definition lookup returned a malformed answer \u2014 expected an OData 'value' array but got ${(0,fi.describeMalformedValue)(s)}`);if(!(0,fi.boundedPageComplete)(a.body,s.length))throw new st.ConnectionError(e.apiUrl(o),a.status,`the setting definition lookup ${dp}`);let u=(r=s[0])===null||r===void 0?void 0:r.settingdefinitionid;return u&&i.set(t,u),u}async function Ane(e,t,n){var r;let i=await Ene(e,n);if(!t||!i)return;let o=`/appsettings/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()${(0,$t.odataQuery)([["$select","value,componentstate"],["$filter",`_parentappmoduleid_value eq ${t} and _settingdefinitionid_value eq ${i}`]])}`,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 st.ConnectionError(e.apiUrl(o),a.status,`the app-scope override read returned a malformed answer \u2014 expected an OData 'value' array but got ${(0,fi.describeMalformedValue)(s)}`);let u=s,l=u.find(d=>d?.componentstate===1);if(!l&&(0,fi.pageEnd)(a.body).kind!=="end")throw new st.ConnectionError(e.apiUrl(o),a.status,u.length===0?`the app-scope override read ${dp}`:"the app-scope override read answered no authored row but says more rows exist, so it proves no value");if(u.length===0)return{exists:!1};let c=l??u[0];return{exists:!0,value:c.value,pendingPublish:c.componentstate===1}}var Cne=4,Sne=500,X$=20,Z$=3e4;function Nne(e){if(e===void 0)return Cne;if(!Number.isFinite(e))throw new st.InvalidArgumentError(`setAppAiFeatures: verifyAttempts must be a finite integer between 1 and ${X$}; got ${e}.`);return Math.min(X$,Math.max(1,Math.floor(e)))}function _ne(e){if(e===void 0)return Sne;if(!Number.isFinite(e))throw new st.InvalidArgumentError(`setAppAiFeatures: verifyDelayMs must be a finite number between 0 and ${Z$}; got ${e}.`);return Math.min(Z$,Math.max(0,Math.floor(e)))}async function Ine(e,t,n,r,i,o,a){let s,u,l,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 Ane(e,p,r),f===void 0&&(l="the app-scope override row could not be read (insufficient access or unresolvable ids)")):l=`the app '${n}' 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,l=p.message}c=f!==void 0,u=f?.exists;try{s=(await qg(e,r,{appUniqueName:n})).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:u}:{result:"unverifiable",effectiveValue:s,appOverrideExists:void 0,reason:l}}function rL(e,t,n){if(t===2)return String(e).toLowerCase()==="true";let r=n?JE(n):void 0;return r?e===r.enabled:e!=null&&e!=="0"&&e!==""}async function qg(e,t,n={}){var r;let i=[`SettingName='${(0,$t.odataPathLiteral)(t)}'`];n.appUniqueName&&i.push(`AppUniqueName='${(0,$t.odataPathLiteral)(n.appUniqueName)}'`);let o=`/RetrieveSetting(${i.join(",")})`,a=(0,Ji.ensureSuccess)(await e.get(o),e.apiUrl(o)),s=(r=a.body)===null||r===void 0?void 0:r.SettingDetail;if(s===null||typeof s!="object"||Array.isArray(s)||!("Value"in s))throw new st.ConnectionError(e.apiUrl(o),a.status,`RetrieveSetting for '${t}' returned a malformed answer \u2014 expected a SettingDetail with a Value`);let{Value:u,DataType:l}=s;return{value:u,dataType:l}}ot.retrieveSetting=qg;async function iL(e,t,n,r={}){let i={SettingName:t,Value:n};r.appUniqueName&&(i.AppUniqueName=r.appUniqueName),r.solutionUniqueName&&(i.SolutionUniqueName=r.solutionUniqueName),(0,Ji.ensureSuccess)(await e.post("/SaveSettingValue",i),e.apiUrl("/SaveSettingValue"))}ot.saveSettingValue=iL;async function Tne(e,t={}){let n={};for(let[r,i]of Object.entries(ot.AI_GATE)){let{value:o,dataType:a}=await qg(e,i,t);n[r]={enabled:rL(o,a,r),setting:i,value:o}}return n}ot.getAiReadiness=Tne;async function One(e,t,n,r={}){var i;if(!t||!t.trim())throw new st.InvalidArgumentError("setAppAiFeatures: a non-empty appUniqueName is required (an empty value would write the setting at organization scope, affecting every app).");let o=Nne(r.verifyAttempts),a=_ne(r.verifyDelayMs),s=[];for(let[m,h]of Object.entries(n)){if(h===void 0)continue;let g=nL[m];g&&s.push({feature:m,setting:g,requestedValue:yne(h,m)})}let u=[],l=r.appModuleId?(0,$t.normalizeGuid)(r.appModuleId,"appModuleId"):void 0;if(l){let m=await wne(e,t);if(m&&(0,$t.normalizeGuid)(m,"appModuleId")!==l)throw new st.InvalidArgumentError(`setAppAiFeatures: appModuleId '${l}' does not belong to app '${t}' (which resolves to '${m}'). 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()=>l||(c||(c=await vne(e,t)),c),f=new Map,p=async m=>{if(hne.has(m))return;let h=ot.AI_GATE[m];if(h){if(!f.has(h))try{let{value:g,dataType:y}=await qg(e,h);f.set(h,{enabled:rL(g,y,m),setting:h,value:g})}catch{f.set(h,void 0)}return f.get(h)}};for(let{feature:m,setting:h,requestedValue:g}of s)try{await iL(e,h,g,{appUniqueName:t,solutionUniqueName:r.solutionUniqueName});let y=await Ine(e,d,t,h,g,o,a),b={feature:m,setting:h,requestedValue:g,effectiveValue:y.effectiveValue,appOverrideExists:y.appOverrideExists};if(y.result==="proven")u.push({...b,status:"applied",...y.pendingPublish?{pendingPublish:!0}:{}});else if(y.result==="absent"){let E=bne(g,m)?await p(m):void 0;E&&!E.enabled?u.push({...b,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 '${E.setting}' reads '${E.value}', so an environment admin must enable it before this app can turn the feature on`}):u.push({...b,status:"notPersisted",reason:`the write reported success but no app-scope override holding '${g}' was observed for '${h}' after ${o} attempt(s) \u2014 ${y.effectiveValue===void 0?"the value in effect for this app could not be read":`it reads '${y.effectiveValue}' for this app`} (Dataverse can accept an app-scope write without storing it)`})}else u.push({...b,status:"unverified",reason:`the write was issued but could not be confirmed: ${(i=y.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(y){u.push({feature:m,setting:h,requestedValue:g,status:"failed",reason:y.message})}return{applied:u.filter(m=>m.status==="applied").map(m=>m.feature),skipped:u.filter(m=>m.status==="skipped").map(m=>m.feature),notPersisted:u.filter(m=>m.status==="notPersisted").map(m=>m.feature),unverified:u.filter(m=>m.status==="unverified").map(m=>m.feature),failed:u.filter(m=>m.status==="failed").map(m=>m.feature),outcomes:u}}ot.setAppAiFeatures=One;var oL="GptPowerPrompt",Dne='{ "consumptionSource": "Api", "partnerSource": "AIBuilder", "consumptionSourceVersion": "GptApiClient"}';function aL(e){var t,n,r,i;let o=e.entityLogicalName,a=[{type:"literal",text:e.instruction.replace(/\s*$/,"")+" "}];return e.columns.forEach((s,u)=>{a.push({type:"data",id:`${o}.${s.logical}`,text:s.display}),u<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:(n=e.temperature)!==null&&n!==void 0?n:0}},settings:{recordRetrievalLimit:(r=e.recordRetrievalLimit)!==null&&r!==void 0?r:30,shouldPreserveRecordLinks:null,runtime:null,enableReasoning:(i=e.enableReasoning)!==null&&i!==void 0?i:!0},code:"",signature:""}}ot.buildGptDynamicPrompt=aL;async function Pne(e,t){var n;let r=`/EntityDefinitions(LogicalName='${(0,$t.odataPathLiteral)(t)}')${(0,$t.odataQuery)([["$select","MetadataId"]])}`,i=(0,Ji.ensureSuccess)(await e.get(r),e.apiUrl(r)),o=(n=i.body)===null||n===void 0?void 0:n.MetadataId;if(typeof o!="string"||o==="")throw new st.ConnectionError(e.apiUrl(r),i.status,`the table metadata read for '${t}' returned a malformed answer \u2014 expected a MetadataId but got ${o===""?"an empty string":(0,fi.describeMalformedValue)(o)}`);return o}function YE(e,t,n,r,i){if(e.length===0){if(!(0,fi.boundedPageComplete)(i,0))throw new st.ConnectionError(t,n,`${r} ${dp}`);return}let o=e[0];if(typeof o!="object"||o===null||Array.isArray(o))throw new st.ConnectionError(t,n,`${r} returned a malformed row \u2014 expected an object but got ${Array.isArray(o)?"an array":(0,fi.describeMalformedValue)(o)}`);return o}async function sL(e){var t;let n=`/msdyn_aitemplates${(0,$t.odataQuery)([["$select","msdyn_aitemplateid"],["$filter",`msdyn_uniquename eq '${oL}'`],["$top",1]])}`,r=(0,Ji.ensureSuccess)(await e.get(n),e.apiUrl(n)),i=(t=r.body)===null||t===void 0?void 0:t.value;if(!Array.isArray(i))throw new st.ConnectionError(e.apiUrl(n),r.status,`the row-summary template lookup returned a malformed answer \u2014 expected an OData 'value' array but got ${(0,fi.describeMalformedValue)(i)}`);let o=YE(i,e.apiUrl(n),r.status,"the row-summary template lookup",r.body);if(!o)return;let a=o.msdyn_aitemplateid;if(typeof a=="string"&&a!=="")try{return(0,$t.normalizeGuid)(a,"msdyn_aitemplateid")}catch{}throw new st.ConnectionError(e.apiUrl(n),r.status,`the row-summary template lookup returned a malformed row \u2014 expected a GUID 'msdyn_aitemplateid' but got ${a===""?"an empty string":typeof a=="string"?"a string that is not a GUID":(0,fi.describeMalformedValue)(a)}`)}function uL(e){return`${e} row summary`}async function Rne(e,t,n){var r;let i=`/msdyn_aimodels(${t})${(0,$t.odataQuery)([["$select","msdyn_name,_msdyn_templateid_value"]])}`,o=await e.get(i);if(o.status===404)return!1;let a=(r=(0,Ji.ensureSuccess)(o,e.apiUrl(i)).body)!==null&&r!==void 0?r:{},s=await sL(e);return typeof a.msdyn_name=="string"&&a.msdyn_name.toLowerCase()===uL(n).toLowerCase()&&typeof a._msdyn_templateid_value=="string"&&s!==void 0&&a._msdyn_templateid_value.toLowerCase()===s.toLowerCase()}async function kne(e,t,n={}){var r;let i=`ais_RowSummary_${t.entityLogicalName}`,o=`/aiskillconfigs${(0,$t.odataQuery)([["$select","aiskillconfigid,_aimodel_value"],["$filter",`uniquename eq '${(0,$t.odataLiteral)(i)}'`],["$top",1]])}`,a=(0,Ji.ensureSuccess)(await e.get(o),e.apiUrl(o)),s=(r=a.body)===null||r===void 0?void 0:r.value;if(!Array.isArray(s))throw new st.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,fi.describeMalformedValue)(s)}`);let u=YE(s,e.apiUrl(o),a.status,"the existing row-summary skill lookup",a.body);if(u)return{modelId:u._aimodel_value,aiSkillConfigId:u.aiskillconfigid};let l=await Pne(e,t.entityLogicalName),c=await sL(e);if(c===void 0)throw new st.SdkError(ot.ROW_SUMMARY_TEMPLATE_NOT_FOUND_CODE,`Cannot configure the row summary of '${t.entityLogicalName}': this org has no AI template '${oL}' (msdyn_aitemplates), which a row-summary model is built from. Nothing was written.`);let d=(0,Y$.newId)(),f=(0,Y$.newId)(),p=JSON.stringify(aL(t)),m={ModelId:d,RunConfigurationId:f,ModelName:uL(t.entityLogicalName),TemplateId:c,CustomConfiguration:p,Source:Dne,RunConfiguration:""};(0,Ji.ensureSuccess)(await e.post("/AIModelPublish",m),e.apiUrl("/AIModelPublish"));try{let h={uniquename:i,description:`${t.entityLogicalName} row summary`,"[email protected]":`/entities(${l})`,"[email protected]":`/msdyn_aimodels(${d})`,aiskill:"RowSummary"},g=(0,Ji.ensureSuccess)(await e.post("/aiskillconfigs",h),e.apiUrl("/aiskillconfigs")),y=(0,Ji.requireCreatedId)(g,"aiskillconfigid","row-summary skill");return{modelId:d,aiSkillConfigId:y}}catch(h){try{await e.delete(`/msdyn_aimodels(${d})`)}catch{}throw h}}ot.configureRowSummary=kne;async function $ne(e,t){var n;let r=`ais_RowSummary_${t.entityLogicalName}`,i=`/aiskillconfigs${(0,$t.odataQuery)([["$select","aiskillconfigid,_aimodel_value"],["$filter",`uniquename eq '${(0,$t.odataLiteral)(r)}'`],["$top",1]])}`,o=(0,Ji.ensureSuccess)(await e.get(i),e.apiUrl(i)),a=(n=o.body)===null||n===void 0?void 0:n.value;if(!Array.isArray(a))throw new st.ConnectionError(e.apiUrl(i),o.status,`the row-summary skill lookup returned a malformed answer \u2014 expected an OData 'value' array but got ${(0,fi.describeMalformedValue)(a)}`);let s=YE(a,e.apiUrl(i),o.status,"the row-summary skill lookup",o.body);if(!s)return{removed:!1};let u=(0,$t.normalizeGuid)(s.aiskillconfigid,"aiskillconfigid"),l=s._aimodel_value?(0,$t.normalizeGuid)(s._aimodel_value,"_aimodel_value"):void 0,c=l?await Rne(e,l,t.entityLogicalName):!1,d=t.entityLogicalName,f=`/aiskillconfigs(${u})`,p=await eL(e,f,`${f}${(0,$t.odataQuery)([["$select","aiskillconfigid"]])}`);if(p.kind==="failed")throw p.stillThere===void 0&&l&&c?(0,st.attachCause)(new st.SdkError(ot.ROW_SUMMARY_REMOVAL_UNCONFIRMED_CODE,`Removing the row summary of '${d}' could not be confirmed: deleting its skill row failed (${tL(p.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.`),p.failure):p.failure;if(l&&c){let m=`/msdyn_aimodels(${l})`,h=await eL(e,m,`${m}${(0,$t.odataQuery)([["$select","msdyn_aimodelid"]])}`,Mne);if(h.kind==="failed")throw(0,st.attachCause)(new st.SdkError(ot.ROW_SUMMARY_MODEL_NOT_DELETED_CODE,`The row summary of '${d}' was removed, but its AI model '${l}' ${h.stillThere?"was not deleted":"could not be confirmed deleted"} (${tL(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)}return{removed:!0}}ot.removeRowSummary=$ne;ot.ROW_SUMMARY_MODEL_NOT_DELETED_CODE="ROW_SUMMARY_MODEL_NOT_DELETED";ot.ROW_SUMMARY_REMOVAL_UNCONFIRMED_CODE="ROW_SUMMARY_REMOVAL_UNCONFIRMED";ot.ROW_SUMMARY_TEMPLATE_NOT_FOUND_CODE="ROW_SUMMARY_TEMPLATE_NOT_FOUND";var Lne="0x8004f01f";function Mne(e){var t,n;let r=(n=(t=e.body)===null||t===void 0?void 0:t.error)===null||n===void 0?void 0:n.code;return e.status===400&&typeof r=="string"&&r.toLowerCase()===Lne}function xne(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 eL(e,t,n,r=()=>!1){let i;try{let o=await(0,Ji.resendWhile)(xne,()=>e.delete(t));if(o.status>=200&&o.status<300||o.status===404)return{kind:"gone"};if(r(o))return{kind:"kept"};try{(0,Ji.ensureSuccess)(o,e.apiUrl(t))}catch(a){i=a}}catch(o){i=o}try{let o=await e.get(n);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 tL(e){return e instanceof Error?e.message:String(e)}});var ZE=C(Yi=>{"use strict";Object.defineProperty(Yi,"__esModule",{value:!0});Yi.readWebResourceByName=Yi.deleteWebResource=Yi.getWebResource=Yi.updateWebResource=Yi.createWebResource=void 0;var lL=Ke(),Fne=mo(),Qs=pe(),Ys=ae(),XE=ia(),Za=Y(),Une={html:1,css:2,js:3,xml:4,png:5,jpg:6,gif:7,xsl:9,ico:10,svg:11,resx:12};function cL(e){if(e.contentBase64!==void 0)return e.contentBase64;if(e.content!==void 0)return(0,XE.utf8ToBase64)(e.content)}async function dL(e,t){return(0,Fne.publishWebResourceById)(e,t)}async function fL(e,t,n){try{await dL(e,t)}catch(r){let i=n?`Web resource '${n.name}' (${t})`:`Web resource ${t}`,o=`write its content again with updateWebResource('${t}', \u2026), which publishes and verifies again`+(n?" \u2014 it exists, and a second create of this name is refused":""),a=(0,Qs.isConcurrencyLockRefusalError)(r)?`Another customization operation holds the environment's lock, and content has been observed missing after a publish the lock refused, so publishing again alone may not recover it: once the lock frees, ${o}.`:`Resolve that failure first, then ${o}.`;throw(0,Za.attachCause)(new Za.WebResourceUnverifiedError(t,n?.name,`${i} was written, but publishing it failed, so whether its published content is what was sent is unconfirmed (${r instanceof Error?r.message:String(r)}). ${a}`),r)}}function qne(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}async function pL(e,t,n,r){var i;let o=r?`Web resource '${r.name}' (${t})`:`Web resource ${t}`,a=r?`It exists: write its content again with updateWebResource('${t}', \u2026), which publishes and verifies again \u2014 a second create of this name is refused.`:"Writing it again is safe.",s=c=>new Za.WebResourceUnverifiedError(t,r?.name,`${o} ${c} ${a}`),u=`/webresourceset(${t})${(0,Ys.odataQuery)([["$select","content"]])}`,l;try{l=(i=(0,Qs.ensureSuccess)(await e.get(u),e.apiUrl(u)).body)===null||i===void 0?void 0:i.content}catch(c){throw(0,Za.attachCause)(s("was written and published, but reading its published content back failed, so whether the write applied is unknown."),c)}if(typeof l!="string")throw s("was written and published, but the read-back carried no content, so whether the write applied is unknown.");if(!qne((0,XE.base64ToBytes)(l),(0,XE.base64ToBytes)(n)))throw s("was written and published, but the published content is not what was sent, so the write did not apply.")}async function Bne(e,t){var n;let r=cL(t);if(r===void 0)throw new Za.InvalidArgumentError(`web resource '${t.name}' requires content or contentBase64`);let i={name:t.name,displayname:(n=t.displayName)!==null&&n!==void 0?n:t.name,webresourcetype:Une[t.type],content:r};t.description&&(i.description=t.description);let o=(0,Qs.ensureSuccess)(await e.post("/webresourceset",i),e.apiUrl("/webresourceset")),a=(0,Qs.readCreatedId)(o,"webresourceid");if(!a)throw new Za.InvalidArgumentError(`Dataverse did not return an id for web resource '${t.name}'`);return t.publish!==!1&&(await fL(e,a,{name:t.name}),await pL(e,a,r,{name:t.name})),{id:a,name:t.name}}Yi.createWebResource=Bne;async function Vne(e,t,n){let r=(0,Ys.normalizeGuid)(t,"id"),i={},o=cL(n);o!==void 0&&(i.content=o),n.displayName!==void 0&&(i.displayname=n.displayName),n.description!==void 0&&(i.description=n.description);let a=`/webresourceset(${r})`;(0,Qs.ensureSuccess)(await e.patch(a,i),e.apiUrl(a)),n.publish!==!1&&(o!==void 0?(await fL(e,r,void 0),await pL(e,r,o,void 0)):await dL(e,r))}Yi.updateWebResource=Vne;async function Gne(e,t){let r=`/webresourceset(${(0,Ys.normalizeGuid)(t,"id")})${(0,Ys.odataQuery)([["$select","name,displayname,webresourcetype,content,description"]])}`,i=e.apiUrl(r),o=(0,Qs.ensureSuccess)(await e.get(r),i),a=o.body;if(a===null||typeof a!="object"||Array.isArray(a))throw new Za.ConnectionError(i,o.status,`getWebResource: the answer is not a web resource row (${Array.isArray(a)?"an array":(0,lL.describeMalformedValue)(a)}); an unreadable answer is never returned as an empty record.`);return a}Yi.getWebResource=Gne;async function jne(e,t){let r=`/webresourceset(${(0,Ys.normalizeGuid)(t,"id")})`;(0,Qs.ensureSuccess)(await e.delete(r),e.apiUrl(r))}Yi.deleteWebResource=jne;async function Wne(e,t,n={}){var r;let i=`/webresourceset${(0,Ys.odataQuery)([["$select",`webresourceid,name,webresourcetype${n.content?",content":""}`],["$filter",`name eq '${(0,Ys.odataLiteral)(t)}'`]])}`,o=(0,Qs.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 Za.ConnectionError(e.apiUrl(i),o.status,`the web resource lookup for '${t}' answered without a value array`);let s=a.find(u=>typeof u?.name=="string"&&u.name.toLowerCase()===t.toLowerCase());if(!s&&(0,lL.pageEnd)(o.body).kind!=="end")throw new Za.ConnectionError(e.apiUrl(i),o.status,`the web resource lookup for '${t}' answered no match but says more rows exist`);if(s?.webresourceid)return{id:(0,Ys.normalizeGuid)(s.webresourceid,"webresourceid"),name:s.name,type:Number(s.webresourcetype),...typeof s.content=="string"?{content:s.content}:{}}}Yi.readWebResourceByName=Wne});var eA=C(Bg=>{"use strict";Object.defineProperty(Bg,"__esModule",{value:!0});Bg.THEME_PALETTE_SLOTS=void 0;Bg.THEME_PALETTE_SLOTS=["darker70","darker60","darker50","darker40","darker30","darker20","darker10","primary","lighter10","lighter20","lighter30","lighter40","lighter50","lighter60","lighter70","lighter80"]});var mL=C(Vg=>{"use strict";Object.defineProperty(Vg,"__esModule",{value:!0});Vg.fnv1a64Hex=void 0;function zne(e){let t=8997,n=33826,r=40164,i=52210;for(let o=0;o<e.length;o++){t^=e[o];let a=t*435,s=n*435+(a>>>16),u=r*435+(s>>>16),l=i*435+(u>>>16),c=(u&65535)+(t<<8&65535),d=(l&65535)+(t>>>8)+(n<<8&65535)+(c>>>16);t=a&65535,n=s&65535,r=c&65535,i=d&65535}return[i,r,n,t].map(o=>o.toString(16).padStart(4,"0")).join("")}Vg.fnv1a64Hex=zne});var aA=C(Ct=>{"use strict";Object.defineProperty(Ct,"__esModule",{value:!0});Ct.settingValueIsNone=Ct.validatePublisherPrefix=Ct.isSdkVersion=Ct.isSdkVersionName=Ct.themeVersionName=Ct.imageDimensions=Ct.themeWarnings=Ct.contrastRatio=Ct.parseAppThemeXml=Ct.serializeAppTheme=Ct.validateAppTheme=Ct.LOGO_IMAGE_TYPES=void 0;var Hne=Ms(),Kne=Y(),Gg=eA(),Jne=ia(),wL=mL(),Yne=["basePaletteColor","lockPrimary","vibrancy","hueTorsion","font","logoWebResource","logoTooltip"],fp=["background","foreground","backgroundHover","foregroundHover","backgroundPressed","foregroundPressed","backgroundSelected","foregroundSelected"],EL=new Map([...Yne,...Gg.THEME_PALETTE_SLOTS].map(e=>[e.toLowerCase(),e])),AL=new Map(fp.map(e=>[e.toLowerCase(),e])),Qne=["basePaletteColor","lockPrimary","vibrancy","hueTorsion","font","palette","appHeader","logo","additionalAttributes"],rA=/^#[0-9A-Fa-f]{6}$/,Xne=/^[A-Za-z_][A-Za-z0-9_.-]*$/,Zne=/^[A-Za-z0-9_./-]{1,256}$/,ere=/[\u0000-\u001F\u007F]/,hL=200;Ct.LOGO_IMAGE_TYPES=[5,6,7,10,11];var CL=/^[A-Za-z][A-Za-z0-9]{1,7}_\/apptheme\/([0-9a-f]{16})\.xml$/;function Zs(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Hn(e,t,n){return{pointer:e,rule:t,message:n}}function iA(e,t,n){(typeof e!="string"||e.length===0||e.length>hL||ere.test(e))&&n.push(Hn(t,"theme-text",`must be 1\u2013${hL} characters with no control character (got ${Pc(e)})`))}function tA(e,t,n){(typeof e!="string"||!rA.test(e))&&n.push(Hn(t,"theme-color-hex",`must be a #RRGGBB colour (got ${Pc(e)})`))}function Pc(e){return typeof e=="string"?e.length>40?`a ${e.length}-character string`:JSON.stringify(e):e===null?"null":typeof e}function gL(e,t,n,r){if(!Zs(e)){r.push(Hn(t,"theme-attribute-name","must be an object of attribute name \u2192 value"));return}let i=new Set;for(let[o,a]of Object.entries(e)){let s=`${t}/${o}`;if(!Xne.test(o)||/^xml/i.test(o)){r.push(Hn(s,"theme-attribute-name",`'${o}' is not an unqualified attribute name (letters, digits, _ . -, not starting with a digit or 'xml'; no namespace prefix)`));continue}let u=o.toLowerCase();if(n.has(u)){r.push(Hn(s,"theme-attribute-collision",`'${o}' is the modelled attribute '${n.get(u)}' \u2014 set it typed`));continue}if(i.has(u)){r.push(Hn(s,"theme-attribute-duplicate",`'${o}' repeats another additional attribute ignoring case`));continue}i.add(u),iA(a,s,r)}}function SL(e){let t=[];if(!Zs(e))return[Hn("","theme-empty","a theme must be an object with at least one property (use null to remove it)")];e.basePaletteColor!==void 0&&tA(e.basePaletteColor,"/basePaletteColor",t),e.lockPrimary!==void 0&&typeof e.lockPrimary!="boolean"&&t.push(Hn("/lockPrimary","theme-boolean",`must be true or false (got ${Pc(e.lockPrimary)})`));for(let r of["vibrancy","hueTorsion"]){let i=e[r];i!==void 0&&(typeof i!="number"||!Number.isInteger(i)||i<-100||i>100)&&t.push(Hn(`/${r}`,"theme-number-range",`must be an integer from -100 to 100 (got ${Pc(i)})`))}e.font!==void 0&&iA(e.font,"/font",t);let n=["basePaletteColor","lockPrimary","vibrancy","hueTorsion","font"].some(r=>e[r]!==void 0);if(e.palette!==void 0)if(!Zs(e.palette))t.push(Hn("/palette","theme-palette-slot","must be an object of slot \u2192 colour"));else for(let[r,i]of Object.entries(e.palette))n=!0,Gg.THEME_PALETTE_SLOTS.includes(r)?tA(i,`/palette/${r}`,t):t.push(Hn(`/palette/${r}`,"theme-palette-slot",`'${r}' is not one of the 16 palette slots`));if(e.appHeader!==void 0){n=!0;let r=e.appHeader;if((!Zs(r)||r.background===void 0)&&t.push(Hn("/appHeader/background","theme-app-header-background-required","header colours need a background")),Zs(r)){for(let i of fp)r[i]!==void 0&&tA(r[i],`/appHeader/${i}`,t);r.additionalAttributes!==void 0&&gL(r.additionalAttributes,"/appHeader/additionalAttributes",AL,t);for(let i of Object.keys(r))!fp.includes(i)&&i!=="additionalAttributes"&&t.push(Hn(`/appHeader/${i}`,"theme-unknown-property",`'${i}' is not a header property`))}}if(e.logo!==void 0){n=!0;let r=e.logo;if((!Zs(r)||r.webResourceName===void 0&&r.tooltip===void 0)&&t.push(Hn("/logo","theme-empty","a logo needs a webResourceName, a tooltip, or both")),Zs(r)){r.webResourceName!==void 0&&(typeof r.webResourceName!="string"||!Zne.test(r.webResourceName))&&t.push(Hn("/logo/webResourceName","theme-logo-name",`must be a web resource name (letters, digits, _ - . /) (got ${Pc(r.webResourceName)})`)),r.tooltip!==void 0&&iA(r.tooltip,"/logo/tooltip",t);for(let i of Object.keys(r))i!=="webResourceName"&&i!=="tooltip"&&t.push(Hn(`/logo/${i}`,"theme-unknown-property",`'${i}' is not a logo property`))}}e.additionalAttributes!==void 0&&(Zs(e.additionalAttributes)&&Object.keys(e.additionalAttributes).length>0&&(n=!0),gL(e.additionalAttributes,"/additionalAttributes",EL,t));for(let r of Object.keys(e))Qne.includes(r)||t.push(Hn(`/${r}`,"theme-unknown-property",`'${r}' is not a theme property`));return!n&&t.length===0&&t.push(Hn("","theme-empty","a theme needs at least one property (use null to remove it)")),t}Ct.validateAppTheme=SL;function tre(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function nA(e){return e.map(([t,n])=>` ${t}="${tre(n)}"`).join("")}function NL(e){var t,n,r,i,o;let a=[],s=(l,c)=>{c!==void 0&&a.push([l,String(c)])};s("basePaletteColor",e.basePaletteColor),s("lockPrimary",e.lockPrimary),s("vibrancy",e.vibrancy),s("hueTorsion",e.hueTorsion),s("font",e.font),s("logoWebResource",(t=e.logo)===null||t===void 0?void 0:t.webResourceName),s("logoTooltip",(n=e.logo)===null||n===void 0?void 0:n.tooltip);for(let l of Gg.THEME_PALETTE_SLOTS)s(l,(r=e.palette)===null||r===void 0?void 0:r[l]);for(let[l,c]of Object.entries((i=e.additionalAttributes)!==null&&i!==void 0?i:{}))a.push([l,c]);if(!e.appHeader)return`<CustomTheme${nA(a)} />`;let u=[];for(let l of fp){let c=e.appHeader[l];c!==void 0&&u.push([l,c])}for(let[l,c]of Object.entries((o=e.appHeader.additionalAttributes)!==null&&o!==void 0?o:{}))u.push([l,c]);return`<CustomTheme${nA(a)}><AppHeaderColors${nA(u)} /></CustomTheme>`}Ct.serializeAppTheme=NL;var nre=1,oA=3,rre=7;function Xs(e){return{exact:!1,diagnostics:[`not representable by AppTheme: ${e}`]}}function _L(e,t){let n=new Map,r=[],i=new Map,o=!1,a=e.attributes;for(let s=0;s<a.length;s++){let u=a.item(s);if(!u)continue;let l=u.name;if(l==="xmlns"||l.startsWith("xmlns:"))return`a namespace declaration (${l})`;if(u.prefix||l.includes(":"))return`a qualified attribute (${l})`;let c=l.toLowerCase(),d=t.get(c);if(i.has(c)&&(d||t.has(c)))return`two attributes differ only by case (${i.get(c)}, ${l})`;i.set(c,l),d?(n.set(d,u.value),o=o||d!==l):r.push([l,u.value])}return{modelled:n,additional:r,spelling:o}}function IL(e,t){var n;let r=[],i=e.childNodes;for(let o=0;o<i.length;o++){let a=i[o];if(!(a.nodeType===oA&&/^\s*$/.test((n=a.nodeValue)!==null&&n!==void 0?n:""))){if(a.nodeType===nre){let s=a;if(!t.includes(s.nodeName)||s.namespaceURI)return`an unexpected element <${s.nodeName}>`;r.push(s);continue}return a.nodeType===oA?"text content":`an unsupported node (type ${a.nodeType})`}}return r}function ire(e){let t=e.toLowerCase();return t==="true"?!0:t==="false"?!1:e}function yL(e){return/^-?\d+$/.test(e)?parseInt(e,10):e===""?e:Number(e)}function bL(e){let t=_L(e,AL);if(typeof t=="string")return t;let n=IL(e,[]);if(typeof n=="string")return n;let r={};for(let i of fp){let o=t.modelled.get(i);o!==void 0&&(r[i]=o)}return t.additional.length>0&&(r.additionalAttributes=Object.fromEntries(t.additional)),r}function ore(e){var t,n;let r=[],i=h=>g=>{r.push(`${h}: ${g}`)},o=new Hne.DOMParser({errorHandler:{warning:i("warning"),error:i("error"),fatalError:i("fatalError")}}).parseFromString(String(e??""),"text/xml"),a=(t=o?.documentElement)!==null&&t!==void 0?t:null;if(!o||!a||r.length>0)return Xs(`not well-formed XML${r.length>0?` (${r[0]})`:""}`);let s=!1,u=o.childNodes;for(let h=0;h<u.length;h++){let g=u[h];if(!(g===a||g.nodeType===oA&&/^\s*$/.test((n=g.nodeValue)!==null&&n!==void 0?n:""))){if(g.nodeType===rre&&g.target.toLowerCase()==="xml"){s=!0;continue}return Xs(`an unsupported node outside the root (type ${g.nodeType})`)}}if(a.namespaceURI||a.nodeName!=="CustomTheme"&&a.nodeName!=="AppHeaderColors")return Xs(`the root is <${a.nodeName}>, not <CustomTheme> or <AppHeaderColors>`);let l={},c=!1;if(a.nodeName==="AppHeaderColors"){let h=bL(a);if(typeof h=="string")return Xs(h);l.appHeader=h}else{let h=_L(a,EL);if(typeof h=="string")return Xs(h);c=h.spelling;let g=IL(a,["AppHeaderColors"]);if(typeof g=="string")return Xs(g);if(g.length>1)return Xs("more than one <AppHeaderColors>");let y=_=>h.modelled.get(_),b=(_,I)=>{I!==void 0&&(l[_]=I)};b("basePaletteColor",y("basePaletteColor")),b("lockPrimary",y("lockPrimary")===void 0?void 0:ire(y("lockPrimary"))),b("vibrancy",y("vibrancy")===void 0?void 0:yL(y("vibrancy"))),b("hueTorsion",y("hueTorsion")===void 0?void 0:yL(y("hueTorsion"))),b("font",y("font"));let E={};y("logoWebResource")!==void 0&&(E.webResourceName=y("logoWebResource")),y("logoTooltip")!==void 0&&(E.tooltip=y("logoTooltip")),Object.keys(E).length>0&&(l.logo=E);let w={};for(let _ of Gg.THEME_PALETTE_SLOTS){let I=y(_);I!==void 0&&(w[_]=I)}if(Object.keys(w).length>0&&(l.palette=w),g.length===1){let _=bL(g[0]);if(typeof _=="string")return Xs(_);l.appHeader=_}h.additional.length>0&&(l.additionalAttributes=Object.fromEntries(h.additional))}let d=SL(l);if(d.length>0)return{exact:!1,diagnostics:d.map(h=>`not representable by AppTheme: ${h.pointer||"/"} ${h.message} [${h.rule}]`)};let f=l,p=NL(f)===e,m=[];if(!p){let h=[...s?["an XML declaration"]:[],...c?["attribute spelling"]:[],...a.nodeName==="AppHeaderColors"?["the header-only root"]:[]];m.push(`writing this theme back creates a NEW version: its canonical bytes differ from the stored document${h.length>0?` (${h.join(", ")})`:" (attribute order, whitespace or value spelling)"}`)}return{theme:f,exact:p,diagnostics:m}}Ct.parseAppThemeXml=ore;function vL(e){let t=n=>{let r=parseInt(e.slice(n,n+2),16)/255;return r<=.03928?r/12.92:Math.pow((r+.055)/1.055,2.4)};return .2126*t(1)+.7152*t(3)+.0722*t(5)}function TL(e,t){let[n,r]=[vL(e),vL(t)].sort((i,o)=>o-i);return(n+.05)/(r+.05)}Ct.contrastRatio=TL;function are(e){let t=[],n=e.appHeader;if(n){let r=[["rest",n.foreground,n.background],["hover",n.foregroundHover,n.backgroundHover],["pressed",n.foregroundPressed,n.backgroundPressed],["selected",n.foregroundSelected,n.backgroundSelected]];for(let[i,o,a]of r)if(o&&a&&rA.test(o)&&rA.test(a)){let s=TL(o,a);s<4.5&&t.push(`App header ${i} colours ${o} on ${a} have a contrast of ${s.toFixed(2)}:1, below the 4.5:1 Learn asks makers to verify.`)}}return(e.vibrancy!==void 0||e.hueTorsion!==void 0)&&e.lockPrimary!==!0&&t.push('vibrancy/hueTorsion are set without lockPrimary: true \u2014 Learn says they apply only with lockPrimary="true" (its own example contradicts that; the effect is not verified).'),t}Ct.themeWarnings=are;function sre(e){let t=r=>{var i;return(i=e[r])!==null&&i!==void 0?i:0},n=r=>t(r)*256+t(r+1);if(e.length>=24&&t(0)===137&&t(1)===80&&t(2)===78&&t(3)===71)return{width:n(16)*65536+n(18),height:n(20)*65536+n(22)};if(e.length>=10&&t(0)===71&&t(1)===73&&t(2)===70&&t(3)===56)return{width:t(6)+t(7)*256,height:t(8)+t(9)*256};if(e.length>=4&&t(0)===255&&t(1)===216){let r=2;for(;r+3<e.length;){if(t(r)!==255)return;let i=t(r+1);if(i===216||i===1||i>=208&&i<=215){r+=2;continue}if(i>=192&&i<=207&&i!==196&&i!==200&&i!==204)return r+8<e.length?{width:n(r+7),height:n(r+5)}:void 0;r+=2+n(r+2)}}}Ct.imageDimensions=sre;function ure(e,t){return`${e}_/apptheme/${(0,wL.fnv1a64Hex)((0,Jne.utf8ToBytes)(t))}.xml`}Ct.themeVersionName=ure;function lre(e){return typeof e=="string"&&CL.test(e)}Ct.isSdkVersionName=lre;function cre(e,t){let n=typeof e=="string"?CL.exec(e):null;return!!n&&n?.[1]===(0,wL.fnv1a64Hex)(t)}Ct.isSdkVersion=cre;function dre(e){if(typeof e!="string"||!/^[A-Za-z][A-Za-z0-9]{1,7}$/.test(e)||/^mscrm/i.test(e))throw new Kne.InvalidArgumentError(`setAppTheme: publisherPrefix must be 2\u20138 letters or digits starting with a letter, not 'mscrm\u2026' (got ${Pc(e)}).`);return e}Ct.validatePublisherPrefix=dre;function fre(e){return e==null||e===""||e==='""'}Ct.settingValueIsNone=fre});var hA=C(Lt=>{"use strict";Object.defineProperty(Lt,"__esModule",{value:!0});Lt.getAppTheme=Lt.setAppTheme=Lt.HEADER_SETTING=Lt.THEME_SETTING=void 0;var pre=QE(),uA=vc(),mre=Ff(),hre=Ke(),lA=il(),kc=ZE(),bn=aA(),ht=Y(),pA=pe(),mp=ia(),wo=ae();Lt.THEME_SETTING="CustomThemeDefinition";Lt.HEADER_SETTING="OverrideAppHeaderColor";var cA=4,OL=61,gre=80,DL=3;function yre(e){return new Promise(t=>setTimeout(t,e))}function ol(e){return e.plain?e.unpublished?e.unpublished.componentstate===1?"publishedWithDraft":"published":"removalPending":e.unpublished?"draft":"absent"}function mA(e){return e==="published"||e==="publishedWithDraft"||e==="removalPending"}function Rc(e){var t,n,r;return ol(e)==="removalPending"?void 0:(n=(t=e.unpublished)===null||t===void 0?void 0:t.value)!==null&&n!==void 0?n:(r=e.plain)===null||r===void 0?void 0:r.value}function dA(e,t){return(0,bn.settingValueIsNone)(e)&&(0,bn.settingValueIsNone)(t)||e===t}function PL(e){let t=e.plain,n=e.unpublished;return JSON.stringify([t?.id,t?.value,t?.etag,n?.id,n?.value,n?.etag,n?.componentstate])}function LL(e){var t,n;if(e instanceof ht.ConnectionError){let r=(n=(t=e.cause)===null||t===void 0?void 0:t.error)===null||n===void 0?void 0:n.code;return typeof r=="string"?r.toLowerCase():void 0}}function RL(e){return e instanceof ht.SdkError&&e.code===pA.VERSION_CONFLICT_CODE}function $c(e,t,n){return(0,hre.collectPages)(e,t,n)}async function ML(e,t){let r=(await $c(e,(0,uA.unpublishedAppModulesQuery)("appmoduleid,uniquename,name",`appmoduleid eq ${t}`),`the app lookup for '${t}'`))[0];if(!r||typeof r.appmoduleid!="string"||typeof r.uniquename!="string")throw new ht.SdkError("APP_NOT_FOUND",`App '${t}' was not found (checked the unpublished-aware projection, which includes drafts).`);return{id:t,uniqueName:r.uniquename,name:typeof r.name=="string"?r.name:r.uniquename}}async function pp(e,t,n){let r=`_parentappmoduleid_value eq ${t} and (`+n.map(c=>`_settingdefinitionid_value eq ${c}`).join(" or ")+")",i=`/appsettings${(0,wo.odataQuery)([["$select","appsettingid,value,_settingdefinitionid_value"],["$filter",r]])}`,o=`/appsettings/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()${(0,wo.odataQuery)([["$select","appsettingid,value,componentstate,_settingdefinitionid_value"],["$filter",r]])}`,a=await $c(e,i,"the app setting read"),s=await $c(e,o,"the unpublished app setting read"),u=new Map,l=(c,d)=>{var f,p,m;for(let h of c){let g=String((f=h._settingdefinitionid_value)!==null&&f!==void 0?f:"").toLowerCase(),y=(p=u.get(g))!==null&&p!==void 0?p:{};if(y[d])throw new ht.ConnectionError(e.apiUrl(i),200,`two ${d} app setting rows for one setting`);y[d]={id:(0,wo.normalizeGuid)(String((m=h.appsettingid)!==null&&m!==void 0?m:""),"appsettingid"),value:typeof h.value=="string"?h.value:"",etag:typeof h["@odata.etag"]=="string"?h["@odata.etag"]:null,...typeof h.componentstate=="number"?{componentstate:h.componentstate}:{}},u.set(g,y)}};return l(a,"plain"),l(s,"unpublished"),u}async function xL(e,t){var n,r;let i=await(0,mre.resolveSettingDefinitions)(e,[Lt.THEME_SETTING,Lt.HEADER_SETTING]),o=(n=i.get(Lt.THEME_SETTING))===null||n===void 0?void 0:n.settingdefinitionid;if(!o)throw new ht.AppThemeError("APP_THEME_UNAVAILABLE",t,`The modern theme is not available in this environment: no settingdefinition '${Lt.THEME_SETTING}' exists (it is a Preview setting and may be version-gated). Nothing was written.`);let a=(r=i.get(Lt.HEADER_SETTING))===null||r===void 0?void 0:r.settingdefinitionid;return{theme:(0,wo.normalizeGuid)(o,"settingdefinitionid"),...a?{header:(0,wo.normalizeGuid)(a,"settingdefinitionid")}:{}}}async function al(e,t,n){return(await(0,pre.retrieveSetting)(e,t,n?{appUniqueName:n}:{})).value}function FL(e,t,n,r){return(0,bn.settingValueIsNone)(e)?"none":mA(t)?n===e?"app":"unknown":r===e?"environment":"unknown"}function UL(e,t,n,r){let i=[];(e==="draft"||e==="publishedWithDraft")&&i.push("rowDraft"),e==="removalPending"&&i.push("removalPending");let o=mA(e)?t:r;return dA(n,o)||i.push("resolvedDiffers"),i}function bre(e){return typeof e=="string"&&e.length>2&&e.startsWith('"')&&e.endsWith('"')}async function vre(e,t,n){if((await $c(e,`/publishers${(0,wo.odataQuery)([["$select","publisherid"],["$filter",`customizationprefix eq '${(0,wo.odataLiteral)(n)}'`]])}`,`the publisher lookup for prefix '${n}'`)).length===0)throw new ht.InvalidArgumentError(`setAppTheme: no publisher in this environment has the customization prefix '${n}' \u2014 a web resource name must carry an existing publisher's prefix. Nothing was written for app ${t}.`)}var kL=new WeakMap;async function wre(e){var t;let n=kL.get(e);if(n!==void 0)return n;let r=await $c(e,`/solutioncomponentdefinitions${(0,wo.odataQuery)([["$select","solutioncomponenttype,primaryentityname"],["$filter","primaryentityname eq 'appsetting'"]])}`,"the appsetting component definition read"),i=Number((t=r[0])===null||t===void 0?void 0:t.solutioncomponenttype);if(!Number.isInteger(i)||i<=0)throw new ht.ConnectionError(e.apiUrl("/solutioncomponentdefinitions"),200,"the appsetting solution component type could not be read");return kL.set(e,i),i}async function $L(e,t,n){let r=await $c(e,`/solutioncomponents${(0,wo.odataQuery)([["$select","objectid,componenttype"],["$filter",`_solutionid_value eq ${t} and (${n.map(i=>`objectid eq ${i}`).join(" or ")})`]])}`,"the solution membership read");return new Set(r.map(i=>{var o;return`${Number(i.componenttype)}:${String((o=i.objectid)!==null&&o!==void 0?o:"").toLowerCase()}`}))}function qL(e,t,n){if(!(t.type===cA&&typeof t.content=="string"&&Ere((0,mp.base64ToBytes)(t.content),(0,mp.utf8ToBytes)(n))))throw new ht.AppThemeError("APP_THEME_NAME_TAKEN",e,`The theme's version name '${t.name}' (web resource ${t.id}) already holds ${t.type===cA?"different bytes":`a non-XML resource (type ${t.type})`}. Theme versions are never overwritten: nothing was written. A name is not proof of ownership. If it is a version an earlier setAppTheme failed to verify, only an operator can remove it: in a quiet window (no one changing app themes), check that no app resolves it (getAppTheme for each app), no app's setting row names it in either layer, and the environment value does not name it \u2014 then deleteWebResource('${t.id}') and run again.`,t.name)}function Ere(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}async function Are(e,t,n,r){var i;let o=(i=n.logo)===null||i===void 0?void 0:i.webResourceName;if(!o)return;let a=await(0,kc.readWebResourceByName)(e,o,{content:!0});if(!a||!bn.LOGO_IMAGE_TYPES.includes(a.type))throw new ht.AppThemeError("APP_THEME_LOGO_INVALID",t,a?`The logo '${o}' is a web resource of type ${a.type}, not an image (png, jpg, gif, ico or svg). Nothing was written.`:`The logo '${o}' names no web resource \u2014 upload it with createWebResource first. Nothing was written.`,o);let s=typeof a.content=="string"?(0,bn.imageDimensions)((0,mp.base64ToBytes)(a.content)):void 0;s&&(s.width>156||s.height>48)&&r.push(`The logo '${o}' is ${s.width} \xD7 ${s.height} px, larger than the 156 \xD7 48 px Learn recommends; Learn says logos that are too large are not displayed (the limit is not measured \u2014 check in a browser).`)}function fA(e,t){return new ht.VersionConflictError("appTheme",e,null,null,t)}async function Cre(e,t,n,r,i,o){var a,s,u;let l=ol(r),c=f=>{throw f instanceof ht.VersionConflictError?f:RL(f)||LL(f)==="0x80072013"?(0,ht.attachCause)(fA(t,`Another writer changed the app's theme setting at the moment of the write (${RL(f)?"its token moved":"a row for this app was created"}); nothing was written to it and nothing is re-sent.${o}`),f):f},d=()=>{var f;if(!(!((f=r.plain)===null||f===void 0)&&f.etag))throw fA(t,`The app's published theme setting row carried no token, so it cannot be written safely.${o}`);return r.plain.etag};try{if(i!==null){if(l==="absent"){let w="/appsettings",_=await e.post(w,{"[email protected]":`/appmodules(${t})`,"[email protected]":`/settingdefinitions(${n})`,value:i});return sA(e,w,_),{outcome:"created",createdId:(a=(0,pA.readCreatedId)(_,"appsettingid"))!==null&&a!==void 0?a:void 0}}let g=Rc(r);if(l!=="removalPending"&&g===i)return{outcome:"unchanged"};let y=((s=r.plain)!==null&&s!==void 0?s:r.unpublished).id,b=l==="draft"?"*":d(),E=`/appsettings(${y})`;return sA(e,E,await e.patch(E,{value:i},{headers:{"If-Match":b}})),{outcome:"updated"}}if(l==="absent")return{outcome:"unchanged"};if(l==="removalPending")return{outcome:"removed"};let f=((u=r.plain)!==null&&u!==void 0?u:r.unpublished).id,p=l==="draft"?"*":d(),m=`/appsettings(${f})`;return sA(e,m,await e.delete(m,{headers:{"If-Match":p}})),{outcome:"removed"}}catch(f){return c(f)}}function sA(e,t,n){var r,i;if(n.status===412)throw new ht.SdkError(pA.VERSION_CONFLICT_CODE,`Version conflict (412) from ${e.apiUrl(t)}`);if(n.status<200||n.status>=300){let o=(i=(r=n.body)===null||r===void 0?void 0:r.error)===null||i===void 0?void 0:i.message;throw new ht.ConnectionError(e.apiUrl(t),n.status,typeof o=="string"?o:"request failed",n.body)}}async function Sre(e,t,n,r={},i={}){var o,a,s,u,l,c,d,f,p,m,h,g,y,b;let E=(0,wo.normalizeGuid)(t,"appId");if(n!==null){let Kt=(0,bn.validateAppTheme)(n);if(Kt.length>0)throw new ht.ValidationError("appTheme",E,Kt)}let w;if(n!==null){if(r.publisherPrefix!==void 0)w=(0,bn.validatePublisherPrefix)(r.publisherPrefix);else if(!e.solutionName)throw new ht.InvalidArgumentError("setAppTheme: a theme version needs a publisher prefix for its web resource name \u2014 pass options.publisherPrefix, or create the SDK with the solution to write into (solutionUniqueName).")}let I=(o=i.sleep)!==null&&o!==void 0?o:yre,T=n!==null?(0,bn.serializeAppTheme)(n):void 0,O=await ML(e,E),v=await xL(e,E),N=[];v.header||N.push(`The setting ${Lt.HEADER_SETTING} is not available in this environment, so a header-colour override was not checked.`);let S=await pp(e,E,[v.theme,...v.header?[v.header]:[]]),R=(a=S.get(v.theme))!==null&&a!==void 0?a:{},x=v.header?S.get(v.header):void 0;n!==null&&x&&!(0,bn.settingValueIsNone)(Rc(x))&&N.push(`The app also has an "Override app header colors" value ('${Rc(x)}'); the platform ignores it while a custom theme is set (Learn).`);let G,U,M;if(n!==null&&T!==void 0){if(w!==void 0&&await vre(e,E,w),e.solutionName&&(G=await(0,lA.getSolution)(e,e.solutionName),w===void 0)){if(!G.publisherPrefix)throw new ht.InvalidArgumentError(`setAppTheme: the publisher of solution '${G.uniqueName}' has no customization prefix \u2014 pass options.publisherPrefix.`);w=G.publisherPrefix}U=(0,bn.themeVersionName)(w,T),await Are(e,E,n,N),M=await(0,kc.readWebResourceByName)(e,U,{content:!0}),M&&qL(E,M,T),N.push(...(0,bn.themeWarnings)(n))}if(r.publish===!0)try{await(0,uA.assertAppPublicationProvable)(e,E)}catch(Kt){throw(0,ht.attachCause)(new ht.AppThemeError("APP_THEME_PUBLISH_BLOCKED",E,`Nothing was written: setAppTheme with publish: true is refused because the app publication it asks for would be refused. ${Kt instanceof Error?Kt.message:String(Kt)}`,U),Kt)}let q;n!==null&&T!==void 0&&U!==void 0&&(M?q={id:M.id,name:U,created:!1}:q=await Nre(e,E,U,T));let X=q?` The theme version '${q.name}' (${q.id}) exists and a re-run reuses it.`:"",ye=(s=(await pp(e,E,[v.theme])).get(v.theme))!==null&&s!==void 0?s:{};if(PL(ye)!==PL(R))throw fA(E,`The app's theme setting changed after it was read (another writer); nothing was written to it.${X}`);let Ve=await Cre(e,E,v.theme,R,(u=q?.name)!==null&&u!==void 0?u:null,X),_e=(l=(await pp(e,E,[v.theme])).get(v.theme))!==null&&l!==void 0?l:{},wt=ol(_e);if(!(q?Rc(_e)===q.name:wt==="absent"||wt==="removalPending"))throw new ht.AppThemeError("APP_THEME_NOT_SAVED",E,q?`The app's theme setting read back holds '${(c=Rc(_e))!==null&&c!==void 0?c:"(nothing)"}', not '${q.name}'.${X}`:`The app's theme override was removed, but the read-back still shows it (state ${wt}).`,q?.name);let xe=[];if(q&&G){let Kt=(p=(f=(d=_e.unpublished)!==null&&d!==void 0?d:_e.plain)===null||f===void 0?void 0:f.id)!==null&&p!==void 0?p:Ve.createdId;Kt&&xe.push(...await _re(e,E,G,q,Kt,X))}let Et,zt;if(r.publish===!0){try{await(0,uA.publishApp)(e,E)}catch(Yr){let Ql=Yr?.code,dT=Ql==="APP_MAIN_FORM_PUBLISH_WITHHELD"||Ql==="APP_MAIN_FORM_PUBLISH_CONFLICT";throw(0,ht.attachCause)(new ht.AppThemeError("APP_THEME_PUBLISH_FAILED",E,`The app's theme setting is saved (${q?`naming '${q.name}'`:"override removed"}, ${Ve.outcome}), but ${dT?`its app publication was refused (${String(Ql)})`:"publishing the app failed"}, so it does not resolve yet: ${Yr instanceof Error?Yr.message:String(Yr)}. ${dT?"Nothing was published; nothing was re-sent.":"Publish the app again; nothing was re-sent."}`,q?.name),Yr)}zt=q?void 0:await al(e,Lt.THEME_SETTING);let Kt=q?q.name:zt,Lu=!1;for(let Yr=0;Yr<DL&&!Lu;Yr++){Yr>0&&await I(1e3*Yr),Et=await al(e,Lt.THEME_SETTING,O.uniqueName),_e=(m=(await pp(e,E,[v.theme])).get(v.theme))!==null&&m!==void 0?m:{};let Ql=ol(_e);Lu=q?Ql==="published"&&((h=_e.plain)===null||h===void 0?void 0:h.value)===q.name&&dA(Et,q.name):Ql==="absent"&&dA(Et,Kt)}if(!Lu)throw new ht.AppThemeError("APP_THEME_NOT_RESOLVED",E,`The app was published, but the platform's resolved theme for it is '${Et}' (expected '${Kt}', row ${ol(_e)}) after ${DL} reads. This is about stored/resolved state, not rendering.`,q?.name)}else Et=await al(e,Lt.THEME_SETTING,O.uniqueName);let Ht=ol(_e),W=(g=_e.plain)===null||g===void 0?void 0:g.value;zt===void 0&&!mA(Ht)&&(zt=await al(e,Lt.THEME_SETTING));let Fe=Et,Ie=FL(Fe,Ht,W,zt),At=UL(Ht,W,Fe,zt),Ts=[(y=R.plain)===null||y===void 0?void 0:y.value,(b=R.unpublished)===null||b===void 0?void 0:b.value].filter((Kt,Lu,Yr)=>typeof Kt=="string"&&!(0,bn.settingValueIsNone)(Kt)&&Yr.indexOf(Kt)===Lu&&Kt!==q?.name),f6=Ts.filter(Kt=>(0,bn.isSdkVersionName)(Kt));if(Ve.outcome!=="unchanged")for(let Kt of Ts.filter(Lu=>!(0,bn.isSdkVersionName)(Lu)))N.push(`The app's previous theme '${Kt}' is not an SDK theme version; it was ${q?"replaced":"unset"} for this app and left untouched.`);return{appId:E,outcome:Ve.outcome,...q?{webResource:q}:{},published:r.publish===!0,resolved:{source:Ie,...Ie!=="none"?{webResourceName:Fe}:{}},rowState:Ht,pendingPublish:At.length>0,pendingReasons:At,superseded:f6,solutionComponentsAdded:xe,warnings:N}}Lt.setAppTheme=Sre;async function Nre(e,t,n,r){let i=n.slice(n.lastIndexOf("/")+1,-4);try{return{id:(await(0,kc.createWebResource)(e,{name:n,type:"xml",content:r,displayName:`Modern app theme ${i}`,description:"Immutable modern-theme XML written by setAppTheme (cds-maker-sdk). Changing a theme creates a new version.",publish:!0})).id,name:n,created:!0}}catch(o){let a=LL(o);if(a==="0x8004f115"){let s=await(0,kc.readWebResourceByName)(e,n,{content:!0});if(s)return qL(t,s,r),{id:s.id,name:n,created:!1}}throw a==="0x8004f118"?(0,ht.attachCause)(new ht.InvalidArgumentError(`setAppTheme: '${n}' does not carry a valid customization prefix (an existing publisher's). Nothing was written.`),o):o}}async function _re(e,t,n,r,i,o){let a=(s,u)=>{let l=new ht.AppThemeError("APP_THEME_NOT_IN_SOLUTION",t,`The theme setting is saved, but ${s} in solution '${n.uniqueName}'.${o} Run again to retry the membership.`,r.name);throw u===void 0?l:(0,ht.attachCause)(l,u)};try{let s=await wre(e),u=[r.id,i,t].map(h=>h.toLowerCase()),l=await $L(e,n.solutionId,u),c=[],d=`${OL}:${u[0]}`,f=`${s}:${u[1]}`;if(l.has(d)||(await(0,lA.addSolutionComponent)(e,{componentId:r.id,componentType:OL,solutionUniqueName:n.uniqueName,addRequiredComponents:!1}),c.push("webResource")),l.has(f)||(await(0,lA.addSolutionComponent)(e,{componentId:i,componentType:s,solutionUniqueName:n.uniqueName,addRequiredComponents:!1}),c.push("appSetting")),c.length===0)return c;let p=await $L(e,n.solutionId,u);if(!p.has(d)||!p.has(f))return a("the theme version or the setting row is still not a member after adding it");let m=`${gre}:${u[2]}`;return p.has(m)&&!l.has(m)&&c.push("app"),c}catch(s){if(s instanceof ht.AppThemeError)throw s;return a("the theme version or the setting row could not be added",s)}}async function Ire(e,t){var n,r,i;let o=(0,wo.normalizeGuid)(t,"appId"),a=await ML(e,o),s=await xL(e,o),u=[],l=await pp(e,o,[s.theme,...s.header?[s.header]:[]]),c=(n=l.get(s.theme))!==null&&n!==void 0?n:{},d=ol(c),f=(r=c.plain)===null||r===void 0?void 0:r.value,p=Rc(c),m=await al(e,Lt.THEME_SETTING,a.uniqueName),h=await al(e,Lt.THEME_SETTING),g=UL(d,f,m,h),y=new Map,b=(I,T)=>{if(I==="none"||T===void 0||(0,bn.settingValueIsNone)(T))return Promise.resolve({source:"none"});let O=`${I}\0${T}`;return y.has(O)||y.set(O,Tre(e,I,T,u)),y.get(O)},E=await b(FL(m,d,f,h),m),w=d==="absent"||d==="removalPending"?await b((0,bn.settingValueIsNone)(h)?"none":"environment",h):await b((0,bn.settingValueIsNone)(p)?"none":"app",p);for(let I of[f,p,h])bre(I)&&u.push(`The theme setting value ${I} is wrapped in quotes \u2014 Learn says to remove them; it is reported verbatim.`);g.includes("resolvedDiffers")&&!g.includes("rowDraft")&&!g.includes("removalPending")&&u.push("The app's theme setting row is published but the app is not \u2014 publish the app so it resolves (a setting-only publish does not change what the app resolves).");for(let I of new Set([E,w]))await Ore(e,I,u);let _;if(s.header){let I=await al(e,Lt.HEADER_SETTING,a.uniqueName);if(!(0,bn.settingValueIsNone)(I)){let T=l.get(s.header);_={source:((i=T?.plain)===null||i===void 0?void 0:i.value)===I?"app":"environment",webResourceName:I},E.source!=="none"&&u.push(`"Override app header colors" ('${I}') is set, but it is ignored by the platform while a custom theme is set (Learn).`)}}else u.push(`The setting ${Lt.HEADER_SETTING} is not available in this environment, so it was not read.`);return{appId:o,appUniqueName:a.uniqueName,resolved:E,row:{state:d,...f!==void 0?{publishedValue:f}:{},...p!==void 0?{latestValue:p}:{}},afterPublish:w,pendingPublish:g.length>0,pendingReasons:g,..._?{headerColorOverride:_}:{},warnings:u}}Lt.getAppTheme=Ire;async function Tre(e,t,n,r){let i;try{i=await(0,kc.readWebResourceByName)(e,n,{content:!0})}catch(s){let u=s instanceof Error?s.message:String(s);return r.push(`The theme web resource '${n}' (${t}) could not be read, so its content is unverified: ${u}`),{source:t,webResourceName:n,diagnostics:[`unreadable: ${u}`]}}if(!i)return r.push(`The theme web resource '${n}' (${t}) does not exist \u2014 the setting names nothing readable.`),{source:t,webResourceName:n};if(i.type!==cA||typeof i.content!="string")return r.push(`The theme web resource '${n}' is not an XML web resource (type ${i.type}).`),{source:t,webResourceName:n,diagnostics:["not an XML web resource"],sdkVersion:!1};let o=(0,mp.base64ToBytes)(i.content),a=(0,bn.parseAppThemeXml)((0,mp.base64ToUtf8)(i.content));return a.theme||r.push(`The theme web resource '${n}' is not representable as an AppTheme (see its diagnostics).`),{source:t,webResourceName:n,...a.theme?{theme:a.theme}:{},exact:a.exact,diagnostics:a.diagnostics,sdkVersion:(0,bn.isSdkVersion)(n,o)}}async function Ore(e,t,n){var r,i;let o=(i=(r=t.theme)===null||r===void 0?void 0:r.logo)===null||i===void 0?void 0:i.webResourceName;if(o)try{await(0,kc.readWebResourceByName)(e,o)||n.push(`The theme '${t.webResourceName}' names the logo '${o}', which no longer exists.`)}catch(a){n.push(`The logo '${o}' named by the theme '${t.webResourceName}' could not be checked: ${a instanceof Error?a.message:String(a)}`)}}});var Kg=C(we=>{"use strict";Object.defineProperty(we,"__esModule",{value:!0});we.buildRecipe=we.roleIdentity=we.readPlanInput=we.readLimits=we.requireCodec=we.unknown=we.refusal=we.CERTIFIED_GATES=void 0;var BL=cp(),ze=Ya(),Dre=kg(),VL=hA(),Pre=aA(),Rre=new Set([VL.THEME_SETTING,VL.HEADER_SETTING].map(e=>e.toLowerCase())),kre=e=>Rre.has(e.definition.toLowerCase())&&!(0,Pre.settingValueIsNone)(e.value);we.CERTIFIED_GATES=Object.freeze({connectionReferences:!1,secretReferences:!1,unmanagedImport:!1,stageCleanup:!1});var $re=(e,t={})=>({problem:(0,ze.promotionProblem)(e,"preflight",t),unknown:!1});we.refusal=$re;var Lre=(e={})=>({problem:(0,ze.promotionProblem)("PROMOTION_VERIFICATION_UNAVAILABLE","preflight",e),unknown:!0});we.unknown=Lre;var Mre=new Set(["packageBase64","appUniqueName","mode","values","connections","settingOverrides","requirements","overwriteUnmanagedCustomizations","publishWorkflows","acknowledgeNonAtomicImport","publishApp","codec","limits"]),xre=new Set(["upgrade","stageAndUpgrade","holdingSolution","importAsHolding","convertToManaged","deleteSolution","uninstall","applyUpgrade"]),un=e=>(0,ze.promotionError)("INVALID_ARGUMENT","preflight",{reason:e}),Hg=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function ki(e,t,n,r){if(!Hg(e))throw un(`${r} must be an object`);for(let i of Object.keys(e))if(!t.includes(i)&&!n.includes(i))throw un(`${r} has an unsupported field`);for(let i of t)if(e[i]===void 0)throw un(`${r} lacks a required field`);return e}function es(e,t){if(typeof e!="string"||e.length===0||e.trim()!==e)throw un(`${t} must be a non-empty string without surrounding whitespace`);return e}function jg(e,t,n){if(!(e===void 0&&n)){if(typeof e!="boolean")throw un(`${t} must be true or false`);return e}}function Wg(e,t){if(!Array.isArray(e))throw un(`${t} must be an array`);return e}function zg(e,t,n){let r=new Set;for(let i of e){let o=t(i).toLowerCase();if(r.has(o))throw un(`${n} names one item twice`);r.add(o)}return[...e].sort((i,o)=>(0,ze.byCodeUnit)(t(i).toLowerCase(),t(o).toLowerCase()))}function GL(e){let t=e;if(!t||typeof t.inflateRaw!="function"||typeof t.sha256!="function")throw(0,ze.promotionError)("PROMOTION_CODEC_REQUIRED","preflight");return t}we.requireCodec=GL;function jL(e){if(e===void 0)return{...ze.DEFAULT_LIMITS};let t=ki(e,[],Object.keys(ze.DEFAULT_LIMITS),"limits"),n={...ze.DEFAULT_LIMITS};for(let r of Object.keys(t)){let i=t[r];if(i!==void 0){if(typeof i!="number"||!Number.isSafeInteger(i)||i<=0)throw un("a limit must be a positive safe integer");n[r]=i}}return n}we.readLimits=jL;function Fre(e){let t=ki(e,["kind","identity","businessUnit"],[],"a requirement role");if(t.kind!=="role"||t.businessUnit!=="root")throw un("a requirement role must be a root role identity");let n=ki(t.identity,["scheme"],["templateId","packageRoleId"],"a role identity"),r=(0,ze.canonicalGuid)(n.scheme==="template"?n.templateId:n.packageRoleId);if(!r||n.scheme!=="template"&&n.scheme!=="package")throw un("a role identity must be a template or package role GUID");return{kind:"role",identity:n.scheme==="template"?{scheme:"template",templateId:r}:{scheme:"package",packageRoleId:r},businessUnit:"root"}}function Ure(e){var t,n,r;let i=Hg(e)?e.kind:void 0,o=(a,s)=>{if(typeof a!="string"||!s.includes(a))throw un("requiredBefore is not a supported phase");return a};if(i==="organizationSetting"){let a=ki(e,["id","kind","settingUniqueName","expectedValue","requiredBefore"],[],"a requirement");if(typeof a.expectedValue!="string")throw un("a requirement expectedValue must be a string");return{id:es(a.id,"a requirement id"),kind:i,settingUniqueName:es(a.settingUniqueName,"a requirement setting"),expectedValue:a.expectedValue,requiredBefore:o(a.requiredBefore,["import","completion"])}}if(i==="roleAssignment"){let a=ki(e,["id","kind","role","principal","requiredBefore"],[],"a requirement"),s=Hg(a.principal)?a.principal:{},u;if(s.kind==="user")ki(s,["kind","aadObjectId"],[],"a principal"),u={kind:"user",aadObjectId:(t=(0,ze.canonicalGuid)(s.aadObjectId))!==null&&t!==void 0?t:gA("a principal id")};else if(s.kind==="groupTeam")ki(s,["kind","aadGroupObjectId"],[],"a principal"),u={kind:"groupTeam",aadGroupObjectId:(n=(0,ze.canonicalGuid)(s.aadGroupObjectId))!==null&&n!==void 0?n:gA("a principal id")};else if(s.kind==="targetTeam")ki(s,["kind","teamId"],[],"a principal"),u={kind:"targetTeam",teamId:(r=(0,ze.canonicalGuid)(s.teamId))!==null&&r!==void 0?r:gA("a principal id")};else throw un("a requirement principal is not a user, group team or target team");return{id:es(a.id,"a requirement id"),kind:i,role:Fre(a.role),principal:u,requiredBefore:o(a.requiredBefore,["completion"])}}if(i==="manual"){let a=ki(e,["id","kind","desiredState","requiredBefore"],[],"a requirement");return{id:es(a.id,"a requirement id"),kind:i,desiredState:es(a.desiredState,"a manual requirement desiredState"),requiredBefore:o(a.requiredBefore,["import","completion"])}}throw un("a requirement kind is not supported")}function gA(e){throw un(`${e} is not a GUID`)}function qre(e){var t,n,r;if(!Hg(e))throw un("the input must be an object");let i=GL(e.codec);for(let l of Object.keys(e))if(xre.has(l))throw(0,ze.promotionError)("PROMOTION_UPGRADE_NOT_SUPPORTED","preflight");if(ki(e,["packageBase64","appUniqueName","values","connections","requirements","overwriteUnmanagedCustomizations","publishWorkflows","codec"],[...Mre],"the input"),typeof e.packageBase64!="string"||e.packageBase64.length===0)throw un("packageBase64 must be a non-empty string");if(e.mode!==void 0&&e.mode!=="managed"&&e.mode!=="unmanaged")throw un("mode must be 'managed' or 'unmanaged'");let o=zg(Wg(e.values,"values").map(l=>{let c=ki(l,["schemaName","value"],[],"a value");if(typeof c.value!="string")throw un("a value must be a string");return{schemaName:es(c.schemaName,"a value schemaName"),value:c.value}}),l=>l.schemaName,"values"),a=zg(Wg(e.connections,"connections").map(l=>{let c=ki(l,["logicalName","connectionId"],[],"a connection");if(typeof c.connectionId!="string"||c.connectionId.trim()!==c.connectionId)throw un("a connectionId must be a string without surrounding whitespace");return{logicalName:es(c.logicalName,"a connection logicalName"),connectionId:c.connectionId}}),l=>l.logicalName,"connections"),s=zg(e.settingOverrides===void 0?[]:Wg(e.settingOverrides,"settingOverrides").map(l=>{let c=ki(l,["settingUniqueName","value"],[],"a setting override");if(typeof c.value!="string")throw un("a setting override value must be a string");return{settingUniqueName:es(c.settingUniqueName,"a setting name"),value:c.value}}),l=>l.settingUniqueName,"settingOverrides"),u=zg(Wg(e.requirements,"requirements").map(Ure),l=>l.id,"requirements");return{codec:i,packageBase64:e.packageBase64,limits:jL(e.limits),intent:{appUniqueName:es(e.appUniqueName,"appUniqueName"),mode:(t=e.mode)!==null&&t!==void 0?t:"managed",values:o,connections:a,settingOverrides:s,requirements:u,overwriteUnmanagedCustomizations:jg(e.overwriteUnmanagedCustomizations,"overwriteUnmanagedCustomizations",!1),publishWorkflows:jg(e.publishWorkflows,"publishWorkflows",!1),acknowledgeNonAtomicImport:(n=jg(e.acknowledgeNonAtomicImport,"acknowledgeNonAtomicImport",!0))!==null&&n!==void 0?n:!1,publishApp:(r=jg(e.publishApp,"publishApp",!0))!==null&&r!==void 0?r:!1}}}we.readPlanInput=qre;var Bre=(e,t)=>e.roles.some(n=>n.id===t)?{kind:"role",identity:{scheme:"package",packageRoleId:t},businessUnit:"root"}:{kind:"role",identity:{scheme:"template",templateId:t},businessUnit:"root"};we.roleIdentity=Bre;var Vre=/^\/subscriptions\/[0-9a-fA-F-]{36}\/resourceGroups\/[^/]+\/providers\/Microsoft\.KeyVault\/vaults\/[^/]+\/secrets\/[^/]+$/;async function Gre(e,t,n,r,i){var o,a,s,u,l,c,d;let f=[...i.findings],p=[],m={kind:"solution",uniqueName:e.solutionUniqueName},h=v=>p.push(v);t.mode==="managed"!==e.managed?f.push((0,we.refusal)("PROMOTION_PACKAGE_MODE_MISMATCH",{subject:m})):t.mode==="unmanaged"&&!n.unmanagedImport&&f.push((0,we.refusal)("PROMOTION_VERIFICATION_UNAVAILABLE",{subject:m,reason:"unmanaged import is not certified"})),t.acknowledgeNonAtomicImport!==!0&&f.push((0,we.refusal)("PROMOTION_NON_ATOMIC_IMPORT_NOT_ACKNOWLEDGED",{subject:m})),t.publishWorkflows&&f.push((0,we.refusal)("PROMOTION_VERIFICATION_UNAVAILABLE",{subject:m,reason:"no certified process activation reader"}));let g=e.apps.find(v=>v.uniqueName.toLowerCase()===t.appUniqueName.toLowerCase()),y={kind:"app",uniqueName:(o=g?.uniqueName)!==null&&o!==void 0?o:t.appUniqueName};g||f.push((0,we.refusal)("PROMOTION_APP_NOT_IN_PACKAGE",{subject:y})),t.publishApp&&f.push((0,we.refusal)("PROMOTION_PUBLICATION_SCOPE_UNKNOWN",{subject:y}));for(let v of t.settingOverrides){let N={kind:"appSetting",appUniqueName:y.uniqueName,settingUniqueName:v.settingUniqueName};f.push((0,we.refusal)("PROMOTION_VERIFICATION_UNAVAILABLE",{subject:N,reason:"app setting overrides are not certified"})),t.publishApp||f.push((0,we.refusal)("PROMOTION_PUBLISH_REQUIRED",{subject:N}))}let b=new Set(((a=g?.sitemapNames)!==null&&a!==void 0?a:[]).map(v=>v.toLowerCase())),E={sitemaps:b,roles:new Set((s=g?.roleIds)!==null&&s!==void 0?s:[]),icon:(u=g?.iconWebResourceId)!==null&&u!==void 0?u:null,webResources:new Set(e.sitemaps.filter(v=>b.has(v.uniqueName.toLowerCase())).flatMap(v=>v.webResources.map(N=>N.toLowerCase())))},w=v=>v?"namedApp":"packageExtra";h({coverageId:"C32",subject:m,relevance:"namedApp",delivery:"solution",complete:!0,checks:[{subject:m,aspect:"definition",expected:{version:e.version,managed:e.managed,publisherUniqueName:e.publisherUniqueName,fields:e.solutionFields},verifierVersion:"solution-v2"}]});let _={kind:"publisher",uniqueName:e.publisherUniqueName};h({coverageId:"C32",subject:_,relevance:"dependency",delivery:"solution",complete:!0,checks:[{subject:_,aspect:"presence",expected:{prefix:e.publisherPrefix,fields:e.publisherFields},verifierVersion:"publisher-v2"}]}),t.publishWorkflows||h({coverageId:"C28",subject:m,relevance:"namedApp",delivery:"solution",complete:!0,checks:[{subject:m,aspect:"activation",expected:{policy:"noActivationRequest"},verifierVersion:"activation-trace-v1"}]});for(let v of e.apps){let N={kind:"app",uniqueName:v.uniqueName},S=v===g,R=v.iconWebResourceId?e.webResources.find(G=>G.id===v.iconWebResourceId):void 0,x=v.sitemapNames.some(G=>!e.sitemaps.some(U=>U.uniqueName.toLowerCase()===G.toLowerCase()));(x||v.iconWebResourceId&&!R)&&f.push((0,we.refusal)("PROMOTION_COVERAGE_GAP",{subject:N,reason:"an app reference is not in the package"})),h({coverageId:"C01",subject:N,relevance:w(S),delivery:x||v.iconWebResourceId&&!R?"refused":"solution",complete:!(x||v.iconWebResourceId&&!R),checks:[{subject:N,aspect:"definition",expected:{icon:R?R.name:null,fields:v.fields},verifierVersion:"app-v2"},{subject:N,aspect:"references",expected:{sitemaps:v.sitemapNames,otherComponents:0},verifierVersion:"app-components-v1"}]}),h({coverageId:"C23",subject:N,relevance:w(S),delivery:"solution",complete:!0,checks:[{subject:N,aspect:"references",expected:{roles:v.roleIds.map(G=>(0,ze.identityKey)((0,we.roleIdentity)(e,G))).sort(ze.byCodeUnit)},verifierVersion:"app-roles-v1"}]});for(let G of v.roleIds.filter(U=>!e.roles.some(M=>M.id===U))){let U=(0,we.roleIdentity)(e,G);h({coverageId:"C23",subject:U,relevance:"dependency",delivery:"existingTarget",complete:!0,checks:[{subject:U,aspect:"presence",expected:{present:!0},verifierVersion:"template-role-v1"}]})}for(let G of v.settings){let U={kind:"appSetting",appUniqueName:v.uniqueName,settingUniqueName:G.definition};if(kre(G)){f.push((0,we.refusal)("PROMOTION_COVERAGE_GAP",{subject:U,reason:"a theme pointer is not certified"})),h({coverageId:"C16",subject:U,relevance:w(S),delivery:"refused",complete:!1,checks:[]});continue}h({coverageId:"C03",subject:U,relevance:w(S),delivery:"solution",complete:!0,checks:[{subject:U,aspect:"setting",expected:{value:G.value,fields:G.fields},verifierVersion:"app-setting-v2"}]});let M={kind:"settingDefinition",uniqueName:G.definition};p.some(q=>q.coverageId==="C05"&&(0,ze.identityKey)(q.subject)===(0,ze.identityKey)(M))||h({coverageId:"C05",subject:M,relevance:"dependency",delivery:"existingTarget",complete:!0,checks:[{subject:M,aspect:"presence",expected:{present:!0},verifierVersion:"setting-definition-v1"}]})}}let I=(v,N,S)=>({coverageId:v,subject:N,relevance:"dependency",delivery:"existingTarget",complete:!0,checks:[{subject:N,aspect:"presence",expected:{present:!0},verifierVersion:S}]}),T=(v,N)=>p.some(S=>S.coverageId===v&&(0,ze.identityKey)(S.subject)===(0,ze.identityKey)(N));for(let v of e.sitemaps){let N={kind:"sitemap",uniqueName:v.uniqueName};h({coverageId:"C02",subject:N,relevance:w(E.sitemaps.has(v.uniqueName.toLowerCase())),delivery:"solution",complete:!0,checks:[{subject:N,aspect:"definition",expected:{canonicalDigest:await(0,ze.digestOf)(r,v.canonicalXml),fields:v.fields},verifierVersion:"sitemap-v2"}]});for(let S of v.webResources){let R={kind:"webResource",name:S};!e.webResources.some(x=>x.name.toLowerCase()===S.toLowerCase())&&!T("C15",R)&&h(I("C15",R,"web-resource-presence-v1"))}for(let S of v.tables){let R={kind:"table",logicalName:S};T("C32",R)||h(I("C32",R,"table-presence-v1"))}}for(let v of e.webResources){let N={kind:"webResource",name:v.name};h({coverageId:"C15",subject:N,relevance:w(E.icon===v.id||E.webResources.has(v.name.toLowerCase())),delivery:"solution",complete:!0,checks:[{subject:N,aspect:"bytes",expected:{sha256:await(0,ze.sha256Of)(r,v.bytes),type:v.type,fields:v.fields},verifierVersion:"web-resource-v2"}]})}for(let v of e.searches){if(!e.apps.some(S=>S.uniqueName.toLowerCase()===v.appUniqueName.toLowerCase()))continue;let N={kind:"appSearch",packageId:v.id,appUniqueName:v.appUniqueName};h({coverageId:"C31",subject:N,relevance:w(v.appUniqueName.toLowerCase()===g?.uniqueName.toLowerCase()),delivery:"solution",complete:!0,checks:[{subject:N,aspect:"definition",expected:{fields:v.fields,member:!0},verifierVersion:"app-search-v2"}]})}for(let v of t.values)e.variables.some(N=>N.schemaName.toLowerCase()===v.schemaName.toLowerCase())||f.push((0,we.refusal)("INVALID_ARGUMENT",{subject:{kind:"environmentVariable",schemaName:v.schemaName},reason:"not a variable of the package"}));for(let v of e.variables){let N={kind:"environmentVariable",schemaName:v.schemaName},S=t.values.find(U=>U.schemaName.toLowerCase()===v.schemaName.toLowerCase()),R=v.type===Dre.SECRET_TYPE,x=!1;R&&(v.hasCurrentValue||((l=v.defaultValue)!==null&&l!==void 0?l:"")!=="")&&(f.push((0,we.refusal)("PROMOTION_SECRET_VALUE",{subject:N})),x=!0);let G=v.isRequired||v.hasCurrentValue;if(G&&(!S||S.value==="")?(f.push((0,we.refusal)("PROMOTION_VALUE_REQUIRED",{subject:N})),x=!0):!G&&S&&S.value===""&&(f.push((0,we.refusal)("INVALID_ARGUMENT",{subject:N,reason:"an empty value is not a clear"})),x=!0),R&&S&&S.value!=="")Vre.test(S.value)?n.secretReferences||(f.push((0,we.refusal)("PROMOTION_VERIFICATION_UNAVAILABLE",{subject:N,reason:"Key Vault reference parameters are not certified"})),x=!0):(f.push((0,we.refusal)("PROMOTION_SECRET_VALUE",{subject:N,reason:"a Secret input must be a Key Vault reference"})),x=!0);else if(S&&S.value!==""){let U=BL.ENVIRONMENT_VARIABLE_TYPES[v.type-1e8];(0,BL.valueTypeProblem)(U,S.value)!==void 0&&(f.push((0,we.refusal)("INVALID_ARGUMENT",{subject:N,reason:`the value is not a valid ${U} value`})),x=!0)}h({coverageId:"C19",subject:N,relevance:"packageExtra",delivery:"solution",complete:!0,checks:[{subject:N,aspect:"definition",expected:{type:v.type,isRequired:v.isRequired,defaultValueDigest:await(0,ze.digestOf)(r,v.defaultValue),fields:v.fields},verifierVersion:"variable-v2"}]}),S&&S.value!==""&&h({coverageId:"C20",subject:N,relevance:"packageExtra",delivery:x?"refused":"parameter",complete:!x,checks:[{subject:N,aspect:"setting",expected:{valueDigest:await(0,ze.digestOf)(r,S.value)},verifierVersion:"variable-value-v1"}]})}for(let v of t.connections)e.references.some(N=>N.logicalName.toLowerCase()===v.logicalName.toLowerCase())||f.push((0,we.refusal)("INVALID_ARGUMENT",{subject:{kind:"connectionReference",logicalName:v.logicalName},reason:"not a connection reference of the package"}));for(let v of e.references){let N={kind:"connectionReference",logicalName:v.logicalName},S=t.connections.find(x=>x.logicalName.toLowerCase()===v.logicalName.toLowerCase()),R=!S||S.connectionId==="";R&&f.push((0,we.refusal)("PROMOTION_CONNECTION_UNMAPPED",{subject:N})),n.connectionReferences||f.push((0,we.refusal)("PROMOTION_VERIFICATION_UNAVAILABLE",{subject:N,reason:"bound connection references are not certified"})),h({coverageId:"C21",subject:N,relevance:"packageExtra",delivery:R?"refused":"parameter",complete:!R&&n.connectionReferences,checks:R?[]:[{subject:N,aspect:"references",expected:{connectorId:v.connectorId.toLowerCase(),connectionId:S.connectionId,fields:v.fields},verifierVersion:"connection-reference-v2"}]})}for(let v of e.roles){if(i.refusedRoles.has(v.id)){h({coverageId:"C22",subject:{kind:"unsupportedComponent",componentType:20,packageId:v.id},relevance:w(E.roles.has(v.id)),delivery:"refused",complete:!1,checks:[]});continue}let N=(0,we.roleIdentity)(e,v.id);h({coverageId:"C22",subject:N,relevance:w(E.roles.has(v.id)),delivery:"solution",complete:!0,checks:[{subject:N,aspect:"presence",expected:{businessUnit:"root",name:v.name,fields:v.fields},verifierVersion:"role-v2"},{subject:N,aspect:"privileges",expected:{privileges:v.privileges},verifierVersion:"role-privileges-v1"}]})}for(let v of e.dependencies){if(v.type==="SettingDefinition"&&v.uniqueName){let R={kind:"settingDefinition",uniqueName:v.uniqueName};T("C05",R)||h(I("C05",R,"setting-definition-v1"));continue}let N=v.type==="EnvironmentVariableDefinition"&&v.schemaName,S=N?{kind:"environmentVariable",schemaName:v.schemaName}:{kind:"unsupportedComponent",componentType:0,packageId:(d=(c=v.schemaName)!==null&&c!==void 0?c:v.uniqueName)!==null&&d!==void 0?d:v.id};N||f.push((0,we.refusal)("PROMOTION_DEPENDENCY_IDENTITY_UNRESOLVED",{subject:S})),h({coverageId:"C32",subject:S,relevance:"dependency",delivery:N?"existingTarget":"refused",complete:!!N,checks:N?[{subject:S,aspect:"presence",expected:{present:!0},verifierVersion:"dependency-v1"}]:[]})}for(let v of e.gaps)f.push((0,we.refusal)("PROMOTION_COVERAGE_GAP",{subject:v.subject,reason:v.reason})),h({coverageId:"C42",subject:v.subject,relevance:"packageExtra",delivery:"refused",complete:!1,checks:[]});let O=[];for(let v of t.requirements){let N={kind:"requirement",requirementId:v.id};v.requiredBefore==="import"&&f.push((0,we.refusal)("PROMOTION_VERIFICATION_UNAVAILABLE",{reason:"no certified reader for a before-import requirement"}));let S=v.kind==="roleAssignment"?"assignment":v.kind==="organizationSetting"?"setting":"manual",R=v.kind==="roleAssignment"?{role:(0,ze.identityKey)(v.role),principal:(0,ze.identityKey)(v.principal)}:v.kind==="organizationSetting"?{settingUniqueName:v.settingUniqueName,expectedValue:v.expectedValue}:{desiredState:v.desiredState},x={subject:N,aspect:S,expected:R,verifierVersion:"requirement-manual-v1"};h({coverageId:v.kind==="roleAssignment"?"C33":"C34",subject:N,relevance:"callerRequirement",delivery:"manual",complete:v.requiredBefore!=="import",checks:[x]}),O.push({requirementId:v.id,checks:[x]})}return{...jre(p,O),findings:f}}we.buildRecipe=Gre;function jre(e,t){let n=[...e].sort((s,u)=>(0,ze.byCodeUnit)(s.coverageId,u.coverageId)||(0,ze.byCodeUnit)((0,ze.identityKey)(s.subject),(0,ze.identityKey)(u.subject))),r=[],i=new Map,o=n.map((s,u)=>{let l=[...s.checks].sort((c,d)=>(0,ze.byCodeUnit)((0,ze.identityKey)(c.subject),(0,ze.identityKey)(d.subject))||(0,ze.byCodeUnit)(c.aspect,d.aspect)).map(c=>{let d=`chk-${r.length+1}`;return i.set(c,d),r.push({id:d,coverageId:s.coverageId,subject:c.subject,aspect:c.aspect,expected:c.expected,required:!0,verifierVersion:c.verifierVersion}),d});return{id:`cov-${u+1}`,coverageId:s.coverageId,subject:s.subject,relevance:s.relevance,delivery:s.delivery,required:!0,checks:l,complete:s.complete}}),a=t.sort((s,u)=>(0,ze.byCodeUnit)(s.requirementId,u.requirementId)).map((s,u)=>({id:`step-${u+1}`,kind:"manual",requirementId:s.requirementId,required:!0,checkIds:s.checks.map(l=>i.get(l))}));return{coverage:o,checks:r,steps:a}}});var bA=C(or=>{"use strict";Object.defineProperty(or,"__esModule",{value:!0});or.verifyChecks=or.readStageAnswer=or.UNREADABLE_STAGE=or.sameObservations=or.observeTarget=or.correspondSource=or.judgeSource=void 0;var yA=Y(),Ue=Kg(),sa=Pg(),Ae=Ya(),Jg="promotion-target-v2",sl={app:"AppModule",sitemap:"SiteMap",webResource:"WebResource",variable:"EnvironmentVariableDefinition",reference:"connectionreference",role:"Role",search:"DVTableSearch"},Wre={61:["webresourceset","name",(e,t)=>e.webResources.some(n=>n.name===t)],62:["sitemaps","sitemapnameunique",(e,t)=>e.sitemaps.some(n=>n.uniqueName===t)],80:["appmodules","uniquename",(e,t)=>e.apps.some(n=>n.uniqueName===t)],380:["environmentvariabledefinitions","schemaname",(e,t)=>e.variables.some(n=>n.schemaName===t)]},zre=381;async function Hre(e,t){let n=[],r=new Set,i={kind:"solution",uniqueName:e.solutionUniqueName},o=l=>n.push((0,Ue.refusal)("PROMOTION_SOURCE_PACKAGE_MISMATCH",{subject:i,reason:l})),a=await t.solution(e.solutionUniqueName);if(a.state==="unreadable")n.push((0,Ue.unknown)({subject:i,reason:"the source solution could not be read"}));else if(a.state==="absent")o("no such source solution");else{let l=a.value,c=(0,Ae.parseVersion)(l.version);l.publisherUniqueName.toLowerCase()!==e.publisherUniqueName.toLowerCase()&&o("another publisher"),(!c||(0,Ae.compareVersions)(c,(0,Ae.parseVersion)(e.version))!==0)&&o("another version");let d=await t.members(l.id);if(!d)n.push((0,Ue.unknown)({subject:i,reason:"the source solution members could not be read"}));else for(let f of[...d].sort((p,m)=>(0,Ae.byCodeUnit)(p.id,m.id)))await Kre(e,t,f,n,o)}let s=await t.rootBusinessUnit();for(let l of e.roles){let c=await t.role(l.id);(!s||c.state!=="present"||c.value.businessUnitId!==s)&&(r.add(l.id),n.push((0,Ue.refusal)("PROMOTION_COVERAGE_GAP",{subject:{kind:"unsupportedComponent",componentType:20,packageId:l.id},reason:"the role is not provably a root business unit role"})))}let u=new Set;for(let l of e.apps)for(let c of l.roleIds)e.roles.some(d=>d.id===c)||u.add(c);for(let l of[...u].sort(Ae.byCodeUnit)){let c=await t.templateRole(l);c.state==="unreadable"?n.push((0,Ue.unknown)({subject:(0,Ue.roleIdentity)(e,l),reason:"a source template role could not be read"})):c.state==="absent"&&n.push((0,Ue.refusal)("PROMOTION_DEPENDENCY_IDENTITY_UNRESOLVED",{subject:(0,Ue.roleIdentity)(e,l)}))}return{refusedRoles:r,findings:n}}or.judgeSource=Hre;async function Kre(e,t,n,r,i){let o={kind:"solution",uniqueName:e.solutionUniqueName},a=()=>r.push((0,Ue.unknown)({subject:o,reason:"a source member could not be named"}));if(n.type===20){e.roles.some(f=>f.id===n.id)||i("a source role member is not in the package");return}if(n.type===zre)return;let s=Wre[n.type];if(s){let f=await t.fieldById(s[0],n.id,s[1]);f.state==="unreadable"?a():(f.state==="absent"||!s[2](e,f.value))&&i("a source member is not in the package");return}let[u,l,c]=[await t.componentType("connectionreference"),await t.componentType("appsetting"),await t.componentType("dvtablesearch")],d=f=>f.state==="present"&&f.value===n.type;if(d(u)){let f=await t.fieldById("connectionreferences",n.id,"connectionreferencelogicalname");f.state==="unreadable"?a():(f.state==="absent"||!e.references.some(p=>p.logicalName===f.value))&&i("a source member is not in the package");return}if(d(l)){let f=await t.byId("appsettings",n.id,"_parentappmoduleid_value,_settingdefinitionid_value"),p=f.state==="present"?(0,Ae.canonicalGuid)(f.value._parentappmoduleid_value):void 0,m=f.state==="present"?(0,Ae.canonicalGuid)(f.value._settingdefinitionid_value):void 0,h=p?await t.fieldById("appmodules",p,"uniquename"):void 0,g=m?await t.fieldById("settingdefinitions",m,"uniquename"):void 0;f.state==="absent"?i("a source member is not in the package"):h?.state!=="present"||g?.state!=="present"?a():e.apps.some(y=>y.uniqueName===h.value&&y.settings.some(b=>b.definition===g.value))||i("a source member is not in the package");return}if(d(c)){e.searches.some(f=>f.id===n.id)||i("a source member is not in the package");return}if([u,l,c].some(f=>f.state==="unreadable")){a();return}r.push((0,Ue.refusal)("PROMOTION_COVERAGE_GAP",{subject:{kind:"unsupportedComponent",componentType:n.type,packageId:n.id},reason:"a source member of a kind without a certified provider"}))}async function Jre(e,t,n,r){let i=[],o=(a,s)=>{let u={...s};return a.subject.kind==="solution"&&delete u.managed,a.subject.kind==="connectionReference"&&delete u.connectionId,u};for(let a of e){let s=a.expected;if(a.subject.kind==="requirement"||a.aspect==="activation"||a.coverageId==="C20"||a.aspect==="presence"&&s?.present===!0)continue;let u=a.subject,l;try{l=await WL(a,t,n,r)}catch(c){if(c instanceof yA.PromotionError&&c.code==="PROMOTION_READ_BUDGET_EXCEEDED")throw c;l=void 0}l===void 0?i.push((0,Ue.unknown)({subject:u,reason:"the source could not be read"})):(0,Ae.canonicalJson)(o(a,l))!==(0,Ae.canonicalJson)(o(a,s))&&i.push((0,Ue.refusal)("PROMOTION_SOURCE_PACKAGE_MISMATCH",{subject:u,reason:"the source differs from its package"}))}return i}or.correspondSource=Jre;async function Yre(e,t,n,r,i,o){let a=[],s=[],u={kind:"solution",uniqueName:e.solutionUniqueName},l={state:"unreadable",reasonCode:"PROMOTION_VERIFICATION_UNAVAILABLE"},c=await n.solution(e.solutionUniqueName),d="undetermined",f,p=!1;if(c.state==="unreadable")a.push((0,Ue.unknown)({subject:u,reason:"the target solution could not be read"})),s.push({subject:u,purpose:"affected",image:l});else if(c.state==="absent")d="install",s.push({subject:u,purpose:"affected",image:{state:"absent"}});else{let v=c.value,N=await n.patches(v.id);N?N.length>0&&(a.push((0,Ue.refusal)("PROMOTION_HOLDING_PRESENT",{subject:u,reason:"the solution has patches"})),p=!0):a.push((0,Ue.unknown)({subject:u,reason:"patches could not be read"})),v.publisherUniqueName.toLowerCase()!==e.publisherUniqueName.toLowerCase()&&(a.push((0,Ue.refusal)("PROMOTION_PUBLISHER_MISMATCH",{subject:u})),p=!0),v.managed!==e.managed&&(a.push((0,Ue.refusal)("PROMOTION_TARGET_MODE_MISMATCH",{subject:u})),p=!0);let S=(0,Ae.parseVersion)(v.version);(!S||(0,Ae.compareVersions)((0,Ae.parseVersion)(e.version),S)<=0)&&(a.push((0,Ue.refusal)("PROMOTION_VERSION_REFUSED",{subject:u})),p=!0);let R=await n.members(v.id);f=R?new Set(R.map(x=>x.id)):void 0,R||a.push((0,Ue.unknown)({subject:u,reason:"the target solution members could not be read"})),d=p?"undetermined":"update",s.push({subject:u,purpose:"affected",image:{state:"present",projectionVersion:Jg,contentDigest:await(0,Ae.digestOf)(r,{version:v.version,managed:v.managed,publisher:v.publisherUniqueName.toLowerCase(),prefix:v.publisherPrefix,fields:v.fields,publisherFields:v.publisherFields,patches:N??null,members:R?R.map(x=>`${x.type}:${x.id}`).sort(Ae.byCodeUnit):null}),layerDigest:null,versions:[{entitySet:"solutions",id:v.id,etag:v.etag}]}})}let m=`${e.solutionUniqueName}_Upgrade`,h=await n.solution(m),g={kind:"solution",uniqueName:m};h.state==="unreadable"?(a.push((0,Ue.unknown)({subject:g,reason:"the holding solution could not be read"})),s.push({subject:g,purpose:"affected",image:l})):(h.state==="present"&&(a.push((0,Ue.refusal)("PROMOTION_HOLDING_PRESENT",{subject:g})),d="undetermined"),s.push({subject:g,purpose:"affected",image:h.state==="absent"?{state:"absent"}:{state:"present",projectionVersion:Jg,contentDigest:await(0,Ae.digestOf)(r,{version:h.value.version}),layerDigest:null,versions:[{entitySet:"solutions",id:h.value.id,etag:h.value.etag}]}}));let y=async(v,N,S)=>{if(S.state==="unreadable"){a.push((0,Ue.unknown)({subject:v,reason:"a target component could not be read"})),s.push({subject:v,purpose:"affected",image:l});return}if(S.state==="absent"){s.push({subject:v,purpose:"affected",image:{state:"absent"}});return}let R=null;if(c.state==="absent")a.push((0,Ue.refusal)("PROMOTION_COMPONENT_COLLISION",{subject:v}));else if(c.state==="present"){f&&!f.has(S.value.id)&&a.push((0,Ue.refusal)("PROMOTION_COMPONENT_COLLISION",{subject:v,reason:"not a component of the target solution"}));let x=await n.topLayer(N,S.value.id);x.state!=="present"?a.push((0,Ue.unknown)({subject:v,reason:"its solution layers could not be read"})):(R=x.value.digest,x.value.top.toLowerCase()!==e.solutionUniqueName.toLowerCase()&&a.push((0,Ue.refusal)("PROMOTION_COMPONENT_COLLISION",{subject:v,reason:"another layer is on top"})))}s.push({subject:v,purpose:"affected",image:{state:"present",projectionVersion:Jg,contentDigest:await(0,Ae.digestOf)(r,S.value.digestInput),layerDigest:R,versions:S.value.versions}})},b=(v,N)=>v.state==="present"?{state:"present",value:N(v.value)}:v;for(let v of e.apps){let N=await n.app(v.uniqueName,!0);await y({kind:"app",uniqueName:v.uniqueName},sl.app,b(N,S=>({id:S.id,digestInput:{...S,etag:void 0,settings:S.settings.map(R=>[R.definition,R.value,R.fields])},versions:[{entitySet:"appmodules",id:S.id,etag:S.etag},...S.settings.map(R=>({entitySet:"appsettings",id:R.id,etag:R.etag}))]})))}for(let v of e.sitemaps){let N=await n.sitemap(v.uniqueName,!0);await y({kind:"sitemap",uniqueName:v.uniqueName},sl.sitemap,b(N,S=>({id:S.id,digestInput:{canonical:S.canonical,fields:S.fields},versions:[{entitySet:"sitemaps",id:S.id,etag:S.etag}]})))}for(let v of e.webResources){let N=await n.webResource(v.name);await y({kind:"webResource",name:v.name},sl.webResource,b(N,S=>({id:S.id,digestInput:{type:S.type,sha256:S.sha256,fields:S.fields},versions:[{entitySet:"webresourceset",id:S.id,etag:S.etag}]})))}for(let v of e.variables){let N=await n.variable(v.schemaName);await y({kind:"environmentVariable",schemaName:v.schemaName},sl.variable,b(N,S=>({id:S.id,digestInput:{type:S.type,isRequired:S.isRequired,defaultValue:S.defaultValue,fields:S.fields,values:S.values},versions:[{entitySet:"environmentvariabledefinitions",id:S.id,etag:S.etag},...S.values.map(R=>({entitySet:"environmentvariablevalues",id:R.id,etag:R.etag}))]})))}for(let v of e.references){let N=await n.reference(v.logicalName);await y({kind:"connectionReference",logicalName:v.logicalName},sl.reference,b(N,S=>({id:S.id,digestInput:{connectorId:S.connectorId,connectionId:S.connectionId,fields:S.fields},versions:[{entitySet:"connectionreferences",id:S.id,etag:S.etag}]})))}for(let v of e.roles){let N=await n.role(v.id),S=N.state==="present"?{state:"unreadable"}:N;if(N.state==="present"){let R=await n.rolePrivileges(v.id),x=N.value;S=R?{state:"present",value:{id:x.id,digestInput:{businessUnitId:x.businessUnitId,templateId:x.templateId,name:x.name,fields:x.fields,privileges:R},versions:[{entitySet:"roles",id:x.id,etag:x.etag}]}}:{state:"unreadable"}}await y((0,Ue.roleIdentity)(e,v.id),sl.role,S)}for(let v of e.searches){let N=await n.search(v.id);await y({kind:"appSearch",packageId:v.id,appUniqueName:v.appUniqueName},sl.search,b(N,S=>({id:S.id,digestInput:{fields:S.fields},versions:[{entitySet:"dvtablesearchs",id:S.id,etag:S.etag}]})))}let E=async(v,N,S)=>{if(N.state==="unreadable"){a.push((0,Ue.unknown)({subject:v,reason:"a prerequisite could not be read"})),s.push({subject:v,purpose:"dependency",image:l});return}if(N.state==="absent"){a.push((0,Ue.refusal)(S,{subject:v})),s.push({subject:v,purpose:"dependency",image:{state:"absent"}});return}s.push({subject:v,purpose:"dependency",image:{state:"present",projectionVersion:Jg,contentDigest:await(0,Ae.digestOf)(r,N.value),layerDigest:null,versions:[]}})},w=new Set,_=new Set;for(let v of e.apps)v.roleIds.filter(N=>!e.roles.some(S=>S.id===N)).forEach(N=>w.add(N)),v.settings.forEach(N=>_.add(N.definition));for(let v of e.dependencies)v.type==="SettingDefinition"&&v.uniqueName&&_.add(v.uniqueName);for(let v of[...w].sort(Ae.byCodeUnit))await E((0,Ue.roleIdentity)(e,v),await n.templateRole(v),"PROMOTION_DEPENDENCY_MISSING");for(let v of[..._].sort(Ae.byCodeUnit))await E({kind:"settingDefinition",uniqueName:v},await n.settingDefinition(v),"PROMOTION_SETTING_UNAVAILABLE");for(let v of e.dependencies){if(v.type!=="EnvironmentVariableDefinition"||!v.schemaName)continue;let N=e.variables.some(S=>{var R;return S.schemaName.toLowerCase()===((R=v.schemaName)===null||R===void 0?void 0:R.toLowerCase())});await E({kind:"environmentVariable",schemaName:v.schemaName},N?{state:"present",value:"package"}:await n.variableExists(v.schemaName),"PROMOTION_DEPENDENCY_MISSING")}let I=new Set,T=new Set;for(let v of e.sitemaps)v.webResources.filter(N=>!e.webResources.some(S=>S.name.toLowerCase()===N.toLowerCase())).forEach(N=>I.add(N)),v.tables.forEach(N=>T.add(N));for(let v of[...I].sort(Ae.byCodeUnit)){let N=await n.webResource(v);await E({kind:"webResource",name:v},N.state==="present"?{state:"present",value:{present:!0}}:N,"PROMOTION_DEPENDENCY_MISSING")}for(let v of[...T].sort(Ae.byCodeUnit))await E({kind:"table",logicalName:v},await n.tableExists(v),"PROMOTION_DEPENDENCY_MISSING");if(i){let v=e.references.map(N=>({reference:N,map:t.connections.find(S=>S.logicalName.toLowerCase()===N.logicalName.toLowerCase())})).filter(N=>N.map&&N.map.connectionId!=="");if(v.length>0){let N;try{N=o?await o():void 0}catch(S){if(S instanceof yA.PromotionError&&S.code==="PROMOTION_READ_BUDGET_EXCEEDED")throw S;N=void 0}for(let{reference:S,map:R}of v){let x={kind:"connectionReference",logicalName:S.logicalName},G=N?.find(U=>U.connectionId===R?.connectionId);N?G?G.connectorId.toLowerCase()!==S.connectorId.toLowerCase()&&a.push((0,Ue.refusal)("PROMOTION_CONNECTION_CONNECTOR_MISMATCH",{subject:x})):a.push((0,Ue.refusal)("PROMOTION_CONNECTION_NOT_IN_TARGET",{subject:x})):a.push((0,Ue.unknown)({subject:x,reason:"the target connections could not be read"}))}}}return{observations:s.sort((v,N)=>(0,Ae.byCodeUnit)(v.purpose,N.purpose)||(0,Ae.byCodeUnit)((0,Ae.identityKey)(v.subject),(0,Ae.identityKey)(N.subject))).map((v,N)=>({id:`obs-${N+1}`,subject:v.subject,purpose:v.purpose,image:v.image})),importKind:d,findings:a,solution:c}}or.observeTarget=Yre;function Qre(e,t){return(0,Ae.canonicalJson)(e)===(0,Ae.canonicalJson)(t)}or.sameObservations=Qre;or.UNREADABLE_STAGE={status:"unreadable",missing:0,validationErrors:0,apps:[],webResources:[],variables:[],references:[]};function Xre(e){var t;let n=or.UNREADABLE_STAGE,r=e?.StageSolutionResults;if(!r||typeof r!="object")return n;let i=r.StageSolutionStatus,o=(0,Ae.canonicalGuid)(r.StageSolutionUploadId),a=Array.isArray(r.MissingDependencies)?r.MissingDependencies.length:-1,s=Array.isArray(r.SolutionValidationResults)?r.SolutionValidationResults:void 0;if(a<0||!s)return n;let u=s.filter(h=>h?.SolutionValidationResultType==="Error").length;if(i==="Failed"||i===0)return{...n,status:"Failed",...o?{uploadId:o}:{},missing:a,validationErrors:u};if(i!=="Passed"&&i!==1||!o||!Array.isArray(r.SolutionComponentsDetails))return n;let l=[],c=[],d=[],f=[];for(let h of r.SolutionComponentsDetails){let g=typeof h?.ComponentTypeName=="string"?h.ComponentTypeName.toLowerCase():void 0;if(!g)return n;if(!["appmodule","webresource","environmentvariabledefinition","connectionreference"].includes(g))continue;let y=h.Attributes,b=y?.Keys,E=y?.Values;if(!Array.isArray(b)||!Array.isArray(E)||b.length!==E.length)return n;let w=I=>{let T=E[b.indexOf(I)];return b.includes(I)&&typeof T=="string"?T:null},_=typeof h.ComponentName=="string"?h.ComponentName:null;if(g==="appmodule"){let I=(t=w("uniquename"))!==null&&t!==void 0?t:_;if(!I)return n;l.push(I.toLowerCase())}else if(g==="webresource"){if(!_)return n;c.push(_.toLowerCase())}else if(g==="environmentvariabledefinition"){let I=w("schemaname");if(!I)return n;d.push({schemaName:I.toLowerCase(),type:w("type"),isRequired:w("isrequired"),defaultValue:w("defaultvalue")})}else{let I=w("connectionreferencelogicalname");if(!I)return n;f.push({logicalName:I.toLowerCase(),connectorId:w("connectorid")})}}let p=r.SolutionDetails,m=p&&typeof p=="object"&&typeof p.SolutionUniqueName=="string"&&typeof p.PublisherUniqueName=="string"&&typeof p.IsManaged=="boolean"&&typeof p.SolutionVersion=="string"&&typeof p.IsPatchSolution=="boolean"&&typeof p.HasPendingUpgrade=="boolean"?{solutionName:p.SolutionUniqueName,publisherName:p.PublisherUniqueName,managed:p.IsManaged,version:p.SolutionVersion,patch:p.IsPatchSolution,pendingUpgrade:p.HasPendingUpgrade}:void 0;return{status:"Passed",uploadId:o,missing:a,validationErrors:u,...m?{details:m}:{},apps:l.sort(Ae.byCodeUnit),webResources:c.sort(Ae.byCodeUnit),variables:d.sort((h,g)=>(0,Ae.byCodeUnit)(h.schemaName,g.schemaName)),references:f.sort((h,g)=>(0,Ae.byCodeUnit)(h.logicalName,g.logicalName))}}or.readStageAnswer=Xre;var Zre=e=>{var t,n;return Object.keys((n=(t=e.expected)===null||t===void 0?void 0:t.fields)!==null&&n!==void 0?n:{})};async function WL(e,t,n,r){var i;let o=e.subject,a=Zre(e),s=async()=>n.solution(t.solutionUniqueName);switch(o.kind){case"solution":{let u=await s();return u.state==="unreadable"?void 0:u.state==="absent"?{absent:!0}:{version:u.value.version,managed:u.value.managed,publisherUniqueName:u.value.publisherUniqueName,fields:(0,sa.pickFields)(u.value.fields,a)}}case"publisher":{let u=await s();return u.state==="unreadable"?void 0:u.state==="absent"?{absent:!0}:{prefix:u.value.publisherPrefix,fields:(0,sa.pickFields)(u.value.publisherFields,a)}}case"app":{let u=await n.app(o.uniqueName,!1);if(u.state!=="present")return u.state==="absent"?{absent:!0}:void 0;let l=u.value;if(e.aspect==="definition"){let f=null;if(l.webResourceId){let p=await n.webResourceName(l.webResourceId);if(p.state!=="present")return;f=p.value}return{icon:f,fields:(0,sa.pickFields)(l.fields,a)}}if(e.coverageId==="C23"){let f=await n.rootBusinessUnit(),p=[];for(let m of l.roles){if(t.roles.some(g=>g.id===m)){p.push((0,Ae.identityKey)((0,Ue.roleIdentity)(t,m)));continue}let h=await n.role(m);if(h.state==="unreadable"||!f)return;p.push(h.state==="present"&&h.value.templateId&&h.value.businessUnitId===f?(0,Ae.identityKey)((0,Ue.roleIdentity)(t,h.value.templateId)):`unresolved:${m}`)}return{roles:p.sort(Ae.byCodeUnit)}}let c=[],d=0;for(let f of l.components){let[p,m]=f.split(":");if(p!=="62"){d+=1;continue}let h=await n.fieldById("sitemaps",m,"sitemapnameunique");if(h.state==="unreadable")return;c.push(h.state==="present"?h.value:`missing:${m}`)}return{sitemaps:c.sort(Ae.byCodeUnit),otherComponents:d}}case"appSetting":{let u=await n.app(o.appUniqueName,!1);if(u.state==="unreadable")return;let l=u.state==="present"?u.value.settings.find(c=>c.definition===o.settingUniqueName):void 0;return l?{value:l.value,fields:(0,sa.pickFields)(l.fields,a)}:{value:null}}case"settingDefinition":{let u=await n.settingDefinition(o.uniqueName);return u.state==="unreadable"?void 0:{present:u.state==="present"}}case"table":{let u=await n.tableExists(o.logicalName);return u.state==="unreadable"?void 0:{present:u.state==="present"}}case"sitemap":{let u=await n.sitemap(o.uniqueName,!1);return u.state==="unreadable"?void 0:u.state==="absent"?{absent:!0}:{canonicalDigest:await(0,Ae.digestOf)(r,u.value.canonical),fields:(0,sa.pickFields)(u.value.fields,a)}}case"webResource":{let u=await n.webResource(o.name);return u.state==="unreadable"?void 0:e.aspect==="presence"?{present:u.state==="present"}:u.state==="absent"?{absent:!0}:{sha256:u.value.sha256,type:u.value.type,fields:(0,sa.pickFields)(u.value.fields,a)}}case"environmentVariable":{let u=await n.variable(o.schemaName);return u.state==="unreadable"?void 0:e.aspect==="presence"?{present:u.state==="present"}:u.state==="absent"?{absent:!0}:e.aspect==="setting"?{valueDigest:u.value.values.length===1?u.value.values[0].valueDigest:null}:{type:u.value.type,isRequired:u.value.isRequired,defaultValueDigest:await(0,Ae.digestOf)(r,u.value.defaultValue),fields:(0,sa.pickFields)(u.value.fields,a)}}case"connectionReference":{let u=await n.reference(o.logicalName);return u.state==="unreadable"?void 0:u.state==="absent"?{absent:!0}:{connectorId:((i=u.value.connectorId)!==null&&i!==void 0?i:"").toLowerCase(),connectionId:u.value.connectionId,fields:(0,sa.pickFields)(u.value.fields,a)}}case"role":{if(o.identity.scheme==="template"){let d=await n.templateRole(o.identity.templateId);return d.state==="unreadable"?void 0:{present:d.state==="present"}}let u=o.identity.packageRoleId;if(e.aspect==="privileges"){let d=await n.rolePrivileges(u);return d?{privileges:d}:void 0}let l=await n.role(u),c=await n.rootBusinessUnit();return l.state==="unreadable"||!c?void 0:l.state==="absent"?{absent:!0}:{businessUnit:l.value.businessUnitId===c?"root":"other",name:l.value.name,fields:(0,sa.pickFields)(l.value.fields,a)}}case"appSearch":{let u=await n.search(o.packageId);if(u.state==="unreadable")return;if(u.state==="absent")return{absent:!0};let l=await s(),c=await n.componentType("dvtablesearch"),d=l.state==="present"?await n.members(l.value.id):void 0;if(l.state==="unreadable"||c.state==="unreadable"||l.state==="present"&&!d)return;let f=c.state==="present"&&(d??[]).some(p=>p.id===u.value.id&&p.type===c.value);return{fields:(0,sa.pickFields)(u.value.fields,a),member:f}}default:return}}async function eie(e,t,n,r,i,o){let a=[],s=!1;for(let u of e){let l=o.get(u.id);if(u.aspect==="activation"){a.push(l&&l.evidence==="attemptTrace"?l:await i(u));continue}if(u.subject.kind==="requirement"){a.push({checkId:u.id,state:"manualPending",evidence:"notAvailable"});continue}let c=u.subject,d,f;if(!s)try{d=await WL(u,t,n,r),f=d===void 0?void 0:await(0,Ae.digestOf)(r,d)}catch(m){if(!(m instanceof yA.PromotionError))throw m;s=m.code==="PROMOTION_READ_BUDGET_EXCEEDED",d=void 0}if(d===void 0||f===void 0){a.push({checkId:u.id,state:"unreadable",evidence:"notAvailable",problem:(0,Ae.promotionProblem)("PROMOTION_VERIFICATION_FAILED","verify",{subject:c,reason:"the target could not be read"})});continue}let p=(0,Ae.canonicalJson)(d)===(0,Ae.canonicalJson)(u.expected);a.push({checkId:u.id,state:p?"matched":"mismatched",evidence:"targetRead",observedDigest:f,...p?{}:{problem:(0,Ae.promotionProblem)("PROMOTION_VERIFICATION_FAILED","verify",{subject:c})}})}return a}or.verifyChecks=eie});var AA=C(Mt=>{"use strict";Object.defineProperty(Mt,"__esModule",{value:!0});Mt.planPromotion=Mt.modelOf=Mt.packageIdentity=Mt.outcomeOf=Mt.sortProblems=Mt.planDigestOf=Mt.digestInput=Mt.decodePackage=Mt.latched=Mt.readClient=Mt.IssuedPlans=void 0;var HL=Y(),tie=ia(),nie=ft(),KL=kg(),zL=zE(),hp=Kg(),vA=bA(),ua=Ya(),wA=class{constructor(t=256){this.capacity=t,this.digests=new Set}add(t){for(this.digests.delete(t),this.digests.add(t);this.digests.size>this.capacity;)this.digests.delete(this.digests.values().next().value)}has(t){return this.digests.has(t)}};Mt.IssuedPlans=wA;function EA(e,t){return e.withoutSolution().withTransport(n=>t.wrap(n)).readOnly()}Mt.readClient=EA;async function JL(e,t){let n=()=>{let i=e.flatMap(o=>o.refusedWrites);if(i.length>0)throw new HL.SdkError("PREVIEW_WRITE_REFUSED",`A promotion plan attempted ${i.length} write(s); it may only read. Nothing was written. This is a defect in the SDK.`)},r;try{r=await t()}catch(i){throw n(),i}return n(),r}Mt.latched=JL;function YL(e){if(!(e.length%4!==0||!/^[A-Za-z0-9+/]*={0,2}$/.test(e)))return(0,tie.base64ToBytes)(e)}Mt.decodePackage=YL;function QL(e){return{schemaVersion:e.schemaVersion,package:e.package,source:e.source,target:e.target,intent:e.intent,limits:e.limits,importKind:e.importKind,observations:e.observations,coverage:e.coverage,checks:e.checks,steps:e.steps,outcome:e.outcome,problems:e.problems.map(t=>{var n,r;return{code:t.code,phase:t.phase,blocking:t.blocking,subject:(n=t.subject)!==null&&n!==void 0?n:null,stepId:(r=t.stepId)!==null&&r!==void 0?r:null}})}}Mt.digestInput=QL;function XL(e,t){return(0,ua.digestOf)(e,QL(t))}Mt.planDigestOf=XL;function ZL(e){let t=new Set;return e.map(n=>n.problem).filter(n=>{var r;let i=`${n.code}\0${(0,ua.identityKey)((r=n.subject)!==null&&r!==void 0?r:null)}\0${n.message}`;return t.has(i)?!1:(t.add(i),!0)}).sort((n,r)=>{var i,o;return(0,ua.byCodeUnit)(n.code,r.code)||(0,ua.byCodeUnit)((0,ua.identityKey)((i=n.subject)!==null&&i!==void 0?i:null),(0,ua.identityKey)((o=r.subject)!==null&&o!==void 0?o:null))})}Mt.sortProblems=ZL;function eM(e,t){return e.some(n=>n.problem.blocking&&!n.unknown)?"refused":!t||e.some(n=>n.problem.blocking&&n.unknown)?"unknown":"ready"}Mt.outcomeOf=eM;function tM(e){return{sha256:e.sha256,solutionUniqueName:e.solutionUniqueName,version:e.version,managed:e.managed,publisherUniqueName:e.publisherUniqueName,publisherPrefix:e.publisherPrefix,projectionVersion:KL.PACKAGE_PROJECTION_VERSION}}Mt.packageIdentity=tM;async function nM(e,t,n){let r=YL(e);if(!r)throw(0,ua.promotionError)("PROMOTION_PACKAGE_UNREADABLE","preflight",{reason:"not base64"});return(0,KL.readPackage)(r,t,n)}Mt.modelOf=nM;async function rie(e,t,n){var r,i;let{intent:o,codec:a,limits:s,packageBase64:u}=(0,hp.readPlanInput)(n),l=(r=e.gates)!==null&&r!==void 0?r:hp.CERTIFIED_GATES,c=new ua.ReadBudget(s,(i=e.now)!==null&&i!==void 0?i:Date.now,!0),d=EA(t,c),f=EA(e.client,c);return JL([d.guard,f.guard],async()=>{var p,m;let h=await nM(u,a,s),g=await(0,ua.readEnvironment)(d.client),y=await(0,ua.readEnvironment)(f.client),b=[];g.organizationId===y.organizationId&&b.push((0,hp.refusal)("PROMOTION_SAME_ENVIRONMENT")),g.tenantId!==y.tenantId&&b.push((0,hp.refusal)("PROMOTION_TENANT_MISMATCH"));let E=!0,w={importKind:"undetermined",observations:[],coverage:[],checks:[],steps:[]};try{c.countComponents(h.componentCount);let O=new zL.OrgReader(d.client,c,a),v=await(0,vA.judgeSource)(h,O),N=await(0,hp.buildRecipe)(h,o,l,a,v),S=await(0,vA.correspondSource)(N.checks,h,O,a),R=await(0,vA.observeTarget)(h,o,new zL.OrgReader(f.client,c,a),a,l.connectionReferences,e.listConnections?()=>e.listConnections(f.client,c):void 0);b.push(...N.findings,...S,...R.findings),w={importKind:R.importKind,observations:R.observations,coverage:N.coverage,checks:N.checks,steps:N.steps}}catch(O){if(!(O instanceof HL.PromotionError)||O.code!=="PROMOTION_READ_BUDGET_EXCEEDED")throw O;E=!1,b.push({problem:O.problem,unknown:!0})}let _=eM(b,E),I={schemaVersion:1,planId:((p=e.newId)!==null&&p!==void 0?p:nie.newId)(),source:g,target:y,package:tM(h),intent:o,limits:s,importKind:w.importKind,observations:w.observations,coverage:w.coverage,checks:w.checks,steps:w.steps,outcome:_,problems:ZL(b),reads:{getAttempts:c.getAttempts,layerLookups:c.layerLookups,layerPages:c.layerPages,components:c.components,elapsedMs:c.elapsedMs,complete:E}},T=await XL(a,I);return(m=e.issuedPlans)===null||m===void 0||m.add(T),{...I,planDigest:T}})}Mt.planPromotion=rie});var sM=C(Qg=>{"use strict";Object.defineProperty(Qg,"__esModule",{value:!0});Qg.promote=void 0;var iie=Ke(),gp=Y(),oM=ft(),oie=pe(),rM=ae(),CA=zE(),yp=Kg(),ts=bA(),oe=Ya(),ns=AA(),aie=new Set(["codec","journal","resumeAttemptId","retryKnownUnappliedStepIds","pollTimeoutMs","onReceipt"]),sie=6e5,iM=[250,500,1e3,2e3,5e3],Eo=e=>(0,oe.promotionError)("PROMOTION_PLAN_INVALID","preflight",{reason:e}),ul=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),rs=e=>JSON.parse(JSON.stringify(e));function uie(e){var t,n;if(!ul(e))throw(0,oe.promotionError)("PROMOTION_JOURNAL_REQUIRED","preflight");let r=e.journal;if(!r||typeof r.begin!="function"||typeof r.read!="function"||typeof r.replace!="function"||typeof r.release!="function")throw(0,oe.promotionError)("PROMOTION_JOURNAL_REQUIRED","preflight");let i=(0,yp.requireCodec)(e.codec);for(let l of Object.keys(e))if(!aie.has(l))throw(0,oe.promotionError)("INVALID_ARGUMENT","preflight",{reason:"an unsupported apply option"});let o=e.resumeAttemptId;if(o!==void 0&&!(0,oe.canonicalGuid)(o))throw(0,oe.promotionError)("INVALID_ARGUMENT","preflight",{reason:"resumeAttemptId must be an attempt id"});let a=(t=e.retryKnownUnappliedStepIds)!==null&&t!==void 0?t:[],s=Array.isArray(a)?[...a]:[];if(!Array.isArray(a)||s.some(l=>typeof l!="string"))throw(0,oe.promotionError)("INVALID_ARGUMENT","preflight",{reason:"retryKnownUnappliedStepIds must be step ids"});let u=(n=e.pollTimeoutMs)!==null&&n!==void 0?n:sie;if(typeof u!="number"||!Number.isSafeInteger(u)||u<=0)throw(0,oe.promotionError)("INVALID_ARGUMENT","preflight",{reason:"pollTimeoutMs must be a positive safe integer"});if(e.onReceipt!==void 0&&typeof e.onReceipt!="function")throw(0,oe.promotionError)("INVALID_ARGUMENT","preflight",{reason:"onReceipt must be a function"});return{codec:i,journal:r,...o!==void 0?{resumeAttemptId:(0,oe.canonicalGuid)(o)}:{},retry:s,pollTimeoutMs:u,...e.onReceipt?{onReceipt:e.onReceipt}:{}}}function lie(e,t){let n;try{n=ul(e)?rs(e):e}catch{throw Eo("a plan that is not JSON data")}if(!ul(n)||n.schemaVersion!==1)throw Eo("an unsupported plan schema");let r=o=>ul(o)&&["organizationId","tenantId","instanceUrl","actorId"].every(a=>typeof o[a]=="string"),i=n.package;if(typeof n.planId!="string"||typeof n.planDigest!="string"||!/^[0-9a-f]{64}$/.test(n.planDigest)||!r(n.source)||!r(n.target)||!ul(i)||typeof i.sha256!="string"||!ul(n.intent)||!["install","update","undetermined"].includes(n.importKind)||!["ready","refused","unknown"].includes(n.outcome)||!["observations","coverage","checks","steps","problems"].every(o=>Array.isArray(n[o]))||!ul(n.reads))throw Eo("a malformed plan");try{let o=(0,yp.readPlanInput)({...n.intent,packageBase64:"x",codec:t});if((0,oe.canonicalJson)(o.intent)!==(0,oe.canonicalJson)(n.intent))throw Eo("a non-canonical intent");if((0,oe.canonicalJson)((0,yp.readLimits)(n.limits))!==(0,oe.canonicalJson)(n.limits))throw Eo("non-canonical limits")}catch(o){throw o instanceof gp.PromotionError&&o.code==="PROMOTION_PLAN_INVALID"?o:Eo("an invalid intent")}return n}function aM(e,t){return{schemaVersion:1,attemptId:t,planId:e.planId,planDigest:e.planDigest,packageSha256:e.package.sha256,targetOrganizationId:e.target.organizationId,targetTenantId:e.target.tenantId,phase:"preflight",stage:{state:"notStarted"},import:{state:"notSubmitted"},steps:e.steps.map(n=>({stepId:n.id,state:"notStarted",expectedBefore:[]})),verification:[],effects:"noneVerified",cleanup:{state:"notStarted"}}}function Lc(e,t,n){return{status:"failed",receipt:aM(e,n),problems:t}}var Yg=class{constructor(t,n,r){this.journal=t,this.record=n,this.onReceipt=r,this.stopped=!1,this.problems=[],this.receipt=rs(n.receipt)}get released(){return this.record.reservation==="released"}async save(t){let n=t(rs(this.receipt));if(this.receipt=n,this.stopped)return!1;let r={...this.record,revision:this.record.revision+1,receipt:rs(n)},i=!1;try{i=await this.journal.replace(n.attemptId,this.record.revision,r)===!0}catch{i=!1}if(!i)return this.stop("the journal did not accept the attempt state"),!1;if(this.record=r,this.onReceipt)try{await this.onReceipt(rs(n))}catch{return this.stop("the host receipt notification failed"),!1}return!0}stop(t){this.stopped=!0,this.problems.push((0,oe.promotionProblem)("PROMOTION_JOURNAL_FAILED",this.receipt.phase,{reason:t}))}async release(){if(this.stopped||this.released)return;let t=!1;try{t=await this.journal.release(this.receipt.targetOrganizationId,this.receipt.attemptId,this.record.revision)===!0}catch{t=!1}t?this.record={...this.record,revision:this.record.revision+1,reservation:"released"}:this.problems.push((0,oe.promotionProblem)("PROMOTION_JOURNAL_FAILED",this.receipt.phase,{blocking:!1,reason:"the reservation could not be released"}))}};function cie(e){return e.import.state==="succeeded"?e.effects==="completeVerified"?"applied":"partial":e.effects==="partialKnown"?"partial":e.effects==="unknown"||["submitting","running","unknown"].includes(e.import.state)?"unknown":"failed"}var SA=class{constructor(t,n,r,i,o,a,s,u){this.context=t,this.attempt=n,this.plan=r,this.model=i,this.client=o,this.budget=a,this.options=s,this.gates=u,this.problems=[],this.trace=[]}problem(t,n,r={}){this.problems.push((0,oe.promotionProblem)(t,n,r))}result(t){return{status:t,receipt:rs(this.attempt.receipt),problems:[...this.problems,...this.attempt.problems]}}lister(t){let n=this.context.listConnections;return n?()=>n(t,this.budget):void 0}async observe(){let{client:t,guard:n}=this.client.readOnly();try{let r=await(0,ns.latched)([n],()=>(0,ts.observeTarget)(this.model,this.plan.intent,new CA.OrgReader(t,this.budget,this.options.codec),this.options.codec,this.gates.connectionReferences,this.lister(t)));return r.observations.some(i=>i.image.state==="unreadable")||r.findings.some(i=>i.unknown)?void 0:r.observations}catch(r){if(r instanceof gp.PromotionError)return;throw r}}parameters(){let t=[];for(let n of this.model.variables){let r=this.plan.intent.values.find(i=>i.schemaName.toLowerCase()===n.schemaName.toLowerCase());r&&r.value!==""&&t.push({"@odata.type":"Microsoft.Dynamics.CRM.environmentvariablevalue",schemaname:n.schemaName,value:r.value})}for(let n of this.model.references){let r=this.plan.intent.connections.find(i=>i.logicalName.toLowerCase()===n.logicalName.toLowerCase());r&&r.connectionId!==""&&t.push({"@odata.type":"Microsoft.Dynamics.CRM.connectionreference",connectionreferencelogicalname:n.logicalName,connectionid:r.connectionId,connectorid:n.connectorId})}return t}stageDiscrepancy(t){let n=this.model,r=t.details;if(!r)return"the staged solution details are missing";let i=(0,oe.parseVersion)(r.version);if(r.solutionName.toLowerCase()!==n.solutionUniqueName.toLowerCase()||r.publisherName.toLowerCase()!==n.publisherUniqueName.toLowerCase()||r.managed!==n.managed||!i||(0,oe.compareVersions)(i,(0,oe.parseVersion)(n.version))!==0)return"another solution, publisher, mode or version was staged";if(r.patch||r.pendingUpgrade)return"a patch or a pending upgrade was staged";if(t.missing>0)return this.problem("PROMOTION_DEPENDENCY_MISSING","stage"),"staging reports missing dependencies";if(t.validationErrors>0)return"staging reports validation errors";let o=c=>c.map(d=>d.toLowerCase()).sort();if((0,oe.canonicalJson)(o(n.apps.map(c=>c.uniqueName)))!==(0,oe.canonicalJson)(t.apps)||(0,oe.canonicalJson)(o(n.webResources.map(c=>c.name)))!==(0,oe.canonicalJson)(t.webResources))return"the staged apps or web resources differ from the package";let a=[...n.variables].sort((c,d)=>(0,oe.byCodeUnit)(c.schemaName.toLowerCase(),d.schemaName.toLowerCase())).map(c=>{var d;return{schemaName:c.schemaName.toLowerCase(),type:String(c.type),isRequired:c.isRequired?"true":"false",defaultValue:(d=c.defaultValue)!==null&&d!==void 0?d:""}}),s=t.variables.map(c=>({...c,isRequired:c.isRequired===null?null:c.isRequired.toLowerCase()}));if((0,oe.canonicalJson)(a)!==(0,oe.canonicalJson)(s))return"the staged variables differ from the package";let u=[...n.references].sort((c,d)=>(0,oe.byCodeUnit)(c.logicalName.toLowerCase(),d.logicalName.toLowerCase())).map(c=>({logicalName:c.logicalName.toLowerCase(),connectorId:c.connectorId.toLowerCase()})),l=t.references.map(c=>({logicalName:c.logicalName,connectorId:c.connectorId===null?null:c.connectorId.toLowerCase()}));if((0,oe.canonicalJson)(u)!==(0,oe.canonicalJson)(l))return"the staged connection references differ from the package"}async fresh(t){if(!await this.attempt.save(s=>({...s,phase:"stage",stage:{state:"submitting"}})))return this.result("failed");let n,r={};this.trace.push({action:"StageSolution"});try{let s=await this.client.post("/StageSolution",{CustomizationFile:t});n=s.status===200?(0,ts.readStageAnswer)(s.body):ts.UNREADABLE_STAGE,r=s.status===200?{}:{httpStatus:s.status}}catch(s){n=ts.UNREADABLE_STAGE,r=(0,oe.safeDiagnostics)(s)}if(n.status==="unreadable")return await this.attempt.save(s=>({...s,stage:{state:"unknown",...n.uploadId?{uploadId:n.uploadId}:{}},effects:"unknown"})),this.problem("PROMOTION_STAGE_UNKNOWN","stage",r),this.result("unknown");if(n.status==="Failed")return await this.attempt.save(s=>({...s,stage:{state:"failed",...n.uploadId?{uploadId:n.uploadId}:{}}})),this.problem("PROMOTION_STAGE_FAILED","stage"),n.missing>0&&this.problem("PROMOTION_DEPENDENCY_MISSING","stage"),await this.cleanup(),await this.finish("failed"),this.result("failed");let i=n.uploadId;if(!await this.attempt.save(s=>({...s,stage:{state:"passed",uploadId:i}})))return await this.attempt.save(s=>({...s,cleanup:{state:"deferred",remainingUploadId:i}})),this.result("failed");let o=this.stageDiscrepancy(n);if(o)return this.problem("PROMOTION_STAGE_FAILED","stage",{reason:o}),await this.cleanup(),await this.finish("failed"),this.result("failed");let a=await this.observe();return!a||!(0,ts.sameObservations)(a,this.plan.observations)?(this.problem(a?"PROMOTION_PLAN_STALE":"PROMOTION_VERIFICATION_UNAVAILABLE","stage"),await this.cleanup(),await this.finish("failed"),this.result("failed")):this.importOnce(i)}async importOnce(t){var n,r;let i=((n=this.context.newId)!==null&&n!==void 0?n:oM.newId)();if(!await this.attempt.save(d=>({...d,phase:"import",import:{state:"submitting",importJobId:i}})))return await this.attempt.save(d=>({...d,cleanup:{state:"deferred",remainingUploadId:t}})),this.result("failed");let o=this.parameters(),a={OverwriteUnmanagedCustomizations:this.plan.intent.overwriteUnmanagedCustomizations,PublishWorkflows:this.plan.intent.publishWorkflows,ImportJobId:i,SolutionParameters:{StageSolutionUploadId:t},...o.length>0?{ComponentParameters:o}:{}};this.trace.push({action:"ImportSolutionAsync",publishWorkflows:a.PublishWorkflows});let s=0,u,l={};try{let d=await this.client.post("/ImportSolutionAsync",a);s=d.status,u=(0,oe.canonicalGuid)((r=d.body)===null||r===void 0?void 0:r.AsyncOperationId)}catch(d){l=(0,oe.safeDiagnostics)(d)}if(s>=200&&s<300&&u){let d=u;await this.attempt.save(p=>({...p,import:{state:"running",importJobId:i,asyncOperationId:d}}));let f=await this.activationEvidence();return await this.attempt.save(p=>({...p,verification:f})),this.attempt.stopped?this.stopped():this.settle(d)}let c=await this.activationEvidence();return await this.attempt.save(d=>({...d,import:{state:"unknown",importJobId:i,...u?{asyncOperationId:u}:{}},verification:c,effects:"unknown",cleanup:{state:"deferred",remainingUploadId:t}})),this.problem("PROMOTION_IMPORT_UNKNOWN","import",{...l,...s?{httpStatus:s}:{}}),this.result("unknown")}async activationEvidence(){let t=[];for(let n of this.plan.checks.filter(r=>r.aspect==="activation"))t.push(await this.activationResult(n));return t}async poll(t){var n,r;let i=(n=this.context.now)!==null&&n!==void 0?n:Date.now,o=(r=this.context.sleep)!==null&&r!==void 0?r:oie.sleep,a=i()+this.options.pollTimeoutMs,s;for(let u=0;;u+=1){try{let c=await this.client.get(`/asyncoperations(${t})${(0,rM.odataQuery)([["$select","statecode,statuscode"]])}`),d=c.body;if(c.status===200&&typeof d?.statecode=="number"&&typeof d?.statuscode=="number"&&(s={stateCode:d.statecode,statusCode:d.statuscode},d.statecode===3))return{state:d.statuscode===30?"succeeded":d.statuscode===31||d.statuscode===32?"failed":"unknown",...s}}catch(c){if(c instanceof gp.PromotionError&&c.code==="PROMOTION_READ_BUDGET_EXCEEDED")break}let l=a-i();if(l<=0)break;await o(Math.min(iM[Math.min(u,iM.length-1)],l))}return s?{state:"running",...s}:{state:"unknown"}}async settle(t){let n=await this.poll(t),r={...n.stateCode!==void 0?{stateCode:n.stateCode}:{},...n.statusCode!==void 0?{statusCode:n.statusCode}:{}};return n.state==="succeeded"?(await this.attempt.save(i=>({...i,phase:"verify",import:{...i.import,state:"succeeded",...r}})),this.attempt.stopped?this.stopped():this.verifyAndFinish()):n.state==="failed"?(await this.attempt.save(i=>({...i,import:{...i.import,state:"failed",...r}})),this.problem("PROMOTION_IMPORT_FAILED","import"),this.attempt.stopped?this.stopped():this.afterFailedImport()):(await this.attempt.save(i=>({...i,import:{...i.import,state:n.state==="running"?"running":"unknown",...r},effects:"unknown",cleanup:i.stage.uploadId?{state:"deferred",remainingUploadId:i.stage.uploadId}:i.cleanup})),this.problem("PROMOTION_IMPORT_UNKNOWN","import",{reason:"the import did not reach a terminal state in time"}),this.result("unknown"))}async activationResult(t){let n=this.trace.filter(a=>a.action==="ImportSolutionAsync");if(n.length!==1)return{checkId:t.id,state:"unreadable",evidence:"notAvailable",problem:(0,oe.promotionProblem)("PROMOTION_VERIFICATION_FAILED","verify",{reason:"no dispatch trace of the import"})};let r={publishWorkflows:n[0].publishWorkflows===!0,activationRequests:this.trace.filter(a=>a.action!=="ImportSolutionAsync"&&a.action!=="StageSolution"&&a.action!=="DeleteUpload").length},i=!r.publishWorkflows&&r.activationRequests===0,o;try{o=await(0,oe.digestOf)(this.options.codec,r)}catch{return{checkId:t.id,state:"unreadable",evidence:"notAvailable",problem:(0,oe.promotionProblem)("PROMOTION_VERIFICATION_FAILED","verify",{reason:"the dispatch evidence could not be digested"})}}return{checkId:t.id,state:i?"matched":"mismatched",evidence:"attemptTrace",observedDigest:o,...i?{}:{problem:(0,oe.promotionProblem)("PROMOTION_VERIFICATION_FAILED","verify",{reason:"an activation was requested"})}}}async verifyAndFinish(){var t;let{client:n,guard:r}=this.client.readOnly(),i=new Map(this.attempt.receipt.verification.map(s=>[s.checkId,s])),o=await(0,ns.latched)([r],()=>(0,ts.verifyChecks)(this.plan.checks,this.model,new CA.OrgReader(n,this.budget,this.options.codec),this.options.codec,s=>this.activationResult(s),i)),a=o.every(s=>s.state==="matched");for(let s of o.filter(u=>u.state!=="matched"))this.problems.push((t=s.problem)!==null&&t!==void 0?t:(0,oe.promotionProblem)("PROMOTION_VERIFICATION_UNAVAILABLE","verify",{reason:"a declared requirement is pending a manual step"}));return await this.attempt.save(s=>({...s,phase:"verify",verification:o,steps:s.steps.map(u=>({...u,state:"manualPending"})),effects:a?"completeVerified":"partialKnown"})),this.attempt.stopped?this.stopped():(await this.cleanup(),a&&await this.finish("applied"),this.attempt.stopped?this.stopped():this.result(a?"applied":"partial"))}async afterFailedImport(){let t=await this.observe(),n=i=>i.filter(o=>o.purpose==="affected"),r=t?(0,ts.sameObservations)(n(t),n(this.plan.observations))?"failed":"partial":"unknown";return await this.attempt.save(i=>({...i,effects:r==="failed"?"noneVerified":r==="partial"?"partialKnown":"unknown"})),this.attempt.stopped?this.stopped():r==="unknown"?(await this.attempt.save(i=>({...i,cleanup:i.stage.uploadId?{state:"deferred",remainingUploadId:i.stage.uploadId}:i.cleanup})),this.result("unknown")):(await this.cleanup(),await this.finish(r),this.attempt.stopped?this.stopped():this.result(r))}async stopped(){let t=this.attempt.receipt,n=t.import.state==="succeeded"||t.effects==="partialKnown"?"partial":"unknown";return await this.attempt.save(r=>({...r,effects:n==="partial"?"partialKnown":"unknown",cleanup:r.stage.uploadId&&r.cleanup.state!=="complete"?{state:"deferred",remainingUploadId:r.stage.uploadId}:r.cleanup})),this.result(n)}async finish(t){t!=="partial"&&await this.attempt.save(n=>({...n,phase:"complete"})),await this.attempt.release()}async cleanup(){let t=this.attempt.receipt.stage.uploadId;if(!t)return;let n=async u=>{await this.attempt.save(l=>({...l,cleanup:{state:"deferred",remainingUploadId:t}})),this.problem("PROMOTION_CLEANUP_FAILED","cleanup",{blocking:!1,reason:u})};if(this.attempt.stopped){await n("the journal stopped this attempt");return}let r=`/stagesolutionuploads${(0,rM.odataQuery)([["$select","stagesolutionuploadid"],["$filter",`stagesolutionuploadid eq ${t}`]])}`,i=async()=>{var u;try{let l=await this.client.get(r),c=(u=l.body)===null||u===void 0?void 0:u.value;return l.status===200&&Array.isArray(c)&&(0,iie.boundedPageComplete)(l.body,c.length)?c:void 0}catch{return}},o=await i();if(o&&o.length===0){await this.attempt.save(u=>({...u,cleanup:{state:"complete"}}));return}if(!this.gates.stageCleanup){await n("conditional deletion of the staged upload is not certified");return}let a=o?.length===1?o[0]["@odata.etag"]:void 0;if(typeof a!="string"){await n("the staged upload has no readable row token");return}if(!await this.attempt.save(u=>({...u,phase:"cleanup"})))return;this.trace.push({action:"DeleteUpload"});try{await this.client.delete(`/stagesolutionuploads(${t})`,{headers:{"If-Match":a}})}catch{}let s=await i();if(s&&s.length===0){await this.attempt.save(u=>({...u,cleanup:{state:"complete"}}));return}await this.attempt.save(u=>({...u,cleanup:{state:"failed",remainingUploadId:t}})),this.problem("PROMOTION_CLEANUP_FAILED","cleanup",{blocking:!1})}async resume(){let t=this.attempt.receipt;return t.import.state==="succeeded"?this.verifyAndFinish():t.import.state==="failed"?this.afterFailedImport():(t.import.state==="running"||t.import.state==="unknown")&&t.import.asyncOperationId?this.settle(t.import.asyncOperationId):t.import.state==="notSubmitted"?t.stage.state!=="passed"&&t.stage.state!=="failed"?(this.problem("PROMOTION_STAGE_UNKNOWN","stage",{reason:"the staging outcome was never read"}),this.result("unknown")):(this.problem("PROMOTION_STAGE_FAILED","stage",{reason:"the attempt stopped before its import"}),await this.cleanup(),await this.finish("failed"),this.result("failed")):(this.problem("PROMOTION_IMPORT_UNKNOWN","import"),this.result("unknown"))}async guarded(t){try{return await t()}catch(n){let r=this.attempt.receipt.phase;this.problems.push(n instanceof gp.PromotionError?(0,oe.promotionProblem)(n.code,r,{reason:"the attempt stopped on an internal failure"}):(0,oe.promotionProblem)("PROMOTION_VERIFICATION_UNAVAILABLE",r,{reason:"the attempt stopped on an unexpected failure"}));let i=this.attempt.receipt.import.state==="succeeded"?"partial":"unknown";try{await this.attempt.save(o=>({...o,effects:i==="partial"?"partialKnown":"unknown",cleanup:o.stage.uploadId&&o.cleanup.state!=="complete"?{state:"deferred",remainingUploadId:o.stage.uploadId}:o.cleanup}))}catch{}return this.result(i)}}};async function die(e,t,n,r){var i,o,a,s,u,l;let c=uie(r),{codec:d}=c,f=lie(t,d);if(await(0,ns.planDigestOf)(d,f)!==f.planDigest)throw Eo("the digest does not match the plan");let p=typeof n=="string"?(0,ns.decodePackage)(n):void 0;if(!p||await(0,oe.sha256Of)(d,p)!==f.package.sha256)throw Eo("the package bytes differ from the planned package");let m=n,h=(i=e.gates)!==null&&i!==void 0?i:yp.CERTIFIED_GATES,g=new oe.ReadBudget(f.limits,(o=e.now)!==null&&o!==void 0?o:Date.now,!1),y=e.client.withoutSolution().withTransport(U=>g.wrap(U)),b=await(0,oe.readEnvironment)(y.readOnly().client);if((0,oe.canonicalJson)(b)!==(0,oe.canonicalJson)(f.target))throw(0,oe.promotionError)("PROMOTION_ENVIRONMENT_MISMATCH","preflight");let E=await(0,ns.modelOf)(m,d,f.limits);if((0,oe.canonicalJson)((0,ns.packageIdentity)(E))!==(0,oe.canonicalJson)(f.package))throw Eo("the package identity differs");let w=(a=c.resumeAttemptId)!==null&&a!==void 0?a:((s=e.newId)!==null&&s!==void 0?s:oM.newId)(),_=U=>e.listConnections?()=>e.listConnections(U,g):void 0,I=U=>new SA(e,U,f,E,y,g,c,h);if(c.resumeAttemptId){let U;try{U=await c.journal.read(w)}catch{throw(0,oe.promotionError)("PROMOTION_JOURNAL_FAILED","preflight")}let M=U?.receipt;if(!U||!M||typeof U.revision!="number"||M.attemptId!==w||((u=U.plan)===null||u===void 0?void 0:u.planId)!==f.planId||((l=U.plan)===null||l===void 0?void 0:l.planDigest)!==f.planDigest||M.planDigest!==f.planDigest||M.packageSha256!==f.package.sha256||M.targetOrganizationId!==f.target.organizationId)throw(0,oe.promotionError)("PROMOTION_RECEIPT_UNVERIFIED","preflight");for(let X of c.retry)if(!M.steps.some(ye=>ye.stepId===X&&ye.state==="failedNotApplied"))throw(0,oe.promotionError)("INVALID_ARGUMENT","preflight",{reason:"a retried step is not known to be unapplied"});if(U.reservation==="released")return{status:cie(M),receipt:rs(M),problems:[]};let q=I(new Yg(c.journal,U,c.onReceipt));return q.guarded(()=>q.resume())}if(c.retry.length>0)throw(0,oe.promotionError)("INVALID_ARGUMENT","preflight",{reason:"only a continuation may retry steps"});if(!e.issuedPlans||!e.issuedPlans.has(f.planDigest))throw Eo("the plan was not issued by this SDK");if(f.outcome!=="ready")return Lc(f,f.problems.map(U=>(0,oe.promotionProblem)(U.code,U.phase,{blocking:U.blocking,subject:U.subject,stepId:U.stepId})),w);let T=await(0,yp.buildRecipe)(E,f.intent,h,d,{refusedRoles:new Set,findings:[]});if((0,oe.canonicalJson)([T.coverage,T.checks,T.steps])!==(0,oe.canonicalJson)([f.coverage,f.checks,f.steps]))throw Eo("the recipe differs from the package and intent");let O=y.readOnly(),v;try{v=await(0,ns.latched)([O.guard],()=>(0,ts.observeTarget)(E,f.intent,new CA.OrgReader(O.client,g,d),d,h.connectionReferences,_(O.client)))}catch(U){if(U instanceof gp.PromotionError&&U.code==="PROMOTION_READ_BUDGET_EXCEEDED")return Lc(f,[U.problem],w);throw U}if(!(0,ts.sameObservations)(v.observations,f.observations)||v.importKind!==f.importKind)return Lc(f,[(0,oe.promotionProblem)("PROMOTION_PLAN_STALE","preflight")],w);let N=[...T.findings,...v.findings],S=[...f.source.organizationId===f.target.organizationId?[(0,oe.promotionProblem)("PROMOTION_SAME_ENVIRONMENT","preflight")]:[],...f.source.tenantId!==f.target.tenantId?[(0,oe.promotionProblem)("PROMOTION_TENANT_MISMATCH","preflight")]:[]];if((0,ns.outcomeOf)(N,!0)!=="ready"||S.length>0)return Lc(f,[...(0,ns.sortProblems)(N),...S],w);let R={revision:0,reservation:"held",plan:rs(f),receipt:aM(f,w)},x;try{x=await c.journal.begin(f.target.organizationId,rs(R))}catch{return Lc(f,[(0,oe.promotionProblem)("PROMOTION_JOURNAL_FAILED","preflight")],w)}if(!x||x.acquired!==!0)return Lc(f,[(0,oe.promotionProblem)("PROMOTION_ATTEMPT_IN_PROGRESS","preflight")],w);let G=I(new Yg(c.journal,R,c.onReceipt));return G.guarded(()=>G.fresh(m))}Qg.promote=die});var lM={};Fi(lM,{CCFControlConstants:()=>uM,CCFPropertyConstants:()=>_A,CustomControlDataType:()=>j,CustomControlNames:()=>is,DefaultControlNameKeys:()=>NA,ICCModeEnum:()=>eu,JSONParametersConstants:()=>IA,LookUpType:()=>Xg,ManifestXMLConstants:()=>vr,NumberType:()=>Zg,Usage:()=>ll});var uM,_A,IA,vr,j,NA,is,eu,ll,Xg,Zg,cl=B(()=>{"use strict";uM={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"},_A={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"},IA={GroupDefinition:"GroupDefinition"},vr={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"})(j||(j={}));(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"})(NA||(NA={}));(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"})(is||(is={}));(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"})(eu||(eu={}));(function(e){e[e.Bound=0]="Bound",e[e.Input=1]="Input",e[e.Output=2]="Output"})(ll||(ll={}));Xg=[j.LookupCustomer,j.LookupOwner,j.LookupPartyList,j.LookupRegarding,j.LookupSimple],Zg=[j.WholeNone,j.WholeDuration,j.WholeLanguage,j.WholeTimeZone,j.FP,j.Decimal]});var Mc,qr,bp=B(()=>{"use strict";Mc=class{keys;values;constructor(){this.keys=[],this.values=[]}add(t,n){return this.containsKey(t)?!1:(this.keys.push(t),this.values.push(n),!0)}upsert(t,n){this.update(t,n)||this.add(t,n)}sortedUpsert(t,n){if(!this.update(t,n)){let r=0;for(;r<this.keys.length&&this.keys[r]<t;)r++;this.keys.splice(r,0,t),this.values.splice(r,0,n)}}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 n=this.keys.indexOf(t);return n!==-1?this.values[n]:!1}getKeys(){return this.keys.slice()}getValues(){return this.values.slice()}remove(t){let n=this.keys.indexOf(t);return n!==-1?(this.keys.splice(n,1),this.values.splice(n,1),!0):!1}update(t,n){let r=this.keys.indexOf(t);return r!==-1?(this.values[r]=n,!0):!1}},qr=class{data={};add(t,n){return this.containsKey(t)?!1:(this.data[t]=n,!0)}upsert(t,n){this.data[t]=n}clear(){this.data={}}containsKey(t){return this.data.hasOwnProperty(t)}containsValue(t){for(let n in this.data)if(this.data[n]===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 n in this.data)t.push(this.data[n]);return t}remove(t){return this.containsKey(t)?delete this.data[t]:!1}update(t,n){return this.containsKey(t)?(this.data[t]=n,!0):!1}getInternalObject(){return this.data}}});var cM={};Fi(cM,{AttributeDataSourceType:()=>vp,AttributeDataSourceTypeMask:()=>e0,AttributePrecisionSource:()=>wp,EntityAttributeDataSourceType:()=>dl,EntityAttributeDateTimeBehavior:()=>DA,EntityAttributeImeMode:()=>OA,EntityAttributePrecisionSource:()=>PA,EntityAttributeRequiredLevel:()=>tu,EntityAttributeType:()=>V,EntityAttributeTypeFormat:()=>ne,EntityMetadataLookUpBase:()=>os,EntityResxKeyLookUp:()=>t0,SourceTypeMask:()=>TA});var os,V,ne,tu,dl,TA,vp,e0,OA,DA,PA,wp,t0,xc=B(()=>{"use strict";bp();os=class{name;constructor(t){this.name=t}toString(){return this.name}getName(){return this.name}getDisplayNameResourceKey(){return t0.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"})(V||(V={}));(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"})(ne||(ne={}));tu=class extends os{constructor(t){super(t)}static get None(){return"None"}static get SystemRequired(){return"SystemRequired"}static get ApplicationRequired(){return"ApplicationRequired"}static get Recommended(){return"Recommended"}},dl=class e extends os{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?vp.Persistent:parseInt(vp[this.name])}},TA=class e extends os{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(e0[this.name])}};(function(e){e[e.Persistent=0]="Persistent",e[e.Calculated=1]="Calculated",e[e.Rollup=2]="Rollup"})(vp||(vp={}));(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"})(e0||(e0={}));OA=class e extends os{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"}},DA=class e extends os{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"}},PA=class e extends os{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?wp.Currency:parseInt(wp[this.name])}};(function(e){e[e.Attribute=0]="Attribute",e[e.Organization=1]="Organization",e[e.Currency=2]="Currency"})(wp||(wp={}));t0=class e{static resourceKeyMap=e.initResourceKeyMap();static initResourceKeyMap(){let t=new Mc;return t.add(V.TwoOptions,"SystemCustomization.type.bit.label"),t.add(V.Customer,"SystemCustomization.type.customer.label"),t.add(V.CustomerType,"SystemCustomization.type.customer.label"),t.add(V.DateTime,"SystemCustomization.type.datetime.label"),t.add(V.DecimalNumber,"SystemCustomization.type.decimal.label"),t.add(V.FloatingPointNumber,"SystemCustomization.type.float.label"),t.add(V.WholeNumber,"SystemCustomization.type.int.label"),t.add(V.LookupType,"SystemCustomization.type.lookup.label"),t.add(V.Lookup,"SystemCustomization.type.lookup.label"),t.add(V.MultipleLineofText,"SystemCustomization.type.ntext.label"),t.add(V.Currency,"SystemCustomization.type.money.label"),t.add(V.Owner,"SystemCustomization.type.owner.label"),t.add(V.OwnerType,"SystemCustomization.type.owner.label"),t.add(V.PartyList,"SystemCustomization.type.partylist.label"),t.add(V.PartyListType,"SystemCustomization.type.partylist.label"),t.add(V.OptionSet,"SystemCustomization.type.picklist.label"),t.add(V.State,"SystemCustomization.type.state.label"),t.add(V.Status,"SystemCustomization.type.status.label"),t.add(V.SingleLineofText,"SystemCustomization.type.nvarchar.label"),t.add(V.UniqueIdentifier,"SystemCustomization.type.uniqueidentifier.label"),t.add(V.UniqueIdentifierType,"SystemCustomization.type.uniqueidentifiertype.label"),t.add(V.CalendarRulesType,"SystemCustomization.type.calendarrules.label"),t.add(V.VirtualType,"SystemCustomization.type.virtual.label"),t.add(V.BigInt,"SystemCustomization.type.bigint.label"),t.add(V.ManagedPropertyType,"SystemCustomization.type.managedproperty.label"),t.add(V.EntityNameType,"SystemCustomization.type.entityname.label"),t.add(V.Image,"SystemCustomization.type.image.label"),t.add(V.MultiSelectOptionSet,"SystemCustomization.type.multiselectpicklist.label"),t.add(V.PrimaryNameAttributeType,"SystemCustomization.type.primaryname.label"),t.add(V.LookupType,"SystemCustomization.type.lookuptype.label"),t.add(V.Subject,"SystemCustomization.type.subject.label"),t.add(ne.Email,"SystemCustomization.String.Format.email"),t.add(ne.Text,"SystemCustomization.String.Format.text"),t.add(ne.TextArea,"SystemCustomization.String.Format.textarea"),t.add(ne.Url,"SystemCustomization.String.Format.url"),t.add(ne.TickerSymbol,"SystemCustomization.String.Format.tickersymbol"),t.add(ne.PhoneticGuide,"SystemCustomization.String.Format.phoneticguide"),t.add(ne.VersionNumber,"SystemCustomization.String.Format.versionnumber"),t.add(ne.Phone,"SystemCustomization.String.Format.phone"),t.add(ne.None,"SystemCustomization.Integer.Format."),t.add(ne.Duration,"SystemCustomization.Integer.Format.duration"),t.add(ne.TimeZone,"SystemCustomization.Integer.Format.timezone"),t.add(ne.Language,"SystemCustomization.Integer.Format.language"),t.add(ne.Locale,"SystemCustomization.Integer.Format.language"),t.add(ne.DateOnly,"SystemCustomization.DateTime.Format.date"),t.add(ne.DateAndTime,"SystemCustomization.DateTime.Format.datetime"),t.add(ne.Regarding,"SystemCustomization.Lookup.Format.regarding"),t.add(dl.Persistent,"SystemCustomization.String.Source.persistent"),t.add(dl.Calculated,"SystemCustomization.String.Source.calculated"),t.add(dl.Rollup,"SystemCustomization.String.Source.rollup"),t.add(dl.None,"SystemCustomization.String.Source.none"),t}static getDisplayNameResourceKey(t){return e.resourceKeyMap.getValue(t)}}});var kA=C(vn=>{"use strict";Object.defineProperty(vn,"__esModule",{value:!0});vn.parsePcfManifest=vn.parseControlElement=vn.parseManifestRoot=vn.firstLevel=vn.attr=vn.elementChildren=vn.manifestTypesForColumn=vn.DEFAULT_TYPE_GROUPS=void 0;var fie=Ms(),ie=(cl(),_i(lM)),Je=(xc(),_i(cM));vn.DEFAULT_TYPE_GROUPS={numbers:[ie.CustomControlDataType.WholeNone,ie.CustomControlDataType.FP,ie.CustomControlDataType.Decimal,ie.CustomControlDataType.Currency],text:[ie.CustomControlDataType.SingleLineText,ie.CustomControlDataType.SingleLineTextArea,ie.CustomControlDataType.Multiple],lookup:[ie.CustomControlDataType.LookupSimple,ie.CustomControlDataType.LookupCustomer,ie.CustomControlDataType.LookupOwner,ie.CustomControlDataType.LookupPartyList,ie.CustomControlDataType.LookupRegarding],dates:[ie.CustomControlDataType.DateAndTimeDateOnly,ie.CustomControlDataType.DateAndTimeDateAndTime],allFields:[ie.CustomControlDataType.TwoOptions,ie.CustomControlDataType.DateAndTimeDateOnly,ie.CustomControlDataType.DateAndTimeDateAndTime,ie.CustomControlDataType.FP,ie.CustomControlDataType.Decimal,ie.CustomControlDataType.WholeNone,ie.CustomControlDataType.WholeDuration,ie.CustomControlDataType.WholeTimeZone,ie.CustomControlDataType.WholeLanguage,ie.CustomControlDataType.LookupSimple,ie.CustomControlDataType.LookupCustomer,ie.CustomControlDataType.LookupOwner,ie.CustomControlDataType.LookupPartyList,ie.CustomControlDataType.LookupRegarding,ie.CustomControlDataType.Multiple,ie.CustomControlDataType.OptionSet,ie.CustomControlDataType.SingleLineText,ie.CustomControlDataType.SingleLineTextArea,ie.CustomControlDataType.SingleLineEmail,ie.CustomControlDataType.SingleLineURL,ie.CustomControlDataType.SingleLineTickerSymbol,ie.CustomControlDataType.SingleLinePhone]};var pie="Phone";function mie(e,t,n){switch(e){case Je.EntityAttributeType.TwoOptions:return[ie.CustomControlDataType.TwoOptions,ie.CustomControlDataType.Boolean];case Je.EntityAttributeType.Customer:case Je.EntityAttributeType.CustomerType:return[ie.CustomControlDataType.LookupCustomer];case Je.EntityAttributeType.DateTime:return t===Je.EntityAttributeTypeFormat.DateAndTime?[ie.CustomControlDataType.DateAndTimeDateAndTime]:[ie.CustomControlDataType.DateAndTimeDateOnly];case Je.EntityAttributeType.DecimalNumber:return[ie.CustomControlDataType.Decimal];case Je.EntityAttributeType.FloatingPointNumber:return[ie.CustomControlDataType.FP];case Je.EntityAttributeType.File:return[ie.CustomControlDataType.File];case Je.EntityAttributeType.Image:return[ie.CustomControlDataType.Image];case Je.EntityAttributeType.WholeNumber:return t===Je.EntityAttributeTypeFormat.Duration?[ie.CustomControlDataType.WholeDuration]:t===Je.EntityAttributeTypeFormat.Language?[ie.CustomControlDataType.WholeLanguage]:t===Je.EntityAttributeTypeFormat.TimeZone?[ie.CustomControlDataType.WholeTimeZone]:[ie.CustomControlDataType.WholeNone];case Je.EntityAttributeType.LookupType:case Je.EntityAttributeType.Lookup:return t===Je.EntityAttributeTypeFormat.Regarding?[ie.CustomControlDataType.LookupRegarding]:[ie.CustomControlDataType.LookupSimple];case Je.EntityAttributeType.MultipleLineofText:return[ie.CustomControlDataType.Multiple];case Je.EntityAttributeType.Currency:return[ie.CustomControlDataType.Currency];case Je.EntityAttributeType.Owner:case Je.EntityAttributeType.OwnerType:return[ie.CustomControlDataType.LookupOwner];case Je.EntityAttributeType.PartyList:case Je.EntityAttributeType.PartyListType:return[ie.CustomControlDataType.LookupPartyList];case Je.EntityAttributeType.Status:case Je.EntityAttributeType.OptionSet:return[ie.CustomControlDataType.OptionSet];case Je.EntityAttributeType.SingleLineofText:switch(t){case Je.EntityAttributeTypeFormat.Email:return[ie.CustomControlDataType.SingleLineEmail];case Je.EntityAttributeTypeFormat.Phone:return[ie.CustomControlDataType.SingleLinePhone];case Je.EntityAttributeTypeFormat.Text:return n===pie?[ie.CustomControlDataType.SingleLinePhone]:[ie.CustomControlDataType.SingleLineText];case Je.EntityAttributeTypeFormat.TextArea:return[ie.CustomControlDataType.SingleLineTextArea];case Je.EntityAttributeTypeFormat.TickerSymbol:return[ie.CustomControlDataType.SingleLineTickerSymbol];case Je.EntityAttributeTypeFormat.Url:return[ie.CustomControlDataType.SingleLineURL];default:return[ie.CustomControlDataType.SingleLineText]}case Je.EntityAttributeType.MultiSelectOptionSet:return[ie.CustomControlDataType.MultiSelectOptionSet];default:return null}}vn.manifestTypesForColumn=mie;function RA(e){let t=[],n=e.childNodes;for(let r=0;r<n.length;r+=1)n[r].nodeType===1&&t.push(n[r]);return t}vn.elementChildren=RA;function Ao(e,t){return e.hasAttribute(t)?e.getAttribute(t):null}vn.attr=Ao;function la(e,...t){return RA(e).filter(n=>t.includes(n.tagName))}vn.firstLevel=la;function hie(e){let t=new Map;for(let n of la(e,"type-group"))t.set(String(Ao(n,"name")),la(n,"type").map(r=>String(r.textContent)));for(let[n,r]of t)t.set(n,r.sort());return t}function gie(e){let t=e.getElementsByTagName("AvailableOn")[0];if(!t)return{web:!0,phone:!0,tablet:!0};let n=new Set(RA(t).map(r=>r.tagName));return{web:n.has("web"),phone:n.has("phone"),tablet:n.has("tablet")}}var yie={input:"input",bound:"bound",output:"output"};function bie(e,t,n){let r=Ao(e,"usage"),i=r!==null&&yie[r]||"input",o=Ao(e,"default-value"),a=la(e,"value").map(p=>{let m={name:Ao(p,"name"),value:String(p.textContent),isDefault:Ao(p,"default")==="true"};return m.isDefault&&(o=m.value),m}),s=Ao(e,"of-type-group"),u=s!==null?t.get(s):void 0,l=s!==null&&Object.prototype.hasOwnProperty.call(vn.DEFAULT_TYPE_GROUPS,s)?vn.DEFAULT_TYPE_GROUPS[s]:void 0,c=u?[...u]:l?[...l]:[],d=Ao(e,"of-type"),f=d!==null?d:c.length>0?c[0]:null;return{name:Ao(e,"name"),usage:i,ofType:d,typeGroupName:s,ofTypeGroup:c,defaultType:f||void 0,required:Ao(e,"required")==="true",hidden:Ao(e,"hidden")==="true",defaultValue:o,enumValues:a,isPrimary:n&&i==="bound"}}function dM(e){var t;let n=[],r=a=>s=>n.push(`${a}: ${s}`),i=new fie.DOMParser({errorHandler:{warning:r("warning"),error:r("error"),fatalError:r("fatalError")}}).parseFromString(e,"text/xml"),o=(t=i?.documentElement)!==null&&t!==void 0?t:null;if(!o||n.length>0)throw new Error(`the control manifest does not parse cleanly${n.length>0?` (${n[0]})`:""}`);return o}vn.parseManifestRoot=dM;function fM(e){let t=la(dM(e),"control")[0];if(!t)throw new Error("the control manifest has no <control> element");return t}vn.parseControlElement=fM;function vie(e){let t=fM(e),n=hie(t),r=la(t,"data-set"),i=la(t,"property"),o=la(t,"groups"),a=[],s=!1;for(let l of i){let c=bie(l,n,r.length===0&&!s);s=s||c.isPrimary,a.push(c)}let u=r.length>0||(a.length>0?a[0].usage==="bound":o.some(l=>la(l,"group").some(c=>la(c,"data-set","property").length>0)));return{properties:a,hasDataset:r.length>0,hasGroups:o.length>0,isBound:u,availableOn:gie(t)}}vn.parsePcfManifest=vie});var mM=C(Uc=>{"use strict";Object.defineProperty(Uc,"__esModule",{value:!0});Uc.readPcfColumn=Uc.readControlManifest=void 0;var Fc=ae(),wie=kA();function $A(e,t,n){var r;let i=(r=n?.error)===null||r===void 0?void 0:r.message;return new Error(`${e}: HTTP ${t}${typeof i=="string"?` ${i}`:""}`)}async function Eie(e,t){var n;let r="/customcontrols"+(0,Fc.odataQuery)([["$select","name,manifest"],["$filter",`name eq '${(0,Fc.odataLiteral)(t)}'`]]);try{let i=await e.get(r);if(i.status<200||i.status>=300)return{kind:"unavailable",error:$A(`reading control "${t}"`,i.status,i.body)};let o=(n=i.body)===null||n===void 0?void 0:n.value;if(!Array.isArray(o)||o.some(u=>u===null||typeof u!="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,wie.parsePcfManifest)(s)}}catch(i){return{kind:"unavailable",error:i instanceof Error?i:new Error(String(i))}}}Uc.readControlManifest=Eie;var Aie=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 pM(e){let t=e?.Value;return typeof t=="string"?t:void 0}async function Cie(e,t,n,r){var i;let o=`/EntityDefinitions(LogicalName='${(0,Fc.odataPathLiteral)(t)}')/Attributes(LogicalName='${(0,Fc.odataPathLiteral)(n)}')`,a=r?.requireCreateEligibility===!0;try{let s=await e.get(o+(0,Fc.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:$A(`reading column "${n}"`,s.status,s.body)};let u=(i=s.body)!==null&&i!==void 0?i:{},l=pM(u.AttributeTypeName);if(!l)return{kind:"unavailable",error:new Error(`column "${n}" has no AttributeTypeName`)};if(a&&typeof u.IsValidForCreate!="boolean")return{kind:"unavailable",error:new Error(`column "${n}" has no IsValidForCreate`)};let c={logicalName:typeof u.LogicalName=="string"?u.LogicalName:n,attributeTypeName:l,isValidForForm:u.IsValidForForm===!0,isPrimaryId:u.IsPrimaryId===!0,...a?{isValidForCreate:u.IsValidForCreate}:{}},d=Aie.get(l);if(d){let f=await e.get(`${o}/Microsoft.Dynamics.CRM.${d.cast}`+(0,Fc.odataQuery)([["$select",d.select]]));if(f.status<200||f.status>=300)return{kind:"unavailable",error:$A(`reading the format of column "${n}"`,f.status,f.body)};let p=f.body;if(p===null||typeof p!="object"||p.Format!==null&&typeof p.Format!="string")return{kind:"unavailable",error:new Error(`reading the format of column "${n}": the answer is unreadable \u2014 expected its Format (a string or null)`)};typeof p.Format=="string"&&(c.format=p.Format);let m=pM(p.FormatName);m&&(c.formatName=m)}return{kind:"found",value:c}}catch(s){return{kind:"unavailable",error:s instanceof Error?s:new Error(String(s))}}}Uc.readPcfColumn=Cie});var fl=C(n0=>{"use strict";Object.defineProperty(n0,"__esModule",{value:!0});n0.DEFAULT_LCID=void 0;n0.DEFAULT_LCID=1033});var r0=C(qc=>{"use strict";Object.defineProperty(qc,"__esModule",{value:!0});qc.fnv128Hex=qc.fnv32=void 0;function hM(e){let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return t>>>0}qc.fnv32=hM;function Sie(e,t){let n="";for(let r=0;r<4;r+=1)n+=hM(`${r}:${e}:${t}`).toString(16).padStart(8,"0");return n}qc.fnv128Hex=Sie});var LA=C(Bc=>{"use strict";Object.defineProperty(Bc,"__esModule",{value:!0});Bc.deterministicId=Bc.fnv32=void 0;var Nie=r0(),_ie=r0();Object.defineProperty(Bc,"fnv32",{enumerable:!0,get:function(){return _ie.fnv32}});function Iie(e,t){let n=(0,Nie.fnv128Hex)(e,t);return`${n.slice(0,8)}-${n.slice(8,12)}-${n.slice(12,16)}-${n.slice(16,20)}-${n.slice(20,32)}`}Bc.deterministicId=Iie});var o0=C(Me=>{"use strict";Object.defineProperty(Me,"__esModule",{value:!0});Me.profileTokenFor=Me.parseProfileToken=Me.composeProfileToken=Me.readPermissionRows=Me.canonicalGuid=Me.toFieldPermission=Me.ALLOWED=Me.NOT_ALLOWED=Me.PERMISSION_SELECT=Me.FIELD_SECURITY_PROFILE_PLATFORM_MANAGED_CODE=Me.FIELD_SECURITY_PROFILE_PUSH_NOT_ATOMIC_CODE=Me.FIELD_SECURITY_COLUMN_NOT_SECURED_CODE=Me.FIELD_PERMISSION_UNRECOGNIZED_CODE=Me.SYSTEM_ADMINISTRATOR_FIELD_SECURITY_PROFILE_ID=void 0;var i0=Y(),Tie=LA(),MA=pe(),yM=ae();Me.SYSTEM_ADMINISTRATOR_FIELD_SECURITY_PROFILE_ID="572329c1-a042-4e22-be47-367c6374ea45";Me.FIELD_PERMISSION_UNRECOGNIZED_CODE="FIELD_PERMISSION_UNRECOGNIZED";Me.FIELD_SECURITY_COLUMN_NOT_SECURED_CODE="FIELD_SECURITY_COLUMN_NOT_SECURED";Me.FIELD_SECURITY_PROFILE_PUSH_NOT_ATOMIC_CODE="FIELD_SECURITY_PROFILE_PUSH_NOT_ATOMIC";Me.FIELD_SECURITY_PROFILE_PLATFORM_MANAGED_CODE="FIELD_SECURITY_PROFILE_PLATFORM_MANAGED";Me.PERMISSION_SELECT="fieldpermissionid,entityname,attributelogicalname,canread,cancreate,canupdate,canreadunmasked";Me.NOT_ALLOWED=0;Me.ALLOWED=4;var Oie=new Map([[0,"none"],[1,"oneRecord"],[3,"allRecords"]]);function gM(e,t,n,r,i){var o;return new i0.SdkError(Me.FIELD_PERMISSION_UNRECOGNIZED_CODE,`Field security profile '${e.profileId}': the permission for ${t}.${n} has ${r} = ${(o=JSON.stringify(i))!==null&&o!==void 0?o:"undefined"}, which this SDK cannot represent (accepted: ${r==="canreadunmasked"?"0, 1, 3":"0, 4"}). Refusing rather than misreport the access.`)}function bM(e,t){for(let r of["canread","cancreate","canupdate"])if(e[r]!==Me.NOT_ALLOWED&&e[r]!==Me.ALLOWED)throw gM(t,e.table,e.column,r,e[r]);let n=Oie.get(e.canreadunmasked);if(n===void 0)throw gM(t,e.table,e.column,"canreadunmasked",e.canreadunmasked);return{table:e.table,column:e.column,read:e.canread===Me.ALLOWED,create:e.cancreate===Me.ALLOWED,update:e.canupdate===Me.ALLOWED,...n!=="none"?{readUnmasked:n}:{},id:e.id}}Me.toFieldPermission=bM;var Die=/^[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 Pie(e){if(typeof e=="string")try{return(0,yM.normalizeGuid)(e,"id")}catch{return}}Me.canonicalGuid=Pie;function Rie(e,t,n){let r=[],i=new Set,o=new Set;for(let a of e){let s=a??{},u=s.fieldpermissionid,l=s["@odata.etag"],c=s.entityname,d=s.attributelogicalname;if(typeof u!="string"||!Die.test(u)||!(0,MA.isVersionToken)(l))throw new i0.ConnectionError(n,200,`the permissions of field security profile '${t.profileId}' could not be read: a row has no usable id or version`);if(typeof c!="string"||c===""||typeof d!="string"||d==="")throw new i0.ConnectionError(n,200,`the permissions of field security profile '${t.profileId}' could not be read: a row names no table or column`);let f=(0,yM.normalizeGuid)(u,"fieldpermissionid"),p=`${c}\0${d}`;if(i.has(f)||o.has(p))throw new i0.ConnectionError(n,200,`the permissions of field security profile '${t.profileId}' were read inconsistently: ${i.has(f)?`the row '${f}'`:`the column ${c}.${d}`} appears twice`);i.add(f),o.add(p);let m={id:f,token:l,table:c,column:d,canread:s.canread,cancreate:s.cancreate,canupdate:s.canupdate,canreadunmasked:s.canreadunmasked};bM(m,t),r.push(m)}return r}Me.readPermissionRows=Rie;var kie="fieldSecurityProfile.permissions";function $ie(e){return Object.keys(e).map(t=>[t.toLowerCase(),e[t]]).sort(([t],[n])=>t<n?-1:t>n?1:0).map(([t,n])=>`${t}=${n}`).join(`+`)}function vM(e,t){return`${e} fp${Object.keys(t).length}:${(0,Tie.deterministicId)(kie,$ie(t))}`}Me.composeProfileToken=vM;function wM(e){if(typeof e!="string")return;let t=e.split(" ");if(t.length!==2||!(0,MA.isVersionToken)(t[0]))return;let n=/^fp(0|[1-9][0-9]*):([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/.exec(t[1]);if(n)return{profileToken:t[0],count:Number(n[1]),digest:n[2]}}Me.parseProfileToken=wM;function Lie(e,t){let n=wM(e);if(!n||!t)return;let r=Object.entries(t);return r.length!==n.count||r.some(([,o])=>!(0,MA.isVersionToken)(o))?void 0:vM(n.profileToken,t)===e?n.profileToken:void 0}Me.profileTokenFor=Lie});var s0=C(Qi=>{"use strict";Object.defineProperty(Qi,"__esModule",{value:!0});Qi.readColumnPermissionHolders=Qi.findFieldSecurityProfile=Qi.resolveFieldSecurityProfiles=Qi.fieldSecurityProfileApi=Qi.readFieldPermissions=void 0;var EM=Zo(),Sp=Ke(),Tn=Y(),wr=pe(),Br=ae(),Er=o0(),pl="fieldsecurityprofiles",Cp="fieldpermissions",Ep="lk_fieldpermission_fieldsecurityprofileid",Ap={Prefer:"return=representation"},Mie=/^[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 Np(e){return(0,wr.isVersionToken)(e)&&!e.includes(" ")}function FA(e){return new Tn.SdkError(Er.FIELD_SECURITY_PROFILE_PLATFORM_MANAGED_CODE,`Refusing to ${e} the System Administrator field security profile: it is platform-managed configuration (the platform adds a full-access permission to it for every column it secures). It can be fetched, not written. Nothing was sent.`)}function UA(e){var t;let n=(t=e?.error)===null||t===void 0?void 0:t.code;return typeof n=="string"?n.toLowerCase():void 0}function xie(e){var t;let n=(t=e?.error)===null||t===void 0?void 0:t.message;return typeof n=="string"?n:""}function CM(e,t){var n,r;let i=(r=/for attribute (\S+) with id/i.exec(xie((n=e?.cause)!==null&&n!==void 0?n:e)))===null||r===void 0?void 0:r[1],o=t.filter(s=>s.column===i),a=(o.length===1?o:t).map(s=>`${s.table}.${s.column}`).join(", ");return(0,Tn.attachCause)(new Tn.SdkError(Er.FIELD_SECURITY_COLUMN_NOT_SECURED_CODE,`A field permission names a column that is not secured (${a}); the platform refused the write and nothing was written. Secure the column first \u2014 updateColumn(table, column, { isSecured: true }) \u2014 then push again.`),e)}async function a0(e,t){let n=`/${Cp}${(0,Br.odataQuery)([["$select",Er.PERMISSION_SELECT],["$filter",`_fieldsecurityprofileid_value eq ${t}`],["$orderby","fieldpermissionid"]])}`,r=await(0,Sp.collectPages)(e,n,`the permissions of field security profile '${t}'`);return(0,Er.readPermissionRows)(r,{profileId:t},e.apiUrl(n))}Qi.readFieldPermissions=a0;function xA(e){return Object.fromEntries(e.map(t=>[t.id,t.token]))}function AM(e,t){let n=Object.keys(e);return n.length===Object.keys(t).length&&n.every(r=>Object.prototype.hasOwnProperty.call(t,r)&&t[r]===e[r])}var Fie="Saved, but the profile's permissions on the server could not be proven equal to what was pushed (a schema change \u2014 unsecuring a column, or deleting a column or table \u2014 removes a permission without moving the profile\u2019s version). No version is held for it now: re-fetch it (fetchArtifact) before the next push.";function SM(e){let t=n=>{var r;return(r=(0,Er.canonicalGuid)(n))!==null&&r!==void 0?r:n.toLowerCase()};return{profile:e.profile,creates:e.creates.map(n=>({...n,id:t(n.id)})),updates:e.updates.map(n=>({...n,id:t(n.id)})),deletes:e.deletes.map(n=>({...n,id:t(n.id)}))}}async function Uie(e,t,n){var r,i;let o=(0,Br.normalizeGuid)(t,"id");if(o===Er.SYSTEM_ADMINISTRATOR_FIELD_SECURITY_PROFILE_ID)throw FA("delete");let a=(0,Er.parseProfileToken)(n?.token),s=(r=n?.snapshot)===null||r===void 0?void 0:r.permissions;if(!a||!Array.isArray(s)||s.length!==a.count)throw new Tn.SdkError(wr.DELETE_NO_ETAG_CODE,`Refusing to delete fieldSecurityProfile '${o}': no usable concurrency token is held for it, so the delete could not be made conditional and could remove what another writer changed. Fetch it first (fetchArtifact).`);let u=`/${pl}(${o})`,l=await e.delete(u,{headers:{"If-Match":a.profileToken}});if(l.status===412)throw new Tn.VersionConflictError("fieldSecurityProfile",o,(i=n?.token)!==null&&i!==void 0?i:null,null,"Another writer changed the profile or one of its permissions since it was fetched; nothing was deleted.");if(UA(l.body)==="0x8004f01f")throw new Tn.ArtifactInUseError("fieldSecurityProfile",o,`Refusing to delete fieldSecurityProfile '${o}': another component depends on it; nothing was deleted.`);(0,wr.ensureSuccess)(l,e.apiUrl(u))}async function qie(e,t,n){var r,i;let o=(0,Br.normalizeGuid)(n??"","fieldsecurityprofileid");if(o===Er.SYSTEM_ADMINISTRATOR_FIELD_SECURITY_PROFILE_ID)throw FA("create");let a=SM(t),s={fieldsecurityprofileid:o,name:a.profile.name,...a.profile.description!==void 0&&a.profile.description!==null?{description:a.profile.description}:{},[Ep]:a.creates.map(m=>({fieldpermissionid:m.id,entityname:m.table,attributelogicalname:m.column,canread:m.canread,cancreate:m.cancreate,canupdate:m.canupdate}))},u=`/${pl}${(0,Br.odataQuery)([["$select","name,description"],["$expand",`${Ep}($select=fieldpermissionid,entityname,attributelogicalname,canread,cancreate,canupdate,canreadunmasked)`]])}`,l;try{l=(0,wr.ensureSuccess)(await e.post(u,s,{headers:Ap}),e.apiUrl(u))}catch(m){throw m instanceof Tn.ConnectionError&&UA(m.cause)==="0x8004f508"?CM(m,a.creates):m}let c=(r=l.body)!==null&&r!==void 0?r:{},d=c[Ep],f={},p=Np((0,wr.readEtag)(l))&&Array.isArray(d)&&d.length===a.creates.length;if(p=p&&c[`${Ep}@odata.nextLink`]===void 0,p){let m=new Map(a.creates.map(h=>[h.id,h]));for(let h of d){if(!h||typeof h!="object"||Array.isArray(h)){p=!1;break}let g=h,y=(i=(0,Er.canonicalGuid)(g.fieldpermissionid))!==null&&i!==void 0?i:"",b=m.get(y),E=g["@odata.etag"];if(!b||Object.prototype.hasOwnProperty.call(f,y)||!Np(E)||g.entityname!==b.table||g.attributelogicalname!==b.column||g.canread!==b.canread||g.cancreate!==b.cancreate||g.canupdate!==b.canupdate){p=!1;break}f[y]=E}}return p?{id:o,etag:(0,Er.composeProfileToken)((0,wr.readEtag)(l),f),memberEtags:f}:{id:o,etag:null,warnings:["Saved; the create's answer did not account for every permission, so no version is held for the profile \u2014 re-fetch it (fetchArtifact) before the next push."]}}function Bie(e,t,n){var r,i;if(!(e instanceof Tn.ConnectionError))return e;let o=UA(e.cause),a=(i=(r=/\/fieldpermissions\(([^)]+)\)/.exec(e.url))===null||r===void 0?void 0:r[1])===null||i===void 0?void 0:i.toLowerCase();if(e.statusCode===404&&o==="0x80040217"&&a){let u=[...t.updates,...t.deletes].find(l=>l.id.toLowerCase()===a);if(u)return(0,Tn.attachCause)(new Tn.SdkError(wr.VERSION_CONFLICT_CODE,`The permission for ${u.table}.${u.column} no longer exists on the server \u2014 a schema change (unsecuring its column, or deleting the column or table) removes it without moving the profile's version. Nothing was written; re-fetch.`),e)}if(o==="0x8004f508")return CM(e,t.creates);let s=/\/fieldpermissions$/i.test(e.url.split("?")[0]);return e.statusCode===400&&o==="0x80040203"&&s?(0,Tn.attachCause)(new Tn.SdkError(wr.VERSION_CONFLICT_CODE,`Another writer added a permission for a column this push creates in profile '${n}'. Nothing was written; re-fetch.`),e):e}async function Vie(e,t,n,r,i){let o=(0,Br.normalizeGuid)(t,"id");if(o===Er.SYSTEM_ADMINISTRATOR_FIELD_SECURITY_PROFILE_ID)throw FA("push");let a=SM(n),s=(0,Er.profileTokenFor)(r,i);if(!s||!i)throw new Tn.SdkError(wr.UPDATE_NO_ETAG_CODE,`Refusing to push fieldSecurityProfile '${o}': no usable concurrency token is held for it (none, or one that does not describe the held permission versions), so the write could not be made conditional. Re-fetch the fieldSecurityProfile and re-apply the change.`);let u=a.creates.length+a.updates.length+a.deletes.length>0;if(u&&!e.supportsAtomicBatch)throw new Tn.SdkError(Er.FIELD_SECURITY_PROFILE_PUSH_NOT_ATOMIC_CODE,`Refusing to push fieldSecurityProfile '${o}': changing its permissions is ONE atomic change set, which needs an HttpClient that implements postRaw. Nothing was sent. (A create, or a change to the name or description only, needs no change set.)`);let l=await a0(e,o);if(!AM(xA(l),i))throw new Tn.SdkError(wr.VERSION_CONFLICT_CODE,"The profile's permissions changed since it was fetched \u2014 another writer, or a schema change that removes a permission without moving the profile's version. Nothing was written; re-fetch.");let c={...i},d,f=`/${pl}(${o})`,p=`${f}${(0,Br.odataQuery)([["$select","fieldsecurityprofileid"]])}`;if(u){let y=(0,Br.odataQuery)([["$select","fieldpermissionid"]]),b=[{method:"PATCH",path:f,body:a.profile,etag:s},...a.deletes.map(T=>{var O;return{method:"DELETE",path:`/${Cp}(${T.id})`,etag:(O=i[T.id])!==null&&O!==void 0?O:void 0}}),...a.updates.map(T=>{var O;return{method:"PATCH",path:`/${Cp}(${T.id})${y}`,body:T.set,etag:(O=i[T.id])!==null&&O!==void 0?O:void 0,headers:Ap}}),...a.creates.map(T=>({method:"POST",path:`/${Cp}${y}`,body:{fieldpermissionid:T.id,entityname:T.table,attributelogicalname:T.column,canread:T.canread,cancreate:T.cancreate,canupdate:T.canupdate,"[email protected]":`/${pl}(${o})`},headers:Ap})),{method:"PATCH",path:p,body:{},headers:Ap}],E;try{E=await(0,EM.sendChangeSet)(e,b,`field security profile '${o}'`)}catch(T){throw Bie(T,a,o)}let w=E.map(T=>(0,wr.readEtag)((0,EM.partResponse)(T)));for(let T of a.deletes)delete c[T.id];let _=1+a.deletes.length;a.updates.forEach((T,O)=>{c[T.id]=w[_+O]});let I=_+a.updates.length;a.creates.forEach((T,O)=>{c[T.id]=w[I+O]}),d=w[w.length-1]}else{let y=(0,wr.ensureSuccess)(await e.patch(p,a.profile,{headers:{...Ap,"If-Match":s}}),e.apiUrl(p));d=(0,wr.readEtag)(y)}let m=Np(d)&&Object.values(c).every(y=>Np(y)),h=!1;if(m)try{h=AM(xA(await a0(e,o)),c)}catch{h=!1}if(!h)return{id:o,etag:null,warnings:[Fie]};let g=c;return{id:o,etag:(0,Er.composeProfileToken)(d,g),memberEtags:g}}Qi.fieldSecurityProfileApi={async get(e,t){var n;let r=(0,Br.normalizeGuid)(t,"id"),i=`/${pl}(${r})${(0,Br.odataQuery)([["$select","name,description"]])}`,o=(0,wr.ensureSuccess)(await e.get(i),e.apiUrl(i)),a=(0,wr.readEtag)(o),s=await a0(e,r),u=(n=o.body)!==null&&n!==void 0?n:{},l={fieldsecurityprofileid:r,name:typeof u.name=="string"?u.name:"",description:typeof u.description=="string"?u.description:null,[Ep]:s.map(d=>({fieldpermissionid:d.id,entityname:d.table,attributelogicalname:d.column,canread:d.canread,cancreate:d.cancreate,canupdate:d.canupdate,canreadunmasked:d.canreadunmasked}))},c=xA(s);return{raw:l,etag:Np(a)?(0,Er.composeProfileToken)(a,c):null,memberEtags:c}},async list(e){let t=`/${pl}${(0,Br.odataQuery)([["$select","fieldsecurityprofileid,name"]])}`;return(await(0,Sp.collectPages)(e,t,"listArtifacts('fieldSecurityProfile')")).map(r=>{var i,o;return{type:"fieldSecurityProfile",id:String((i=r.fieldsecurityprofileid)!==null&&i!==void 0?i:""),name:String((o=r.name)!==null&&o!==void 0?o:""),isDirty:!1}})},create(e,t,n){return qie(e,t,n)},update(e,t,n,r,i){return Vie(e,t,n,r,i)},delete(e,t,n){return Uie(e,t,n)}};async function NM(e,t,n){let r=`/${pl}${(0,Br.odataQuery)([["$select","fieldsecurityprofileid,name"],["$filter",`name eq '${(0,Br.odataLiteral)(t)}'`],...n!==void 0?[["$top",String(n)]]:[]])}`,i=e.apiUrl(r),o;if(n===void 0)o=await(0,Sp.collectPages)(e,r,"resolveArtifact('fieldSecurityProfile')");else{let a=(0,wr.ensureSuccess)(await e.get(r),i).body;if(o=a?.value,Array.isArray(o)&&!(0,Sp.boundedPageComplete)(a,o.length,n))throw new Tn.ConnectionError(i,200,"the list of field security profiles is incomplete (the answer says more rows exist), so it proves neither absence nor a single match")}if(!Array.isArray(o))throw new Tn.ConnectionError(i,200,"the response could not be read as a list of field security profiles");return o.map(a=>({id:String(a.fieldsecurityprofileid),name:String(a.name)}))}Qi.resolveFieldSecurityProfiles=NM;async function Gie(e,t){let n=await NM(e,t,2);if(n.length>1)throw new Tn.AmbiguousArtifactError("fieldSecurityProfile",t,n.length);return n.length===1?n[0].id:null}Qi.findFieldSecurityProfile=Gie;async function jie(e,t,n){let r=`/${Cp}${(0,Br.odataQuery)([["$select","fieldpermissionid,_fieldsecurityprofileid_value"],["$filter",`entityname eq '${(0,Br.odataLiteral)(t)}' and attributelogicalname eq '${(0,Br.odataLiteral)(n)}'`],["$orderby","fieldpermissionid"]])}`,i=await(0,Sp.collectPages)(e,r,`the field permissions on ${t}.${n}`),o=new Set;for(let a of i){let s=a?._fieldsecurityprofileid_value;if(typeof a?.fieldpermissionid!="string"||typeof s!="string"||!Mie.test(s))throw new Tn.ConnectionError(e.apiUrl(r),200,`the field permissions on ${t}.${n} could not be classified (a row has no readable profile), so whether unsecuring it would delete another profile\u2019s permission is unknown`);let u=s.toLowerCase();u!==Er.SYSTEM_ADMINISTRATOR_FIELD_SECURITY_PROFILE_ID&&o.add(u)}return[...o]}Qi.readColumnPermissionHolders=jie});var u0=C(Ce=>{"use strict";Object.defineProperty(Ce,"__esModule",{value:!0});Ce.updateTable=Ce.deleteAlternateKey=Ce.createAlternateKey=Ce.deleteGlobalOptionSet=Ce.createGlobalOptionSet=Ce.deleteRelationship=Ce.deleteColumn=Ce.updateColumn=Ce.deleteTable=Ce.createRelationship=Ce.insertStatusValue=Ce.createCustomerColumn=Ce.createColumns=Ce.setColumnVisualization=Ce.getColumnVisualization=Ce.createColumn=Ce.createTable=Ce.resolveUpsertTarget=Ce.resolveEntitySetName=Ce.pluralFallback=void 0;var nt=pe(),he=ae(),ca=fl(),de=Y(),Wie=Zo(),zie=s0(),Hie={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 ln(e,t){return{"@odata.type":"Microsoft.Dynamics.CRM.Label",LocalizedLabels:Kie(e,t)}}var _M=65535;function Kie(e,t){let n=(o,a)=>({"@odata.type":"Microsoft.Dynamics.CRM.LocalizedLabel",Label:o,LanguageCode:a});if(typeof e=="string")return[n(e,t)];let r=Object.entries(e);if(!r.length)throw new de.InvalidArgumentError("a localized label must contain at least one language");let i=new Set;return r.map(([o,a])=>{if(!/^[1-9]\d*$/.test(o))throw new de.InvalidArgumentError(`localized label key '${o}' is not an LCID (expected a canonical positive integer, e.g. 1033)`);let s=Number(o);if(s>_M)throw new de.InvalidArgumentError(`localized label LCID ${s} is out of range (1-${_M})`);if(i.has(s))throw new de.InvalidArgumentError(`localized label LCID ${s} is specified more than once`);if(i.add(s),typeof a!="string")throw new de.InvalidArgumentError(`localized label for LCID ${s} must be a string`);return n(a,s)})}function PM(e){return typeof e=="string"?`${e}s`:Object.fromEntries(Object.entries(e).map(([t,n])=>{if(typeof n!="string")throw new de.InvalidArgumentError(`localized label for LCID ${t} must be a string`);return[t,`${n}s`]}))}Ce.pluralFallback=PM;function _p(e){return{Value:e,CanBeChanged:!0,ManagedPropertyLogicalName:"canmodifyrequirementlevelsettings"}}var IM=["None","ApplicationRequired","Recommended"];function GA(e){let t=e.indexOf("_");return t>0?e.slice(0,t):e}function TM(e,t,n){let r=e[t];r&&typeof r=="object"?r.Value=n:e[t]={Value:n}}function Ip(e){let t=(0,nt.readCreatedId)(e,"MetadataId");if(!t)throw new de.InvalidArgumentError("Dataverse did not return a MetadataId for the created metadata component");return t}var BA=["UserLocal","DateOnly","TimeZoneIndependent"];function RM(e,t){if(!BA.includes(e))throw new de.InvalidArgumentError(`${t}: dateTimeBehavior '${String(e)}' is not one of ${BA.join(", ")}.`);return e}function Jie(e,t,n,r){var i;let o=`'${n}' on '${r}'`,a=e.DateTimeBehavior,s="unreadable";if(a===null?s="missing":a&&typeof a=="object"&&BA.includes(a.Value)&&(s=a.Value),s==="unreadable")throw new de.InvalidArgumentError(`updateColumn: the current DateTimeBehavior of ${o} could not be read, so the SDK will not change it.`);if(s!==t){let u=(i=e.CanChangeDateTimeBehavior)===null||i===void 0?void 0:i.Value;if(u!==!0)throw new de.InvalidArgumentError(typeof u=="boolean"?`updateColumn: CanChangeDateTimeBehavior is false on ${o}; Learn requires it to be true for any change of behaviour, a repair included.`:`updateColumn: CanChangeDateTimeBehavior of ${o} could not be read, so the SDK will not change its behaviour (Learn requires it to be true).`);if(s!=="missing"&&s!=="UserLocal")throw new de.InvalidArgumentError(`updateColumn: ${o} is ${s}, which cannot be changed \u2014 Learn documents DateOnly and TimeZoneIndependent as permanent; only UserLocal may become DateOnly or TimeZoneIndependent.`)}e.DateTimeBehavior={Value:t},t==="DateOnly"&&e.Format!=="DateOnly"&&(e.Format="DateOnly")}var Yie="0x80048550";async function jA(e,t,n){var r,i;let o=n instanceof de.ConnectionError?(i=(r=n.cause)===null||r===void 0?void 0:r.error)===null||i===void 0?void 0:i.code:void 0;if(!(n instanceof de.ConnectionError)||n.statusCode!==400||typeof o!="string"||o.toLowerCase()!==Yie)throw n;let a;try{a=await Qie(e,t)}catch{a=void 0}throw a&&a.length>0?(0,de.attachCause)(new de.DateTimeBehaviorMissingError(t,a),n):n}async function Qie(e,t){var n;let r=`/EntityDefinitions(LogicalName='${(0,he.odataPathLiteral)(t)}')/Attributes/Microsoft.Dynamics.CRM.DateTimeAttributeMetadata`+(0,he.odataQuery)([["$select","LogicalName,DateTimeBehavior"]]),i=await e.get(r);if(i.status<200||i.status>=300)return;let o=(n=i.body)===null||n===void 0?void 0:n.value;if(!Array.isArray(o))return;let a=[];for(let s of o){if(!s||typeof s!="object"||!Object.prototype.hasOwnProperty.call(s,"DateTimeBehavior"))return;let{LogicalName:u,DateTimeBehavior:l}=s;if(typeof u!="string"||u==="")return;l===null&&a.push(u)}return a}function Xie(e,t,n){var r,i,o,a,s,u,l,c,d,f,p,m,h,g,y,b,E,w,_,I,T,O,v,N;if(t.defaultValue!==void 0&&e!=="boolean")throw new de.InvalidArgumentError(`createColumn: 'defaultValue' applies to boolean columns, but '${t.schemaName}' is of type '${e}'.`);if(t.integerFormat!==void 0&&e!=="integer")throw new de.InvalidArgumentError(`createColumn: 'integerFormat' applies to integer columns, but '${t.schemaName}' is of type '${e}'.`);if(t.dateTimeBehavior!==void 0&&e!=="dateTime")throw new de.InvalidArgumentError(`createColumn: 'dateTimeBehavior' applies to dateTime 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:(r=t.maxLength)!==null&&r!==void 0?r: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:(u=t.maxValue)!==null&&u!==void 0?u:2147483647};case"bigint":return{"@odata.type":"Microsoft.Dynamics.CRM.BigIntAttributeMetadata",AttributeType:"BigInt",AttributeTypeName:{Value:"BigIntType"}};case"double":return{"@odata.type":"Microsoft.Dynamics.CRM.DoubleAttributeMetadata",AttributeType:"Double",AttributeTypeName:{Value:"DoubleType"},Precision:(l=t.precision)!==null&&l!==void 0?l:2,MinValue:(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:(y=t.maxValue)!==null&&y!==void 0?y:1e9};case"boolean":return{"@odata.type":"Microsoft.Dynamics.CRM.BooleanAttributeMetadata",AttributeType:"Boolean",AttributeTypeName:{Value:"BooleanType"},DefaultValue:(b=t.defaultValue)!==null&&b!==void 0?b:!1,OptionSet:{"@odata.type":"Microsoft.Dynamics.CRM.BooleanOptionSetMetadata",TrueOption:{Value:1,Label:ln((E=t.trueLabel)!==null&&E!==void 0?E:"Yes",n)},FalseOption:{Value:0,Label:ln((w=t.falseLabel)!==null&&w!==void 0?w:"No",n)}}};case"dateTime":{let S=t.dateTimeBehavior===void 0?"UserLocal":RM(t.dateTimeBehavior,"createColumn");if(S==="DateOnly"&&t.dateFormat==="DateAndTime")throw new de.InvalidArgumentError(`createColumn: dateTimeBehavior 'DateOnly' needs dateFormat 'DateOnly', but '${t.schemaName}' asks for 'DateAndTime' \u2014 Dataverse refuses that pair.`);return{"@odata.type":"Microsoft.Dynamics.CRM.DateTimeAttributeMetadata",AttributeType:"DateTime",AttributeTypeName:{Value:"DateTimeType"},Format:(_=t.dateFormat)!==null&&_!==void 0?_:S==="DateOnly"?"DateOnly":"DateAndTime",DateTimeBehavior:{Value:S}}}case"choice":return OM(t,n,!1);case"multiChoice":return OM(t,n,!0);case"file":return{"@odata.type":"Microsoft.Dynamics.CRM.FileAttributeMetadata",AttributeType:"Virtual",AttributeTypeName:{Value:"FileType"},MaxSizeInKB:(I=t.maxSizeKb)!==null&&I!==void 0?I:10240};case"image":return{"@odata.type":"Microsoft.Dynamics.CRM.ImageAttributeMetadata",AttributeType:"Virtual",AttributeTypeName:{Value:"ImageType"},IsPrimaryImage:(T=t.isPrimaryImage)!==null&&T!==void 0?T:!1,MaxSizeInKB:(O=t.maxSizeKb)!==null&&O!==void 0?O:10240};case"autonumber":if(!(!((v=t.autoNumberFormat)===null||v===void 0)&&v.trim()))throw new de.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:(N=t.maxLength)!==null&&N!==void 0?N:100,AutoNumberFormat:t.autoNumberFormat};default:throw new de.InvalidArgumentError(`unsupported column type '${String(e)}'`)}}function OM(e,t,n){let i={"@odata.type":n?"Microsoft.Dynamics.CRM.MultiSelectPicklistAttributeMetadata":"Microsoft.Dynamics.CRM.PicklistAttributeMetadata",AttributeType:n?"Virtual":"Picklist",AttributeTypeName:{Value:n?"MultiSelectPicklistType":"PicklistType"}};if(e.globalChoiceMetadataId)return i["[email protected]"]=`/GlobalOptionSetDefinitions(${(0,he.normalizeGuid)(e.globalChoiceMetadataId,"globalChoiceMetadataId")})`,i;if(!e.options||e.options.length===0)throw new de.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:ln(o.label,t)}))},i}var Vc=new WeakMap;async function Zie(e,t){var n,r;let i=(n=Vc.get(e))===null||n===void 0?void 0:n.get(t);if(i)return i;let o=`/EntityDefinitions(LogicalName='${(0,he.odataPathLiteral)(t)}')${(0,he.odataQuery)([["$select","EntitySetName"]])}`,s=(r=(0,nt.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||r===void 0?void 0:r.EntitySetName;if(!s)throw new de.InvalidArgumentError(`could not resolve EntitySetName for '${t}'`);(0,he.assertODataName)(s,`server-derived EntitySetName for '${t}'`);let u=Vc.get(e);return u||(u=new Map,Vc.set(e,u)),u.set(t,s),s}Ce.resolveEntitySetName=Zie;var qA=new WeakMap;async function eoe(e,t){var n,r,i;let o=(n=Vc.get(e))===null||n===void 0?void 0:n.get(t),a=(r=qA.get(e))===null||r===void 0?void 0:r.get(t);if(o&&a)return{entitySetName:o,primaryIdAttribute:a};let s=`/EntityDefinitions(LogicalName='${(0,he.odataPathLiteral)(t)}')${(0,he.odataQuery)([["$select","EntitySetName,PrimaryIdAttribute"]])}`,l=(0,nt.ensureSuccess)(await e.get(s),e.apiUrl(s)).body,c=l?.EntitySetName;if(typeof c!="string"||!c)throw new de.InvalidArgumentError(`could not resolve EntitySetName for '${t}'`);(0,he.assertODataName)(c,`server-derived EntitySetName for '${t}'`);let d=Vc.get(e);d||(d=new Map,Vc.set(e,d)),d.has(t)||d.set(t,c);let f=l?.PrimaryIdAttribute;if(typeof f!="string"||!f)throw new de.InvalidArgumentError(`could not resolve PrimaryIdAttribute for '${t}'`);(0,he.assertODataName)(f,`server-derived PrimaryIdAttribute for '${t}'`);let p=qA.get(e);return p||(p=new Map,qA.set(e,p)),p.set(t,f),{entitySetName:(i=d.get(t))!==null&&i!==void 0?i:c,primaryIdAttribute:f}}Ce.resolveUpsertTarget=eoe;async function toe(e,t){var n,r,i,o,a,s,u,l,c,d,f,p,m,h,g;let y=t.primaryColumnRequired;if(y!==void 0&&!IM.includes(y))throw new de.InvalidArgumentError(`createTable: 'primaryColumnRequired' must be one of ${IM.join(", ")}; got '${String(y)}'.`);let b=y!==void 0&&y!=="None";if(b&&!t.primaryColumnAutoNumberFormat&&!e.supportsPut)throw new de.InvalidArgumentError(`createTable: 'primaryColumnRequired: ${y}' 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 E=(n=t.languageCode)!==null&&n!==void 0?n:ca.DEFAULT_LCID,w=GA(t.schemaName),_=(r=t.primaryColumnSchemaName)!==null&&r!==void 0?r:`${w}_Name`,I={"@odata.type":"Microsoft.Dynamics.CRM.StringAttributeMetadata",AttributeType:"String",AttributeTypeName:{Value:"StringType"},SchemaName:_,RequiredLevel:_p(y??"None"),MaxLength:(i=t.primaryColumnMaxLength)!==null&&i!==void 0?i:100,FormatName:{Value:"Text"},DisplayName:ln((o=t.primaryColumnDisplayName)!==null&&o!==void 0?o:"Name",E),IsPrimaryName:!0};t.primaryColumnAutoNumberFormat&&(I.AutoNumberFormat=t.primaryColumnAutoNumberFormat),t.columns&&(MM(t.columns,"createTable"),ioe(t.columns));let T={"@odata.type":"Microsoft.Dynamics.CRM.EntityMetadata",SchemaName:t.schemaName,DisplayName:ln(t.displayName,E),DisplayCollectionName:ln((a=t.pluralName)!==null&&a!==void 0?a:PM(t.displayName),E),OwnershipType:(s=t.ownership)!==null&&s!==void 0?s:"UserOwned",IsActivity:!1,HasActivities:(u=t.hasActivities)!==null&&u!==void 0?u:!1,HasNotes:(l=t.hasNotes)!==null&&l!==void 0?l:!1,Attributes:[I,...((c=t.columns)!==null&&c!==void 0?c:[]).map(X=>WA(X,E))]};t.description&&(T.Description=ln(t.description,E)),t.searchEnabled===!0&&(T.SyncToExternalSearchIndex=!0,T.ChangeTrackingEnabled=!0);let O="/EntityDefinitions",v=(0,nt.ensureSuccess)(await e.post(O,T),e.apiUrl(O)),N=Ip(v),S=`/EntityDefinitions(${N})`+(0,he.odataQuery)([["$select","LogicalName,EntitySetName,PrimaryIdAttribute,PrimaryNameAttribute"]]),R=Math.max(1,Math.trunc((d=t.readBackAttempts)!==null&&d!==void 0?d:6)),x=Math.max(0,(f=t.readBackDelayMs)!==null&&f!==void 0?f:1e3),G=b?` Its primary column's requirement level '${y}' was NOT applied or checked: once the table is readable, set it with updateColumn('${t.schemaName.toLowerCase()}', '${_.toLowerCase()}', { required: '${y}' }).`:"",U;try{U=await kM(e,S,R,x)}catch(X){throw b?(0,de.attachCause)(new de.SdkError("PRIMARY_COLUMN_REQUIRED_NOT_APPLIED",`Table '${t.schemaName}' WAS CREATED (MetadataId ${N}), but reading it back failed (${X instanceof Error?X.message:String(X)}).${G} Do NOT re-run the create \u2014 it will collide on the schema name.`),X):X}if(!U)throw new de.SdkError("TABLE_METADATA_NOT_VISIBLE",`Table '${t.schemaName}' WAS CREATED (MetadataId ${N}) but its metadata was still not readable after ${R} attempt(s). Do NOT re-run the create \u2014 it will collide on the schema name. Re-read /EntityDefinitions(${N}) once the environment catches up, or raise 'readBackAttempts'.${G}`);let M=U.body,q={logicalName:(p=M.LogicalName)!==null&&p!==void 0?p:t.schemaName.toLowerCase(),metadataId:N,entitySetName:(m=M.EntitySetName)!==null&&m!==void 0?m:"",primaryIdAttribute:(h=M.PrimaryIdAttribute)!==null&&h!==void 0?h:`${t.schemaName.toLowerCase()}id`,primaryNameAttribute:(g=M.PrimaryNameAttribute)!==null&&g!==void 0?g:_.toLowerCase()};return b&&(q.primaryColumnRequired=await noe(e,t.schemaName,q,y,R,x)),q}Ce.createTable=toe;async function kM(e,t,n,r){for(let i=1;i<=n;i+=1){let o=await e.get(t);if(o.status>=200&&o.status<300)return o;o.status!==404&&(0,nt.ensureSuccess)(o,e.apiUrl(t)),i<n&&r>0&&await new Promise(a=>setTimeout(a,r))}}async function noe(e,t,n,r,i,o){let a=`/EntityDefinitions(LogicalName='${(0,he.odataPathLiteral)(n.logicalName)}')/Attributes(LogicalName='${(0,he.odataPathLiteral)(n.primaryNameAttribute)}')`+(0,he.odataQuery)([["$select","RequiredLevel"]]),s=async()=>{var d,f;let p=await kM(e,a,i,o),m=(f=(d=p?.body)===null||d===void 0?void 0:d.RequiredLevel)===null||f===void 0?void 0:f.Value;return typeof m=="string"?m:void 0},u="read",l,c=d=>{let f=`its primary column '${n.primaryNameAttribute}'`,p=u==="read"?`${f} could not be read back`:u==="update"?`${f} read '${l??"(unreadable)"}' and the update to '${r}' failed, so it may or may not carry it`:l===void 0?`${f} was updated to '${r}' but could not be read back`:`${f} is still '${l}' after the update to '${r}'`;return new de.SdkError("PRIMARY_COLUMN_REQUIRED_NOT_APPLIED",`Table '${t}' WAS CREATED (MetadataId ${n.metadataId}), but ${p}${d?` (${d})`:""}. Do NOT re-run the create \u2014 it will collide on the schema name. Check the level, and set it with updateColumn('${n.logicalName}', '${n.primaryNameAttribute}', { required: '${r}' }).`)};try{l=await s(),l!==r&&(u="update",await qM(e,n.logicalName,n.primaryNameAttribute,{required:r}),u="verify",l=await s())}catch(d){throw u==="verify"&&(l=void 0),(0,de.attachCause)(c(d instanceof Error?d.message:String(d)),d)}if(l!==r)throw c(l===void 0?"the answer had no RequiredLevel":void 0);return r}function WA(e,t){var n,r;let i=(n=e.languageCode)!==null&&n!==void 0?n:t,o={...Xie(e.type,e,i),SchemaName:e.schemaName,RequiredLevel:_p((r=e.required)!==null&&r!==void 0?r:"None"),DisplayName:ln(e.displayName,i)};return e.description&&(o.Description=ln(e.description,i)),e.sourceType&&e.sourceType!=="Simple"&&(o.SourceType=e.sourceType==="Rollup"?2:1,e.formulaDefinition&&(o.FormulaDefinition=e.formulaDefinition)),$M(o,e),e.isSecured===!0&&(o.IsSecured=!0),o}function $M(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 roe(e,t,n){var r;let i=WA(n,(r=n.languageCode)!==null&&r!==void 0?r:ca.DEFAULT_LCID),o=`/EntityDefinitions(LogicalName='${(0,he.odataPathLiteral)(t)}')/Attributes`,a;try{a=(0,nt.ensureSuccess)(await e.post(o,i),e.apiUrl(o))}catch(u){return jA(e,t,u)}let s={logicalName:n.schemaName.toLowerCase(),metadataId:Ip(a)};if(n.visualization&&n.visualization!=="None")try{await UM(e,t,s.logicalName,s.metadataId,n.visualization)}catch(u){let l=new de.SdkError("COLUMN_VISUALIZATION_BIND_FAILED",`Column '${s.logicalName}' on '${t}' was created, but binding its '${n.visualization}' grid visualization failed; the column exists WITHOUT a visualization. Retry with setColumnVisualization('${t}', '${s.logicalName}', '${n.visualization}'). Cause: ${u instanceof Error?u.message:String(u)}`);throw(0,de.attachCause)(l,u),l}return s}Ce.createColumn=roe;var Gc="/controlconfigurations",LM="CustomRenderersConfiguration",VA={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 MM(e,t){let n=e.find(r=>r.visualization&&r.visualization!=="None");if(n)throw new de.InvalidArgumentError(`${t}: setting 'visualization' on an inline column ('${n.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 ioe(e){let t=e.find(n=>n.isSecured===!0);if(t)throw new de.InvalidArgumentError(`createTable: 'isSecured' on an inline column ('${t.schemaName}') is not supported \u2014 the platform refuses a table create that secures an inline column. Create the table, then call updateColumn(table, column, { isSecured: true }); or add the column with createColumn / createColumns.`)}function xM(e){return JSON.stringify({type:VA[e]})}function ooe(e){if(!e)return"None";let t;try{t=JSON.parse(e)}catch{return"None"}let n=t?.type,r=Object.keys(VA).find(i=>VA[i]===n);return r??"None"}async function FM(e,t,n){var r,i;let o=`entitylogicalname eq '${(0,he.odataLiteral)(t)}' and Attribute/logicalname eq '${(0,he.odataLiteral)(n)}'`,a=`${Gc}${(0,he.odataQuery)([["$select","name,uniquename,metadatajson"],["$expand","Attribute($select=name,logicalname)"],["$filter",o]])}`,u=(i=(r=(0,nt.ensureSuccess)(await e.get(a),e.apiUrl(a)).body)===null||r===void 0?void 0:r.value)!==null&&i!==void 0?i:[],l=n.toLowerCase();return u.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())===l})}async function aoe(e,t,n){var r;let i=`/EntityDefinitions(LogicalName='${(0,he.odataPathLiteral)(t)}')/Attributes(LogicalName='${(0,he.odataPathLiteral)(n)}')${(0,he.odataQuery)([["$select","MetadataId"]])}`,a=(r=(0,nt.ensureSuccess)(await e.get(i),e.apiUrl(i)).body)===null||r===void 0?void 0:r.MetadataId;if(!a)throw new de.InvalidArgumentError(`cannot resolve column '${n}' on '${t}' to set its visualization`);return(0,he.normalizeGuid)(a,"MetadataId")}async function UM(e,t,n,r,i){let o={name:LM,uniquename:`msdyn_${t}_${n}_customrenderers`,metadatajson:xM(i),"[email protected]":`/attributes(${(0,he.normalizeGuid)(r,"MetadataId")})`,entitylogicalname:t};(0,nt.ensureSuccess)(await e.post(Gc,o),e.apiUrl(Gc))}async function soe(e,t,n){var r;let i=await FM(e,t,n);return ooe((r=i[0])===null||r===void 0?void 0:r.metadatajson)}Ce.getColumnVisualization=soe;async function uoe(e,t,n,r){let o=(await FM(e,t,n)).map(l=>l.controlconfigurationid).filter(l=>!!l);if(r==="None"){for(let l of o){let c=`${Gc}(${(0,he.normalizeGuid)(l,"controlconfigurationid")})`;(0,nt.ensureSuccess)(await e.delete(c),e.apiUrl(c))}return}let[a,...s]=o,u=await aoe(e,t,n);if(a){let l=`${Gc}(${(0,he.normalizeGuid)(a,"controlconfigurationid")})`,c={name:LM,metadatajson:xM(r),"[email protected]":`/attributes(${u})`,entitylogicalname:t};(0,nt.ensureSuccess)(await e.patch(l,c),e.apiUrl(l))}else await UM(e,t,n,u,r);for(let l of s){let c=`${Gc}(${(0,he.normalizeGuid)(l,"controlconfigurationid")})`;(0,nt.ensureSuccess)(await e.delete(c),e.apiUrl(c))}}Ce.setColumnVisualization=uoe;async function loe(e,t,n){if(n.length===0)return;if(MM(n,"createColumns"),!e.supportsAtomicBatch)throw new de.InvalidArgumentError(`createColumns writes ${n.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 r=`/EntityDefinitions(LogicalName='${(0,he.odataPathLiteral)(t)}')/Attributes`;try{await(0,Wie.postChangeSet)(e,n.map(i=>{var o;return{method:"POST",path:r,body:WA(i,(o=i.languageCode)!==null&&o!==void 0?o:ca.DEFAULT_LCID)}}),`${n.length} column(s) on '${t}'`)}catch(i){await jA(e,t,i)}}Ce.createColumns=loe;async function coe(e,t,n){var r,i,o,a;let s=(r=n.languageCode)!==null&&r!==void 0?r:ca.DEFAULT_LCID,u=GA(n.schemaName),l=(i=n.accountRelationshipName)!==null&&i!==void 0?i:`${u}_${t}_account`,c=(o=n.contactRelationshipName)!==null&&o!==void 0?o:`${u}_${t}_contact`,d={Lookup:{"@odata.type":"Microsoft.Dynamics.CRM.ComplexLookupAttributeMetadata",SchemaName:n.schemaName,DisplayName:ln(n.displayName,s),RequiredLevel:_p((a=n.required)!==null&&a!==void 0?a:"None"),Targets:["account","contact"]},OneToManyRelationships:[{"@odata.type":"Microsoft.Dynamics.CRM.ComplexOneToManyRelationshipMetadata",SchemaName:l,ReferencedEntity:"account",ReferencingEntity:t},{"@odata.type":"Microsoft.Dynamics.CRM.ComplexOneToManyRelationshipMetadata",SchemaName:c,ReferencedEntity:"contact",ReferencingEntity:t}]};return(0,nt.ensureSuccess)(await e.post("/CreateCustomerRelationships",d),e.apiUrl("/CreateCustomerRelationships")),{logicalName:n.schemaName.toLowerCase(),metadataId:""}}Ce.createCustomerColumn=coe;async function doe(e,t,n){var r,i,o,a,s;let u=(r=n.languageCode)!==null&&r!==void 0?r:ca.DEFAULT_LCID,l={EntityLogicalName:t,AttributeLogicalName:"statuscode",Label:ln(n.label,u),StateCode:(i=n.stateCode)!==null&&i!==void 0?i:0};typeof n.value=="number"&&(l.Value=n.value),n.color&&(l.Color=n.color);let c=(0,nt.ensureSuccess)(await e.post("/InsertStatusValue",l),e.apiUrl("/InsertStatusValue"));return Number((s=(a=(o=c.body)===null||o===void 0?void 0:o.NewOptionValue)!==null&&a!==void 0?a:n.value)!==null&&s!==void 0?s:0)}Ce.insertStatusValue=doe;async function foe(e,t){var n,r,i,o,a;let s=(n=t.languageCode)!==null&&n!==void 0?n:ca.DEFAULT_LCID,u,l;if(t.type==="OneToMany"){if(!t.referencedEntity||!t.referencingEntity)throw new de.InvalidArgumentError("OneToMany relationship requires referencedEntity and referencingEntity");let f=(r=t.lookupSchemaName)!==null&&r!==void 0?r:`${GA(t.schemaName)}_${t.referencedEntity}Id`;l=f.toLowerCase(),u={"@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:_p((i=t.lookupRequired)!==null&&i!==void 0?i:"None"),DisplayName:ln((o=t.lookupDisplayName)!==null&&o!==void 0?o:t.referencedEntity,s)}}}else{if(!t.entity1||!t.entity2)throw new de.InvalidArgumentError("ManyToMany relationship requires entity1 and entity2");u={"@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;try{d=(0,nt.ensureSuccess)(await e.post(c,u),e.apiUrl(c))}catch(f){if(t.type==="OneToMany"&&t.referencingEntity)return jA(e,t.referencingEntity,f);throw f}return{schemaName:t.schemaName,metadataId:Ip(d),lookupLogicalName:l}}Ce.createRelationship=foe;async function poe(e,t){let n=`/EntityDefinitions(LogicalName='${(0,he.odataPathLiteral)(t)}')`;(0,nt.ensureSuccess)(await e.delete(n),e.apiUrl(n))}Ce.deleteTable=poe;function moe(e){return Object.entries(e).every(([t,n])=>t==="isSecured"||t==="languageCode"||n===void 0)}async function qM(e,t,n,r){var i,o;let a=(i=r.languageCode)!==null&&i!==void 0?i:ca.DEFAULT_LCID,s=`/EntityDefinitions(LogicalName='${(0,he.odataPathLiteral)(t)}')/Attributes`,u=r.dateTimeBehavior===void 0?void 0:RM(r.dateTimeBehavior,"updateColumn"),l=`${s}(LogicalName='${(0,he.odataPathLiteral)(n)}')${(0,he.odataQuery)([["$select","MetadataId,AttributeType"]])}`,d=(0,nt.ensureSuccess)(await e.get(l),e.apiUrl(l)).body,f=Hie[(o=d.AttributeType)!==null&&o!==void 0?o:""];if(!d.MetadataId||!f){let y=d.MetadataId?d.AttributeType?`type '${d.AttributeType}' not supported`:"the attribute read returned no AttributeType":"the attribute read returned no MetadataId";throw new de.InvalidArgumentError(`cannot update column '${n}' on '${t}' (${y})`)}let p=(0,he.normalizeGuid)(d.MetadataId,"MetadataId");if(u!==void 0&&d.AttributeType!=="DateTime")throw new de.InvalidArgumentError(`updateColumn: 'dateTimeBehavior' applies to DateTime columns, but '${n}' on '${t}' is of type '${d.AttributeType}'.`);let m=`${s}(${p})/${f}`,h=(0,nt.ensureSuccess)(await e.get(m),e.apiUrl(m)).body;for(let y of Object.keys(h))y.startsWith("@odata.")&&delete h[y];if(h["@odata.type"]=f,r.displayName!==void 0&&(h.DisplayName=ln(r.displayName,a)),r.description!==void 0&&(h.Description=ln(r.description,a)),r.required!==void 0&&(h.RequiredLevel=_p(r.required)),r.maxLength!==void 0&&(h.MaxLength=r.maxLength),r.autoNumberFormat!==void 0&&(h.AutoNumberFormat=r.autoNumberFormat),r.defaultValue!==void 0&&d.AttributeType!=="Boolean")throw new de.InvalidArgumentError(`updateColumn: 'defaultValue' applies to Boolean columns, but '${n}' on '${t}' is of type '${d.AttributeType}'.`);if(r.integerFormat!==void 0&&d.AttributeType!=="Integer")throw new de.InvalidArgumentError(`updateColumn: 'integerFormat' applies to Integer columns, but '${n}' on '${t}' is of type '${d.AttributeType}'.`);if(r.defaultValue!==void 0&&(h.DefaultValue=r.defaultValue),r.integerFormat!==void 0&&(h.Format=r.integerFormat),$M(h,r),u!==void 0&&Jie(h,u,n,t),r.isSecured===!0)h.IsSecured=!0;else if(r.isSecured===!1){if(h.IsSecured!==!0&&moe(r))return;h.IsSecured=!1}let g=`${s}(${p})`;if(r.isSecured===!1){let y=await(0,zie.readColumnPermissionHolders)(e,t,n);if(y.length>0)throw new de.ArtifactInUseError("column",`${t}.${n}`,`Refusing to unsecure ${t}.${n}: ${y.length} field security profile(s) hold a permission on it, and unsecuring a column deletes every permission on it in every profile. Nothing was changed. Remove those permissions from their profiles first.`,y.map(b=>({table:"fieldsecurityprofile",id:b})))}(0,nt.ensureSuccess)(await e.put(g,h,{headers:{"MSCRM.MergeLabels":"true"}}),e.apiUrl(g))}Ce.updateColumn=qM;async function hoe(e,t,n){var r;let i=`/EntityDefinitions(LogicalName='${(0,he.odataPathLiteral)(t)}')/Attributes`,o=`${i}(LogicalName='${(0,he.odataPathLiteral)(n)}')${(0,he.odataQuery)([["$select","MetadataId"]])}`,s=(r=(0,nt.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||r===void 0?void 0:r.MetadataId;if(!s)throw new de.InvalidArgumentError(`column '${n}' not found on '${t}'`);let u=`${i}(${(0,he.normalizeGuid)(s,"MetadataId")})`;(0,nt.ensureSuccess)(await e.delete(u),e.apiUrl(u))}Ce.deleteColumn=hoe;async function goe(e,t){var n,r,i;let o=`/RelationshipDefinitions${(0,he.odataQuery)([["$filter",`SchemaName eq '${(0,he.odataLiteral)(t)}'`],["$select","MetadataId"]])}`,s=(i=(r=(n=(0,nt.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||n===void 0?void 0:n.value)===null||r===void 0?void 0:r[0])===null||i===void 0?void 0:i.MetadataId;if(!s)throw new de.InvalidArgumentError(`relationship '${t}' not found`);let u=`/RelationshipDefinitions(${(0,he.normalizeGuid)(s,"MetadataId")})`;(0,nt.ensureSuccess)(await e.delete(u),e.apiUrl(u))}Ce.deleteRelationship=goe;async function DM(e,t){var n;let r=`/GlobalOptionSetDefinitions(Name='${(0,he.odataPathLiteral)(t)}')${(0,he.odataQuery)([["$select","MetadataId"]])}`,i=await e.get(r);if(i.status===404)return;let a=(n=(0,nt.ensureSuccess)(i,e.apiUrl(r)).body)===null||n===void 0?void 0:n.MetadataId;return a?(0,he.normalizeGuid)(a,"MetadataId"):void 0}async function yoe(e,t){var n;let r=t.name.toLowerCase(),i=await DM(e,r);if(i)return{name:r,metadataId:i};let o=(n=t.languageCode)!==null&&n!==void 0?n:ca.DEFAULT_LCID,a={"@odata.type":"Microsoft.Dynamics.CRM.OptionSetMetadata",Name:r,DisplayName:ln(t.displayName,o),IsGlobal:!0,OptionSetType:"Picklist",Options:t.options.map(u=>({Value:u.value,Label:ln(u.label,o)}))};t.description&&(a.Description=ln(t.description,o));let s="/GlobalOptionSetDefinitions";try{let u=(0,nt.ensureSuccess)(await e.post(s,a),e.apiUrl(s));return{name:r,metadataId:Ip(u)}}catch(u){let l;try{l=await DM(e,r)}catch{l=void 0}if(l)return{name:r,metadataId:l};throw u}}Ce.createGlobalOptionSet=yoe;async function boe(e,t){let n=`/GlobalOptionSetDefinitions(Name='${(0,he.odataPathLiteral)(t.toLowerCase())}')`;(0,nt.ensureSuccess)(await e.delete(n),e.apiUrl(n))}Ce.deleteGlobalOptionSet=boe;async function voe(e,t,n){var r;let i=(r=n.languageCode)!==null&&r!==void 0?r:ca.DEFAULT_LCID,o={"@odata.type":"Microsoft.Dynamics.CRM.EntityKeyMetadata",SchemaName:n.schemaName,DisplayName:ln(n.displayName,i),KeyAttributes:n.keyAttributes},a=`/EntityDefinitions(LogicalName='${(0,he.odataPathLiteral)(t)}')/Keys`,s=(0,nt.ensureSuccess)(await e.post(a,o),e.apiUrl(a));return{logicalName:n.schemaName.toLowerCase(),metadataId:Ip(s)}}Ce.createAlternateKey=voe;async function woe(e,t,n){var r;let i=`/EntityDefinitions(LogicalName='${(0,he.odataPathLiteral)(t)}')/Keys`,o=`${i}(LogicalName='${(0,he.odataPathLiteral)(n.toLowerCase())}')${(0,he.odataQuery)([["$select","MetadataId"]])}`,s=(r=(0,nt.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||r===void 0?void 0:r.MetadataId;if(!s)throw new de.InvalidArgumentError(`alternate key '${n}' not found on '${t}'`);let u=`${i}(${(0,he.normalizeGuid)(s,"MetadataId")})`;(0,nt.ensureSuccess)(await e.delete(u),e.apiUrl(u))}Ce.deleteAlternateKey=woe;function Eoe(e,t,n){var r;let i=t.ChangeTrackingEnabled===!0;if(n.changeTrackingEnabled===!1&&i)throw new de.InvalidArgumentError(`updateTable('${e}'): change tracking is on and cannot be turned off \u2014 the platform keeps it on (it would accept the write and change nothing). Nothing was written.`);if(n.searchEnabled!==!0)return;if(n.changeTrackingEnabled===!1)throw new de.InvalidArgumentError(`updateTable('${e}'): searchEnabled: true contradicts changeTrackingEnabled: false \u2014 Dataverse search needs change tracking. Nothing was written.`);if(!i&&n.changeTrackingEnabled!==!0)throw new de.InvalidArgumentError(`updateTable('${e}'): searchEnabled: true turns on change tracking, which can never be turned off again. Pass changeTrackingEnabled: true in the same call to confirm. Nothing was written.`);if(((r=t.CanEnableSyncToExternalSearchIndex)===null||r===void 0?void 0:r.Value)===!1)throw new de.TableSearchNotAllowedError(e)}async function Aoe(e,t,n){var r;let i=(r=n.languageCode)!==null&&r!==void 0?r:ca.DEFAULT_LCID,o=`/EntityDefinitions(LogicalName='${(0,he.odataPathLiteral)(t)}')`,s=(0,nt.ensureSuccess)(await e.get(o),e.apiUrl(o)).body,u=s.MetadataId;if(!u)throw new de.InvalidArgumentError(`table '${t}' not found`);let l=(0,he.normalizeGuid)(u,"MetadataId");Eoe(t,s,n);for(let d of Object.keys(s))d.startsWith("@odata.")&&delete s[d];s["@odata.type"]="Microsoft.Dynamics.CRM.EntityMetadata",n.displayName!==void 0&&(s.DisplayName=ln(n.displayName,i)),n.pluralName!==void 0&&(s.DisplayCollectionName=ln(n.pluralName,i)),n.description!==void 0&&(s.Description=ln(n.description,i)),n.auditEnabled!==void 0&&TM(s,"IsAuditEnabled",n.auditEnabled),n.duplicateDetectionEnabled!==void 0&&TM(s,"IsDuplicateDetectionEnabled",n.duplicateDetectionEnabled),n.changeTrackingEnabled!==void 0&&(s.ChangeTrackingEnabled=n.changeTrackingEnabled),n.searchEnabled===!0?(s.SyncToExternalSearchIndex=!0,s.ChangeTrackingEnabled=!0):n.searchEnabled===!1&&(s.SyncToExternalSearchIndex=!1),n.quickCreateEnabled!==void 0&&(s.IsQuickCreateEnabled=n.quickCreateEnabled),n.iconVectorName!==void 0&&(s.IconVectorName=n.iconVectorName),n.iconSmallName!==void 0&&(s.IconSmallName=n.iconSmallName),n.iconMediumName!==void 0&&(s.IconMediumName=n.iconMediumName),n.iconLargeName!==void 0&&(s.IconLargeName=n.iconLargeName);let c=`/EntityDefinitions(${l})`;(0,nt.ensureSuccess)(await e.put(c,s,{headers:{"MSCRM.MergeLabels":"true"}}),e.apiUrl(c))}Ce.updateTable=Aoe});var VM=C(jc=>{"use strict";Object.defineProperty(jc,"__esModule",{value:!0});jc.getSearchSettings=jc.configuredIndexFieldCount=void 0;var c0=Ke(),Coe=pe(),zA=ae(),HA=Y(),Soe="isexternalsearchindexenabled,quickfindrecordlimitenabled,usequickfindviewforgridsearch",Noe="LogicalName,SyncToExternalSearchIndex,ChangeTrackingEnabled,CanEnableSyncToExternalSearchIndex",_oe="Attributes($select=LogicalName,AttributeType,IsSearchable,IsFilterable,IsRetrievable,IsPrimaryId,IsPrimaryName)",Ioe=new Set(["ownerid","owningbusinessunit","businessunitid","versionnumber","statecode","statuscode","entityimage_url","createdon","modifiedon"]),Toe=new Set(["Lookup","Customer","Owner"]),Ooe=new Set(["Boolean","Picklist","State","Status"]);function BM(e){let t=0;for(let n of e){if(!(n.IsSearchable||n.IsFilterable||n.IsRetrievable)||n.IsPrimaryId||n.IsPrimaryName||Ioe.has(String(n.LogicalName)))continue;let r=String(n.AttributeType);t+=Toe.has(r)?3:Ooe.has(r)?2:1}return t}jc.configuredIndexFieldCount=BM;function Doe(e){var t,n;let r=e?.response;if(typeof r!="string")return"unknown";let i;try{i=(n=(t=JSON.parse(r))===null||t===void 0?void 0:t.value)===null||n===void 0?void 0:n.status}catch{return"unknown"}switch(String(i).toLowerCase()){case"notprovisioned":case"0":return"notProvisioned";case"provisioninginprogress":case"1":return"provisioningInProgress";case"provisioned":case"2":return"provisioned";default:return"unknown"}}async function Poe(e){let t;try{t=await e.get("/searchstatus")}catch{return"unknown"}return t.status>=200&&t.status<300?Doe(t.body):"unknown"}var l0=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Roe=["isexternalsearchindexenabled","quickfindrecordlimitenabled","usequickfindviewforgridsearch"],koe=["IsSearchable","IsFilterable","IsRetrievable","IsPrimaryId","IsPrimaryName"];function as(e,t,n){return new HA.ConnectionError(e,t,`getSearchSettings: ${n}; an unreadable answer is never reported as a search configuration.`)}function $oe(e,t){var n;let r=(n=e.body)===null||n===void 0?void 0:n.value;if(!Array.isArray(r))throw as(t,e.status,`the organization answer has no rows (${(0,c0.describeMalformedValue)(r)})`);let i=r[0];if(r.length!==1||!l0(i))throw as(t,e.status,`the organization answer holds ${r.length} row(s), not one organization`);let o=Roe.find(a=>typeof i[a]!="boolean");if(o)throw as(t,e.status,`the organization's '${o}' is not a boolean`);return i}function Loe(e,t){if(!l0(e)||typeof e.LogicalName!="string"||e.LogicalName==="")throw as(t,200,"a table row without its LogicalName");let n=e.LogicalName,r=["SyncToExternalSearchIndex","ChangeTrackingEnabled"].find(s=>typeof e[s]!="boolean");if(r)throw as(t,200,`table '${n}': '${r}' is not a boolean`);let i=e.CanEnableSyncToExternalSearchIndex;if(!l0(i)||typeof i.Value!="boolean")throw as(t,200,`table '${n}': 'CanEnableSyncToExternalSearchIndex' has no boolean Value`);let o=e["[email protected]"];if((0,c0.moreRecordsClaim)(e,"Attributes")!=="none"||o!=null)throw as(t,200,`table '${n}': its attributes were answered incompletely`);let a=e.Attributes;if(!Array.isArray(a))throw as(t,200,`table '${n}': its attributes are ${(0,c0.describeMalformedValue)(a)}`);for(let s of a)if(!l0(s)||typeof s.LogicalName!="string"||typeof s.AttributeType!="string"||koe.some(u=>typeof s[u]!="boolean"))throw as(t,200,`table '${n}': an attribute without its name, type or search flags`);return e}function Moe(e){var t,n,r;let i=(t=e.Attributes)!==null&&t!==void 0?t:[],o=e.SyncToExternalSearchIndex===!0,a=e.ChangeTrackingEnabled===!0;return{entityLogicalName:String((n=e.LogicalName)!==null&&n!==void 0?n:""),syncToSearchIndex:o,changeTrackingEnabled:a,searchEnabled:o&&a,canEnableSearch:((r=e.CanEnableSyncToExternalSearchIndex)===null||r===void 0?void 0:r.Value)===!0,configuredSearchableColumns:i.filter(s=>s.IsSearchable===!0&&typeof s.LogicalName=="string").map(s=>String(s.LogicalName)).sort(),configuredIndexFieldCount:BM(i)}}async function xoe(e,t={}){let n=t.tables;if(n!==void 0){if(!Array.isArray(n))throw new HA.InvalidArgumentError("getSearchSettings: tables must be an array of table logical names.");n.forEach((l,c)=>{if(typeof l!="string"||l.trim()==="")throw new HA.InvalidArgumentError(`getSearchSettings: tables[${c}] must be a non-empty table logical name, got ${JSON.stringify(l)}.`)})}let r=n===void 0?void 0:[...new Set(n.map(l=>l.toLowerCase()))],i=`/organizations${(0,zA.odataQuery)([["$select",Soe]])}`,o=e.apiUrl(i),a=$oe((0,Coe.ensureSuccess)(await e.get(i),o),o),s=await Poe(e),u=[];if(r===void 0||r.length>0){let l=r===void 0?"SyncToExternalSearchIndex eq true":r.map(p=>`LogicalName eq '${(0,zA.odataLiteral)(p)}'`).join(" or "),c=`/EntityDefinitions${(0,zA.odataQuery)([["$select",Noe],["$expand",_oe],["$filter",l]])}`,d=e.apiUrl(c),f=(await(0,c0.collectPages)(e,c,"getSearchSettings")).map(p=>Moe(Loe(p,d)));u=r===void 0?f:r.map(p=>f.find(m=>m.entityLogicalName.toLowerCase()===p)).filter(p=>p!==void 0)}return{environment:{dataverseSearchEnabled:a.isexternalsearchindexenabled,indexStatus:s,quickFindRecordLimitEnabled:a.quickfindrecordlimitenabled,gridSearchUsesQuickFindView:a.usequickfindviewforgridsearch},tables:u}}jc.getSearchSettings=xoe});var KM=C(On=>{"use strict";Object.defineProperty(On,"__esModule",{value:!0});On.recoverFormCreate=On.solutionMembershipProblem=On.formWriteMismatches=On.validateExistingForm=On.formExistsAtId=On.isFormRecordAt=On.MAIN_FORM_TYPE=void 0;var Wc=ae(),GM=Ke(),jM=il();On.MAIN_FORM_TYPE=2;function d0(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function f0(e){return e instanceof Error?e.message:String(e)}function KA(e,t){if(typeof e!="string"||typeof t!="string")return!1;try{return(0,Wc.normalizeGuid)(e,"a GUID")===(0,Wc.normalizeGuid)(t,"a GUID")}catch{return!1}}function JA(e,t){return d0(e)&&KA(e.formid,t)}On.isFormRecordAt=JA;async function Foe(e,t){try{return JA((await e()).raw,t)}catch{return!1}}On.formExistsAtId=Foe;function WM(e,t){let n=e.raw;if(!d0(n))return{problem:"it is not a record"};if(!JA(n,t))return{problem:"its formid is not the id this create sent"};if(n.type!==On.MAIN_FORM_TYPE)return{problem:`its type is not ${On.MAIN_FORM_TYPE} (a Main form)`};if(typeof n.objecttypecode!="string")return{problem:"its objecttypecode is not a string"};if(typeof n.name!="string")return{problem:"its name is not a string"};if(typeof n.formxml!="string"||n.formxml.length===0)return{problem:"its formxml is not a non-empty string"};if(typeof n.formpresentation!="number")return{problem:"its formpresentation is not a number"};if(typeof n.formactivationstate!="number")return{problem:"its formactivationstate is not a number"};for(let o of["uniquename","description"]){let a=n[o];if(a!=null&&typeof a!="string")return{problem:`its ${o} is neither a string nor null`}}let r=n["@odata.etag"];if(r!==void 0&&typeof r!="string")return{problem:"its @odata.etag is not a string"};if(r!==void 0&&e.etag!==null&&e.etag!==r)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:n,etag:i}}On.validateExistingForm=WM;function zM(e,t){let n=[];for(let i of["formxml","name","objecttypecode","type"])e[i]!==t[i]&&n.push(i);let r=t.description;if(r!==void 0){let i=e.description;typeof r=="string"&&(r===""?i==null||i==="":i===r)||n.push("description")}return n}On.formWriteMismatches=zM;async function HM(e,t){let n=e.solutionName;if(n)try{let r=await(0,GM.collectPages)(e,`/solutions${(0,Wc.odataQuery)([["$select","solutionid,uniquename"],["$filter",`uniquename eq '${(0,Wc.odataLiteral)(n)}'`]])}`,"createRecovery solution lookup");if(r.length!==1)return`the configured solution '${n}' resolves to ${r.length} solutions, not exactly one`;let[i]=r,o;return d0(i)&&typeof i.uniquename=="string"&&typeof i.solutionid=="string"&&i.uniquename.toLowerCase()===n.toLowerCase()&&(o=(0,Wc.normalizeGuid)(i.solutionid,"solutionid")),o===void 0?`the configured solution '${n}' did not resolve to a valid solution of that name`:(await(0,GM.collectPages)(e,`/solutioncomponents${(0,Wc.odataQuery)([["$select","objectid,componenttype,_solutionid_value"],["$filter",`_solutionid_value eq ${o} and componenttype eq ${jM.SolutionComponentType.SystemForm} and objectid eq ${t}`]])}`,"createRecovery solution membership")).some(u=>d0(u)&&u.componenttype===jM.SolutionComponentType.SystemForm&&KA(u.objectid,t)&&KA(u._solutionid_value,o))?void 0:`the form is not a component of the configured solution '${n}'`}catch(r){return`membership in the configured solution '${n}' could not be established (${f0(r)})`}}On.solutionMembershipProblem=HM;async function Uoe(e){try{return await qoe(e)}catch(t){return{refused:`the recovery could not be completed (${f0(t)})`}}}On.recoverFormCreate=Uoe;async function qoe(e){let{client:t,read:n,sent:r,authoredFormType:i,project:o}=e;if(i!=="Main"||r.type!==On.MAIN_FORM_TYPE)return{refused:`only a Main form is adopted (this one is authored as ${String(i)})`};let a=r.formid;if(typeof a!="string")return{refused:"the create sent no formid to look for"};let s;try{s=await n()}catch(f){return{refused:`the existing row could not be read (${f0(f)})`}}let u=WM(s,a);if("problem"in u)return{refused:`the existing row cannot be trusted: ${u.problem}`};let l=zM(u.record,r);if(l.length>0)return{refused:`the existing row is not what this create wrote (it differs in ${l.join(", ")})`};let c;try{c=o(u.record)}catch(f){return{refused:`the existing row could not be read into a form (${f0(f)})`}}let d=await HM(t,a);return d!==void 0?{refused:d}:{adopted:{artifact:c,etag:u.etag}}}});var p0=C(Xt=>{"use strict";Object.defineProperty(Xt,"__esModule",{value:!0});Xt.disassociateRecords=Xt.associateRecords=Xt.createRecordsBulk=Xt.upsertRecord=Xt.queryAllRecords=Xt.queryRecords=Xt.getRecord=Xt.deleteRecord=Xt.updateRecord=Xt.createRecord=void 0;var QA=Ke(),pi=pe(),ar=ae(),$i=Y(),Co=u0();function Tp(e){let t=e,n=!1,r={};for(let i of Object.keys(t)){let o=t[i];Array.isArray(o)&&o.every(a=>typeof a=="number")?(r[i]=o.join(","),n=!0):r[i]=o}return n?r:e}async function Boe(e,t,n){let i=`/${await(0,Co.resolveEntitySetName)(e,t)}`,o=(0,pi.ensureSuccess)(await e.post(i,Tp(n)),e.apiUrl(i)),a=(0,pi.readCreatedId)(o,`${t}id`);if(!a)throw new $i.InvalidArgumentError(`Dataverse did not return an id for the created '${t}' row`);return{id:a,entityType:t}}Xt.createRecord=Boe;async function Voe(e,t,n,r){let i=(0,ar.normalizeGuid)(n,"id"),a=`/${await(0,Co.resolveEntitySetName)(e,t)}(${i})`;(0,pi.ensureSuccess)(await e.patch(a,Tp(r)),e.apiUrl(a))}Xt.updateRecord=Voe;async function Goe(e,t,n){let r=(0,ar.normalizeGuid)(n,"id"),o=`/${await(0,Co.resolveEntitySetName)(e,t)}(${r})`;(0,pi.ensureSuccess)(await e.delete(o),e.apiUrl(o))}Xt.deleteRecord=Goe;async function joe(e,t,n,r){let i=(0,ar.normalizeGuid)(n,"id"),o=await(0,Co.resolveEntitySetName)(e,t),a=(0,ar.odataQuery)([["$select",r&&r.length>0?r.join(","):void 0]]),s=`/${o}(${i})${a}`,u=(0,pi.ensureSuccess)(await e.get(s),e.apiUrl(s)),l=u.body;if(l===null||typeof l!="object"||Array.isArray(l))throw new $i.ConnectionError(e.apiUrl(s),u.status,`getRecord: read returned a malformed row \u2014 expected an OData entity object but got ${Array.isArray(l)?"an array":(0,QA.describeMalformedValue)(l)}; refusing to read it as a row.`);return l}Xt.getRecord=joe;function Woe(e){return e?.fetchXml?(0,ar.odataQuery)([["fetchXml",e.fetchXml]]):(0,ar.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 YM(e,t,n){var r;if(n?.paginate){if(n.top!==void 0)throw new $i.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(n.fetchXml)throw new $i.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,Co.resolveEntitySetName)(e,t)}${Woe(n)}`;if(n?.paginate)return(0,QA.collectPages)(e,o,"queryRecords");let a=(0,pi.ensureSuccess)(await e.get(o),e.apiUrl(o)),s=(r=a.body)===null||r===void 0?void 0:r.value;if(!Array.isArray(s))throw new $i.ConnectionError(e.apiUrl(o),a.status,`queryRecords: read returned a malformed page \u2014 expected an OData 'value' array but got ${(0,QA.describeMalformedValue)(s)}; refusing to read it as rows.`);return s}Xt.queryRecords=YM;async function zoe(e,t,n){return YM(e,t,{...n,paginate:!0})}Xt.queryAllRecords=zoe;function Hoe(e){if("id"in e)return`(${(0,ar.normalizeGuid)(e.id,"id")})`;let t=typeof e.value=="string"?`'${(0,ar.odataPathLiteral)(e.value)}'`:e.value;return`(${(0,ar.assertODataName)(e.key,"alternate key name")}=${t})`}function JM(e){if(e===201)return!0;if(e===200)return!1}function Koe(e){if(e===void 0)return!1;let t=e!==null&&typeof e=="object"?Object.getPrototypeOf(e):void 0;if(t!==Object.prototype&&t!==null)throw new $i.InvalidArgumentError("upsertRecord: `options` must be a plain object, e.g. { reportCreated: true }");let n=e.reportCreated;if(n!==void 0&&typeof n!="boolean")throw new $i.InvalidArgumentError(`upsertRecord: \`reportCreated\` must be true or false, not ${n===null?"null":typeof n}`);return n===!0}async function Joe(e,t,n,r,i){let o=Koe(i),a=Hoe(n);if(!o){let g=`/${await(0,Co.resolveEntitySetName)(e,t)}${a}`,y=(0,pi.ensureSuccess)(await e.patch(g,Tp(r)),e.apiUrl(g)),b=(0,pi.readCreatedId)(y,`${t}id`);return{id:b??("id"in n?(0,ar.normalizeGuid)(n.id,"id"):""),created:JM(y.status)}}let s=await(0,Co.resolveUpsertTarget)(e,t),u=(0,pi.echoWrite)(s.primaryIdAttribute),l=`/${s.entitySetName}${a}${u.query}`,c=e.apiUrl(l),d=Tp(r),f;try{f=await e.patch(l,d,u.options)}catch(h){throw YA(t,n,h instanceof $i.ConnectionError?h:new $i.ConnectionError(c,0,String(h),h))}if(f.status<200||f.status>=300)throw YA(t,n,new $i.ConnectionError(c,f.status,(0,pi.extractErrorMessage)(f.body),f.body));let p;try{p=(0,pi.readCreatedId)(f,s.primaryIdAttribute)}catch(h){throw YA(t,n,new $i.ConnectionError(c,f.status,`the answer's primary id could not be read: ${h instanceof Error?h.message:String(h)}`,h))}return{id:p??("id"in n?(0,ar.normalizeGuid)(n.id,"id"):""),created:JM(f.status)}}Xt.upsertRecord=Joe;function YA(e,t,n){var r,i;let o=(i=(r=n.cause)===null||r===void 0?void 0:r.error)===null||i===void 0?void 0:i.code,a=typeof o=="string"&&o?o:void 0,s="id"in t?`id ${t.id}`:`${t.key} = ${String(t.value)}`,u=a?`${n.message} [${a}]`:n.message,c=n.statusCode>=200&&n.statusCode<300?`was acknowledged, but its answer could not be read \u2014 ${u}. The row was most likely written; whether it was inserted or updated, and its id, are unknown. `:`failed after it was sent \u2014 ${u}. The row MAY have been written: Dataverse was asked to read it back, and this failure does not say whether the write happened first. `;return new $i.UpsertOutcomeUnknownError(e,t,n.statusCode,a,`Upsert of '${e}' (${s}) with reportCreated ${c}Nothing was re-sent. Read the row by its key before deciding to re-run; re-running the same upsert writes the same values again.`,n)}async function Yoe(e,t,n){var r,i;if(n.length===0)return[];let o=await(0,Co.resolveEntitySetName)(e,t),a=n.map(c=>({"@odata.type":`Microsoft.Dynamics.CRM.${t}`,...Tp(c)})),s=`/${o}/Microsoft.Dynamics.CRM.CreateMultiple`,l=(i=(r=(0,pi.ensureSuccess)(await e.post(s,{Targets:a}),e.apiUrl(s)).body)===null||r===void 0?void 0:r.Ids)!==null&&i!==void 0?i:[];if(l.length!==n.length)throw new $i.InvalidArgumentError(`CreateMultiple on '${t}' returned ${l.length} id(s) for ${n.length} row(s)`);return l}Xt.createRecordsBulk=Yoe;async function Qoe(e,t,n,r){let i=(0,ar.normalizeGuid)(n,"id"),o=(0,ar.normalizeGuid)(r.targetId,"targetId"),a=await(0,Co.resolveEntitySetName)(e,t),s=await(0,Co.resolveEntitySetName)(e,r.targetEntity),u=(0,ar.assertODataName)(r.relationshipName,"relationshipName"),l=`/${a}(${i})/${u}/$ref`,c={"@odata.id":e.apiUrl(`/${s}(${o})`)};(0,pi.ensureSuccess)(await e.post(l,c),e.apiUrl(l))}Xt.associateRecords=Qoe;async function Xoe(e,t,n,r,i){let o=(0,ar.normalizeGuid)(n,"id"),a=(0,ar.normalizeGuid)(i,"targetId"),s=await(0,Co.resolveEntitySetName)(e,t),u=(0,ar.assertODataName)(r,"relationshipName"),l=`/${s}(${o})/${u}(${a})/$ref`;(0,pi.ensureSuccess)(await e.delete(l),e.apiUrl(l))}Xt.disassociateRecords=Xoe});var h0=C(m0=>{"use strict";Object.defineProperty(m0,"__esModule",{value:!0});m0.HEADER_NAV_BOOLEAN_RULE=void 0;m0.HEADER_NAV_BOOLEAN_RULE="headerAndNavigationRefresh-must-be-boolean"});var XA=C(So=>{"use strict";Object.defineProperty(So,"__esModule",{value:!0});So.classifyValueAnswer=So.parseVariableToken=So.composeVariableToken=So.UNSETTLED_TOKEN=void 0;var nu=pe();So.UNSETTLED_TOKEN="?";var Zoe=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function eae(e,t){return(0,nu.isVersionToken)(e)?t===void 0?e:`${e} ${t.rowId}=${t.token}`:null}So.composeVariableToken=eae;function tae(e,t){if(typeof e!="string")return{kind:"none"};let n=e.split(" ");if(n.length<1||n.length>2||n.some(s=>s==="")||!(0,nu.isVersionToken)(n[0]))return{kind:"none"};let r=n[0];if(n.length===1)return t===null?{kind:"versioned",definition:r}:{kind:"none"};let i=n[1].indexOf("="),o=i===-1?"":n[1].slice(0,i),a=i===-1?"":n[1].slice(i+1);return Zoe.test(o)?a===So.UNSETTLED_TOKEN?{kind:"unsettled",definition:r,rowId:o}:!(0,nu.isVersionToken)(a)||t===null||o!==t.toLowerCase()?{kind:"none"}:{kind:"versioned",definition:r,value:{rowId:o,token:a}}:{kind:"none"}}So.parseVariableToken=tae;function nae(e,t){if(!("response"in t))return"unknown";let{response:n}=t,r=n.status;return r>=200&&r<300?e==="DELETE"?"deleted":(0,nu.isVersionToken)((0,nu.readEtag)(n))?"written":"unversioned":r===0||nu.AMBIGUOUS_WRITE_STATUSES.has(r)?"unknown":r===500&&((0,nu.isSqlDeadlockVictim)(n)||(0,nu.isTransactionNotStarted)(n))?"refused":r>=500||r<400?"unknown":"refused"}So.classifyValueAnswer=nae});var g0=C(Xi=>{"use strict";Object.defineProperty(Xi,"__esModule",{value:!0});Xi.isTransportFailure=Xi.variableTransportFailure=Xi.variableRefusal=Xi.isValueConflict=Xi.platformErrorCode=void 0;var Op=Y(),rae=XA(),iae=pe(),oae=new Set(["0x80040217","0x80040216","0x80072013"]),aae=new Set(["0x80040216"]),sae={"0x80072040":"the caller cannot reach the Key Vault the reference names (or the reference is wrong)","0x80072049":"the value is not an Azure Key Vault secret reference","0x80044331":"a value is longer than the platform allows","0x80040265":"the platform refused the row (for a Secret: an empty reference is not accepted)","0x8004f01f":"another component (a flow, an app) depends on it"};function eC(e){var t;let n=(t=e?.error)===null||t===void 0?void 0:t.code;return typeof n=="string"&&/^0x[0-9a-f]{1,8}$/i.test(n)?n.toLowerCase():void 0}Xi.platformErrorCode=eC;function ZA(e){let t=e.schemaName?` '${e.schemaName}'`:"",n=e.rowId?`, value row ${e.rowId}`:"";return`${e.operation} of environment variable${t} (${e.id}${n})`}function QM(e){if(e.status===412)return!0;let t=eC(e.body);return t!==void 0&&oae.has(t)&&(e.status===400||e.status===404&&t==="0x80040217")}Xi.isValueConflict=QM;function uae(e,t,n,r){let i=eC(n.body),o=r==="value"?QM(n):n.status===412||i!==void 0&&aae.has(i),a=i===void 0?void 0:sae[i],s=(0,rae.classifyValueAnswer)("PATCH",{response:n})==="unknown",u=`HTTP ${n.status}${i?` ${i}`:""}`+(a?` \u2014 ${a}`:""),l=(s?`${ZA(e)} got an answer that does not say whether it was applied (${u}): the outcome is unknown`:`${ZA(e)} was refused: ${u}`)+" (the platform message is withheld: it can quote the value).";return o?new Op.SdkError(iae.VERSION_CONFLICT_CODE,`${l} Re-fetch and re-apply the change.`):new Op.ConnectionError(t,n.status,l,{status:n.status,...i?{code:i}:{}})}Xi.variableRefusal=uae;function lae(e,t,n){let r=n instanceof Op.ConnectionError?n.cause:n,i=r instanceof Error?r.name:"Error",o=r?.code,a=typeof o=="string"&&/^[A-Z0-9_]{1,40}$/i.test(o)?o:void 0;return new Op.ConnectionError(t,0,`${ZA(e)} got no answer (${i}${a?` ${a}`:""}): whether it was applied is unknown.`,{status:0,name:i,...a?{code:a}:{}})}Xi.variableTransportFailure=lae;function cae(e){return e instanceof Op.ConnectionError&&e.statusCode===0}Xi.isTransportFailure=cae});var Jc=C(_t=>{"use strict";Object.defineProperty(_t,"__esModule",{value:!0});_t.foldVariableValueComponents=_t.findEnvironmentVariable=_t.resolveEnvironmentVariables=_t.environmentVariableApi=_t.readDeleteDependents=_t.ENVIRONMENT_VARIABLE_VALUE_COMPONENT=_t.ENVIRONMENT_VARIABLE_DEFINITION_COMPONENT=_t.ENVIRONMENT_VARIABLE_TYPE_CODES=void 0;var y0=Ke(),tC=Zo(),No=g0(),ru=XA(),mi=Y(),sr=pe(),dae=ft(),Ar=ae();_t.ENVIRONMENT_VARIABLE_TYPE_CODES={string:1e8,number:100000001,boolean:100000002,json:100000003,dataSource:100000004,secret:100000005};_t.ENVIRONMENT_VARIABLE_DEFINITION_COMPONENT=380;_t.ENVIRONMENT_VARIABLE_VALUE_COMPONENT=381;var oC="environmentvariabledefinition_environmentvariablevalue",nC="envdefinition_envdefinition",fae="environmentvariabledefinitionid,schemaname,displayname,description,type,defaultvalue,isrequired,valueschema,apiid,parameterkey,_parentdefinitionid_value,secretstore,hint,learnmoreurl,inputcontrolconfig",pae="environmentvariablevalueid,value";function mae(e){let t=e.split("/"),n=[[1,"subscriptions"],[3,"resourcegroups"],[5,"providers"],[6,"microsoft.keyvault"],[7,"vaults"],[9,"secrets"]];return(t.length===11||t.length===12)&&t[0]===""&&n.every(([r,i])=>t[r].toLowerCase()===i)&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(t[2])&&[4,8,10,11].every(r=>r>=t.length||t[r]!=="")}var b0="environmentvariabledefinitions",zc="environmentvariablevalues";function Hc(e){return`/${b0}(${e})`}function Kc(e,t){return new mi.ConnectionError(e,200,`the response could not be read as ${t}`)}function hae(e){let t=e[oC];return Array.isArray(t)&&t.every(n=>n!==null&&typeof n=="object")?t:void 0}function gae(e,t){if(e.type!==_t.ENVIRONMENT_VARIABLE_TYPE_CODES.secret)return;let n=`'${String(e.schemaname)}' (${String(e.environmentvariabledefinitionid)})`,r=o=>{throw new mi.SdkError("ENVIRONMENT_VARIABLE_SECRET_UNRECOGNIZED",`Refusing to fetch the Secret environment variable ${n}: ${o}. The SDK never reads a secret: a Secret it manages holds an Azure Key Vault secret reference. Manage this variable in the maker portal.`)};e.secretstore!==void 0&&e.secretstore!==null&&e.secretstore!==0&&r("its secret is stored by Dataverse, not referenced in Azure Key Vault");let i=o=>o==null||typeof o=="string"&&mae(o);i(e.defaultvalue)||r("its default value is not an Azure Key Vault secret reference"),t.some(o=>!i(o.value))&&r("its current value is not an Azure Key Vault secret reference")}function yae(e){let t=e["@odata.etag"];return typeof t=="string"?t:void 0}function t2(e,t){throw new mi.SdkError(sr.UPDATE_NO_ETAG_CODE,`Refusing to push environmentVariable '${e}': ${t?"the concurrency token held for it is not a version of this variable":"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 environmentVariable and re-apply the change.`)}function n2(e,t){return new mi.SdkError("ENVIRONMENT_VARIABLE_VALUE_UNSETTLED",`Refusing to ${t} environmentVariable '${e}': the outcome of its last value write is unknown (or the server returned no version for it), so no request can be conditioned on it. Re-fetch it \u2014 fetchArtifact('environmentVariable', id, { overwrite: true }) when you have local edits \u2014 and re-apply the change.`)}async function rC(e,t){let n;try{n={response:await t()}}catch(r){if(!(0,No.isTransportFailure)(r))throw r;n={transport:r}}return{answer:n,outcome:(0,ru.classifyValueAnswer)(e,n)}}function iC(e,t,n){return"response"in n?(0,No.variableRefusal)(e,t,n.response,"value"):(0,No.variableTransportFailure)(e,t,n.transport)}async function XM(e,t,n){let r;try{r=await n()}catch(i){throw(0,No.isTransportFailure)(i)?(0,No.variableTransportFailure)(e,t,i):i}if(r.status<200||r.status>=300)throw(0,No.variableRefusal)(e,t,r,"definition");return r}async function ZM(e,t,n,r,i){let o=n.value;if(o.op==="none")return{part:r};let a=e.withoutSolution(),s=(0,Ar.normalizeGuid)(o.id,"currentValue.id"),u={operation:`${o.op} value`,id:t,rowId:s,schemaName:n.schemaName},l,c;if(o.op==="create"){let d=(0,sr.echoWrite)("environmentvariablevalueid"),f=`/${zc}${d.query}`;l=a.apiUrl(f),c=await rC("POST",()=>a.post(f,{environmentvariablevalueid:s,value:o.value,"[email protected]":Hc(t)},d.options))}else if(r||t2(t,null),o.op==="update"){let d=(0,sr.echoWrite)("environmentvariablevalueid",{"If-Match":r.token}),f=`/${zc}(${s})${d.query}`;l=a.apiUrl(f),c=await rC("PATCH",()=>a.patch(f,{value:o.value},d.options))}else{let d=`/${zc}(${s})`;l=a.apiUrl(d),c=await rC("DELETE",()=>a.delete(d,{headers:{"If-Match":r.token}}))}switch(c.outcome){case"deleted":return{part:void 0};case"written":return{part:{rowId:s,token:(0,sr.readEtag)(c.answer.response)}};case"unversioned":return{part:{rowId:s,token:ru.UNSETTLED_TOKEN},warning:`Saved; the server returned no version for the value of environment variable '${n.schemaName}', so the next push is refused until it is re-fetched (fetchArtifact).`};case"refused":{let d=iC(u,l,c.answer);if(!i)throw d;return{part:r,warning:`The definition of environment variable '${n.schemaName}' was saved; the value was NOT: ${d.message} The value change is kept locally \u2014 push again (a conflict needs a re-fetch).`,intentPending:!0}}default:{if(!i)throw iC(u,l,c.answer);return{part:{rowId:s,token:ru.UNSETTLED_TOKEN},warning:`The definition of environment variable '${n.schemaName}' was saved; whether the value was is UNKNOWN (${iC(u,l,c.answer).message}). The next push and delete are refused until it is re-fetched: fetchArtifact('environmentVariable', id, { overwrite: true }).`,intentPending:!0}}}}function e2(e,t,n){return{id:e,etag:(0,ru.composeVariableToken)(t,n.part),...n.warning?{warnings:[n.warning]}:{},...n.intentPending?{intentPending:!0}:{}}}async function r2(e,t,n){var r;if(n!==void 0)try{let i=`/RetrieveDependenciesForDelete(ObjectId=@p1,ComponentType=@p2)?@p1=${(0,Ar.normalizeGuid)(t,"id")}&@p2=${n}`,a=(r=(0,sr.ensureSuccess)(await e.get(i),e.apiUrl(i)).body)===null||r===void 0?void 0:r.value;return Array.isArray(a)?a.map(s=>{var u;let l=Number(s.dependentcomponenttype);return{table:l===29?"workflow":l===380?"environmentvariabledefinition":"solutioncomponent",id:String((u=s.dependentcomponentobjectid)!==null&&u!==void 0?u:"").toLowerCase(),...Number.isInteger(l)?{componentType:l}:{}}}):void 0}catch{return}}_t.readDeleteDependents=r2;async function bae(e,t,n){var r,i,o,a,s;let u=(0,Ar.normalizeGuid)(t,"id"),l=n?.snapshot,c=!((r=l?.currentValue)===null||r===void 0)&&r.id?(0,Ar.normalizeGuid)(l.currentValue.id,"currentValue.id"):null,d=(0,ru.parseVariableToken)((i=n?.token)!==null&&i!==void 0?i:null,c);if(d.kind==="unsettled")throw n2(u,"delete");if(d.kind==="none"||!l)throw new mi.SdkError(sr.DELETE_NO_ETAG_CODE,`Refusing to delete environmentVariable '${u}': no usable concurrency token is held for it, so the delete could not be made conditional and could remove what another writer changed. Fetch it first (fetchArtifact).`);if(!e.supportsAtomicBatch)throw new mi.SdkError("ENVIRONMENT_VARIABLE_DELETE_NOT_ATOMIC",`Refusing to delete environmentVariable '${u}': the injected HttpClient does not implement postRaw(), and the definition and its value can only be deleted together, guarded, in one change set. Nothing was sent.`);if(l.type==="secret"&&d.value===void 0)throw new mi.SdkError("ENVIRONMENT_VARIABLE_DELETE_UNGUARDED",`Refusing to delete the Secret environment variable '${u}': it holds no value, and for a Secret the SDK cannot build the guard that proves no value was created since it was read (the platform refuses an empty Secret value row), so the delete could remove a value it never saw. This is a limit of the SDK, not of the variable: delete it in the maker portal. Nothing was sent.`);let f=`${Hc(u)}${(0,Ar.odataQuery)([["$select","environmentvariabledefinitionid"],["$expand",`${oC}($select=environmentvariablevalueid),${nC}($select=environmentvariabledefinitionid,schemaname)`]])}`,p=e.apiUrl(f),m=await e.get(f);if(m.status===404)throw new mi.VersionConflictError("environmentVariable",u,(o=n?.token)!==null&&o!==void 0?o:null,null,"The variable no longer exists on the server (another writer deleted it).");(0,sr.ensureSuccess)(m,p);let h=(a=m.body)===null||a===void 0?void 0:a[nC];if(!Array.isArray(h))throw Kc(p,"the variable's child definitions, so whether the delete would cascade is unknown");if(h.length===0&&(0,y0.pageEnd)(m.body,nC).kind!=="end")throw Kc(p,"the variable's child definitions \u2014 the answer carries none but does not say it is the end \u2014 so whether the delete would cascade is unknown");if(h.length>0){let S=h.map(R=>{var x;return{table:"environmentvariabledefinition",id:String((x=R.environmentvariabledefinitionid)!==null&&x!==void 0?x:"").toLowerCase(),componentType:_t.ENVIRONMENT_VARIABLE_DEFINITION_COMPONENT}});throw new mi.ArtifactInUseError("environmentVariable",u,`Refusing to delete environmentVariable '${u}': ${S.length} data-source variable(s) depend on it, and the platform would delete them \u2014 with their values \u2014 together with it, without saying so. Delete or re-parent them first. Nothing was deleted.`,S)}let g=e.withoutSolution(),y={method:"DELETE",path:Hc(u),etag:d.definition},b=d.value?[{method:"DELETE",path:`/${zc}(${d.value.rowId})`,etag:d.value.token},y]:[{method:"POST",path:`/${zc}`,body:{environmentvariablevalueid:(0,dae.newId)(),"[email protected]":Hc(u)}},y],{body:E,batchId:w,contentIds:_}=(0,tC.renderChangeSet)(g,b),I=g.apiUrl("/$batch"),T={operation:"delete",id:u,schemaName:l.schemaName},O;try{O=await g.postBatch(E,w)}catch(S){throw(0,No.isTransportFailure)(S)?(0,No.variableTransportFailure)(T,I,S):S}let v=(0,tC.parseChangeSetParts)(O.body,_),N=v?.find(S=>S.status<200||S.status>=300);if(N){let S=(0,tC.partResponse)(N),R=(0,No.platformErrorCode)(S.body);throw S.status===412||S.status===404&&R==="0x80040217"||S.status===400&&R==="0x80072013"?new mi.VersionConflictError("environmentVariable",u,(s=n?.token)!==null&&s!==void 0?s:null,null,"Another writer changed, created or deleted its definition or value since it was fetched; nothing was deleted."):R==="0x8004f01f"?new mi.ArtifactInUseError("environmentVariable",u,`Refusing to delete environmentVariable '${u}': another component (a flow, an app) depends on it; nothing was deleted. Remove the dependency first.`,await r2(e,u,_t.ENVIRONMENT_VARIABLE_DEFINITION_COMPONENT)):(0,No.variableRefusal)(T,I,S,"definition")}if(O.status<200||O.status>=300)throw(0,No.variableRefusal)(T,I,O,"definition");if(!v||v.length!==b.length)throw new mi.ConnectionError(I,O.status,`the delete of environmentVariable '${u}' cannot be confirmed: its change-set response ${v?`reported ${v.length} result(s) for ${b.length} operation(s)`:"could not be parsed"}, so whether it was deleted is unknown. Re-fetch it to see.`)}_t.environmentVariableApi={async get(e,t){let n=(0,Ar.normalizeGuid)(t,"id"),r=`${Hc(n)}${(0,Ar.odataQuery)([["$select",fae],["$expand",`${oC}($select=${pae})`]])}`,i=e.apiUrl(r),o=(0,sr.ensureSuccess)(await e.get(r),i),a=o.body,s=a?hae(a):void 0;if(!a||!s||s.length>1)throw Kc(i,"an environment variable with at most one value");if(!Object.values(_t.ENVIRONMENT_VARIABLE_TYPE_CODES).includes(a.type))throw new mi.SdkError("ENVIRONMENT_VARIABLE_TYPE_UNRECOGNIZED",`Environment variable '${n}' has a type the SDK does not know (${JSON.stringify(a.type)}).`);gae(a,s);let u=(0,sr.readEtag)(o),l=s[0],c;if(!l)c=(0,ru.composeVariableToken)(u);else{let d=yae(l);c=d===void 0?null:(0,ru.composeVariableToken)(u,{rowId:(0,Ar.normalizeGuid)(String(l.environmentvariablevalueid),"environmentvariablevalueid"),token:d})}return{raw:a,etag:c}},async list(e){let t=`/${b0}${(0,Ar.odataQuery)([["$select","environmentvariabledefinitionid,schemaname,displayname"]])}`;return(await(0,y0.collectPages)(e,t,"listArtifacts('environmentVariable')")).map(r=>{var i,o,a;return{type:"environmentVariable",id:String((i=r.environmentvariabledefinitionid)!==null&&i!==void 0?i:""),name:String((a=(o=r.displayname)!==null&&o!==void 0?o:r.schemaname)!==null&&a!==void 0?a:""),isDirty:!1}})},async create(e,t,n){let r=t,i=(0,sr.echoWrite)("environmentvariabledefinitionid"),o=`/${b0}${i.query}`,a=e.apiUrl(o),s={operation:"create definition",id:n??"(new)",schemaName:r.schemaName},u=await XM(s,a,()=>{var d;return e.post(o,(0,sr.withClientMintedId)((d=r.definition)!==null&&d!==void 0?d:{},"environmentvariabledefinitionid",n),i.options)}),l=(0,sr.resolveCreatedId)(u,"environmentvariabledefinitionid","environment variable",n),c=await ZM(e,l,r,void 0,!0);return e2(l,(0,sr.readEtag)(u),c)},async update(e,t,n,r){let i=n,o=(0,Ar.normalizeGuid)(t,"id"),a=(0,ru.parseVariableToken)(r,i.heldRowId);if(a.kind==="unsettled")throw n2(o,"push");a.kind==="none"&&t2(o,r);let s=a.definition,u=!1;if(i.definition){let c=(0,sr.echoWrite)("environmentvariabledefinitionid",{"If-Match":a.definition}),d=`${Hc(o)}${c.query}`,f=await XM({operation:"update definition",id:o,schemaName:i.schemaName},e.apiUrl(d),()=>e.patch(d,i.definition,c.options));s=(0,sr.readEtag)(f),u=!0}let l=await ZM(e,o,i,a.value,u);return e2(o,s,l)},delete(e,t,n){return bae(e,t,n)}};async function i2(e,t,n){let r=`/${b0}${(0,Ar.odataQuery)([["$select","environmentvariabledefinitionid,schemaname"],["$filter",`schemaname eq '${(0,Ar.odataLiteral)(t)}'`],...n!==void 0?[["$top",String(n)]]:[]])}`,i=e.apiUrl(r),o;if(n===void 0)o=await(0,y0.collectPages)(e,r,"resolveArtifact('environmentVariable')");else{let a=(0,sr.ensureSuccess)(await e.get(r),i).body;if(o=a?.value,Array.isArray(o)&&!(0,y0.boundedPageComplete)(a,o.length,n))throw Kc(i,"a complete list of environment variables (the answer says more rows exist)")}if(!Array.isArray(o))throw Kc(i,"a list of environment variables");return o.map(a=>({id:String(a.environmentvariabledefinitionid),name:String(a.schemaname)}))}_t.resolveEnvironmentVariables=i2;async function vae(e,t){let n=await i2(e,t,2);if(n.length>1)throw new mi.AmbiguousArtifactError("environmentVariable",t,n.length);return n.length===1?n[0].id:null}_t.findEnvironmentVariable=vae;async function wae(e,t){var n;let r=[],i=new Set,o=[];for(let u of t){if(u.componentType===_t.ENVIRONMENT_VARIABLE_DEFINITION_COMPONENT){try{i.add((0,Ar.normalizeGuid)(u.objectId,"objectid"))}catch(l){r.push({component:u,error:l})}continue}if(u.componentType!==_t.ENVIRONMENT_VARIABLE_VALUE_COMPONENT){o.push(u);continue}try{let l=`/${zc}(${(0,Ar.normalizeGuid)(u.objectId,"objectid")})${(0,Ar.odataQuery)([["$select","_environmentvariabledefinitionid_value"]])}`,d=(n=(0,sr.ensureSuccess)(await e.get(l),e.apiUrl(l)).body)===null||n===void 0?void 0:n._environmentvariabledefinitionid_value;if(typeof d!="string")throw Kc(e.apiUrl(l),"the value's definition");i.add((0,Ar.normalizeGuid)(d,"_environmentvariabledefinitionid_value"))}catch(l){r.push({component:u,error:l})}}let a=[...i].map(u=>({objectId:u,componentType:_t.ENVIRONMENT_VARIABLE_DEFINITION_COMPONENT})),s=u=>u.objectId.toLowerCase().replace(/^\{|\}$/g,"");return{components:[...o,...a].sort((u,l)=>u.componentType-l.componentType||(s(u)<s(l)?-1:s(u)>s(l)?1:0)),failed:r}}_t.foldVariableValueComponents=wae});var v0=C(wn=>{"use strict";Object.defineProperty(wn,"__esModule",{value:!0});wn.parseCustomApiToken=wn.composeCustomApiToken=wn.canonicalGuid=wn.EXPANSION_CAP=wn.optionName=wn.CUSTOM_API_TYPE_CODES=wn.CUSTOM_API_STEP_CODES=wn.CUSTOM_API_BINDING_CODES=void 0;var o2=pe();wn.CUSTOM_API_BINDING_CODES={global:0,entity:1,entityCollection:2};wn.CUSTOM_API_STEP_CODES={none:0,asyncOnly:1,syncAndAsync:2};wn.CUSTOM_API_TYPE_CODES={boolean:0,dateTime:1,decimal:2,entity:3,entityCollection:4,entityReference:5,float:6,integer:7,money:8,picklist:9,string:10,stringArray:11,guid:12};function Eae(e,t){return Object.keys(e).find(n=>e[n]===t)}wn.optionName=Eae;wn.EXPANSION_CAP=5e3;var Aae=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,Cae=e=>String(e??"").toLowerCase().replace(/^\{|\}$/g,"");wn.canonicalGuid=Cae;function Sae(e,t){let n=(r,i)=>i.map(([o,a])=>[(0,wn.canonicalGuid)(o),a]).sort(([o],[a])=>o<a?-1:o>a?1:0).map(([o,a])=>` ${r}${o}=${a}`);return[e,...n("p",t.requestParameters),...n("r",t.responseProperties)].join("")}wn.composeCustomApiToken=Sae;function Nae(e,t){if(typeof e!="string")return;let[n,...r]=e.split(" ");if(!(0,o2.isVersionToken)(n))return;let i={api:n,requestParameters:new Map,responseProperties:new Map};for(let a of r){let s=/^([pr])([0-9a-f-]{36})=(\S+)$/.exec(a);if(!s||!Aae.test(s[2])||!(0,o2.isVersionToken)(s[3]))return;let u=s[1]==="p"?i.requestParameters:i.responseProperties;if(u.has(s[2]))return;u.set(s[2],s[3])}let o=(a,s)=>{let u=new Set(s.map(wn.canonicalGuid));return u.size===s.length&&u.size===a.size&&[...u].every(l=>a.has(l))};return o(i.requestParameters,t.requestParameters)&&o(i.responseProperties,t.responseProperties)?i:void 0}wn.parseCustomApiToken=Nae});var C0=C(ut=>{"use strict";Object.defineProperty(ut,"__esModule",{value:!0});ut.foldCustomApiChildComponents=ut.findCustomApi=ut.resolveCustomApis=ut.customApiApi=ut.SYSTEM_ADMINISTRATOR_ROLE_TEMPLATE=ut.CUSTOM_API_OPTION_UNRECOGNIZED_CODE=ut.CUSTOM_API_DELETE_UNVERIFIABLE_CODE=ut.CUSTOM_API_LABELS_UNSUPPORTED_CODE=ut.CUSTOM_API_NOT_ATOMIC_CODE=void 0;var ss=Ke(),ml=Zo(),_ae=Jc(),p2=g0(),rt=v0(),m2=il(),Zt=Y(),en=pe(),Kn=ae();ut.CUSTOM_API_NOT_ATOMIC_CODE="CUSTOM_API_NOT_ATOMIC";ut.CUSTOM_API_LABELS_UNSUPPORTED_CODE="CUSTOM_API_LABELS_UNSUPPORTED";ut.CUSTOM_API_DELETE_UNVERIFIABLE_CODE="CUSTOM_API_DELETE_UNVERIFIABLE";ut.CUSTOM_API_OPTION_UNRECOGNIZED_CODE="CUSTOM_API_OPTION_UNRECOGNIZED";ut.SYSTEM_ADMINISTRATOR_ROLE_TEMPLATE="627090ff-40a3-4053-8790-584edc5be201";var Dp={headers:{"If-None-Match":"null"}},E0="customapis",Iae="customapiid,uniquename,name,displayname,description,bindingtype,boundentitylogicalname,isfunction,isprivate,allowedcustomprocessingsteptype,workflowsdkstepenabled,executeprivilegename,_plugintypeid_value",a2="uniquename,name,displayname,description,type,logicalentityname",da=[{kind:"requestParameter",nav:"CustomAPIRequestParameters",set:"customapirequestparameters",pk:"customapirequestparameterid",select:`customapirequestparameterid,${a2},isoptional`},{kind:"responseProperty",nav:"CustomAPIResponseProperties",set:"customapiresponseproperties",pk:"customapiresponsepropertyid",select:`customapiresponsepropertyid,${a2}`}],w0=e=>da.find(t=>t.kind===e),sC=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,hl=e=>`/${E0}(${e})`;function Yc(e,t){return new Zt.ConnectionError(e,200,`incomplete read: ${t} \u2014 never read as "no rows". Retry.`)}function aC(e){return da.map(t=>`${t.nav}($select=${e(t)})`).join(",")}async function h2(e,t,n,r,i){let o=t[n.nav],a=t[`${n.nav}@odata.nextLink`],s=(0,ss.moreRecordsClaim)(t,n.nav);if(!Array.isArray(o)||a!==void 0&&(typeof a!="string"||a==="")||s==="malformed")throw Yc(i,`the API's ${n.nav}`);let u=o;(o.length>=rt.EXPANSION_CAP||s==="more"||a!==void 0)&&(u=await(0,ss.collectPages)(e,`/${n.set}${(0,Kn.odataQuery)([["$select",n.select],["$filter",`_customapiid_value eq ${r}`]])}`,`fetchArtifact('customApi') ${n.nav}`,void 0,Dp));let l=new Set;for(let c of u){let d=c?.[n.pk],f=c?.["@odata.etag"];if(c===null||typeof c!="object"||typeof d!="string"||!sC.test((0,rt.canonicalGuid)(d))||!(0,en.isVersionToken)(f)||l.has((0,rt.canonicalGuid)(d)))throw Yc(i,`a row of the API's ${n.nav} without its id or version, or listed twice`);l.add((0,rt.canonicalGuid)(d))}return u}function Tae(e,t){let n=(r,i,o)=>{if((0,rt.optionName)(i,o)===void 0)throw new Zt.SdkError(ut.CUSTOM_API_OPTION_UNRECOGNIZED_CODE,`Custom API '${t}' has a ${r} the SDK does not know (${JSON.stringify(o)}); refusing to guess it.`)};n("bindingtype",rt.CUSTOM_API_BINDING_CODES,e.bindingtype),n("allowedcustomprocessingsteptype",rt.CUSTOM_API_STEP_CODES,e.allowedcustomprocessingsteptype);for(let r of da)for(let i of e[r.nav])n(`${r.nav} type`,rt.CUSTOM_API_TYPE_CODES,i.type)}function s2(e,t){if(!(0,en.isVersionToken)(e))return null;let n=r=>t[r.nav].map(i=>[(0,rt.canonicalGuid)(String(i[r.pk])),String(i["@odata.etag"])]);return(0,rt.composeCustomApiToken)(e,{requestParameters:n(da[0]),responseProperties:n(da[1])})}function Oae(e,t){throw new Zt.SdkError(en.UPDATE_NO_ETAG_CODE,`Refusing to push customApi '${e}': ${t?"the concurrency token held for it does not name exactly the rows last synced":"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 customApi and re-apply the change.`)}async function Dae(e,t,n){var r;let i="/RetrieveProvisionedLanguages()",o,a="its provisioned languages could not be read";try{let u=await e.get(i);u.status>=200&&u.status<300&&(o=(r=u.body)===null||r===void 0?void 0:r.RetrieveProvisionedLanguages)}catch{o=void 0}let s=Array.isArray(o)&&o.every(u=>typeof u=="number"&&Number.isInteger(u)&&u>0);if(!(s&&o.length===1))throw s&&(a=`it provisions ${o.length} languages`),new Zt.SdkError(ut.CUSTOM_API_LABELS_UNSUPPORTED_CODE,`Refusing to push customApi '${t}': it changes the localized label(s) ${n.join(", ")}, and ${a} \u2014 which language a write addresses there is not established, so the SDK does not write it. Edit labels in the maker portal; every other change can be pushed without them. Nothing was sent.`)}function Pae(e,t,n){let r={Prefer:"return=representation"},i=[],o=(a,s)=>(a==="requestParameter"?n.requestParameters:n.responseProperties).get(s);for(let a of t.deletes){let s=w0(a.kind);i.push({target:a.kind,id:a.id,op:{method:"DELETE",path:`/${s.set}(${a.id})`,etag:o(a.kind,a.id)}})}t.api&&i.push({target:"api",id:e,op:{method:"PATCH",path:`${hl(e)}?$select=customapiid`,body:t.api,etag:n.api,headers:r}});for(let a of t.posts){let s=w0(a.kind);i.push({target:a.kind,id:a.id,op:{method:"POST",path:`/${s.set}?$select=${s.pk}`,body:{...a.body,"[email protected]":hl(e)},headers:r}})}for(let a of t.patches){let s=w0(a.kind);i.push({target:a.kind,id:a.id,op:{method:"PATCH",path:`/${s.set}(${a.id})?$select=${s.pk}`,body:a.body,etag:o(a.kind,a.id),headers:r}})}return i}function u2(e,t,n){let r=(0,p2.platformErrorCode)(t.body);if(t.status===412||t.status===404&&r==="0x80040217"&&e.target!=="api"||t.status===400&&r==="0x80040216"||t.status===400&&r==="0x80072013"&&e.op.method==="POST")return new Zt.SdkError(en.VERSION_CONFLICT_CODE,`${e.op.method} of ${e.target} '${e.id}' was refused (${t.status}${r?` ${r}`:""}): another writer changed, added or deleted it since the fetch. Nothing was written.`);try{(0,en.ensureSuccess)(t,n)}catch(o){return o}return new Zt.ConnectionError(n,t.status,"unexpected refusal")}async function Rae(e,t){var n;if(t.length===1){let[c]=t,{op:d}=c,f={...(n=d.headers)!==null&&n!==void 0?n:{},...d.etag?{"If-Match":d.etag}:{}},p=d.method==="DELETE"?await e.delete(d.path,{headers:f}):d.method==="PATCH"?await e.patch(d.path,d.body,{headers:f}):await e.post(d.path,d.body,{headers:f});if(p.status<200||p.status>=300)throw u2(c,p,e.apiUrl(d.path));return[p]}let{body:r,batchId:i,contentIds:o}=(0,ml.renderChangeSet)(e,t.map(c=>c.op)),a=e.apiUrl("/$batch"),s=await e.postBatch(r,i),u=(0,ml.parseChangeSetParts)(s.body,o),l=u?.find(c=>c.status<200||c.status>=300);if(l){let c=t[o.indexOf(l.contentId)];throw u2(c,(0,ml.partResponse)(l),e.apiUrl(c.op.path))}if((0,en.ensureSuccess)(s,a),!u||u.length!==t.length)throw new Zt.ConnectionError(a,s.status,`the change set's answer ${u?`reported ${u.length} result(s) for ${t.length} operation(s)`:"could not be parsed"}, so whether it was applied is unknown. Nothing is re-sent; re-fetch to see.`);return o.map(c=>(0,ml.partResponse)(u.find(d=>d.contentId===c)))}function kae(e,t){var n;let r=e.target==="api"?"customapiid":w0(e.target).pk,i=(n=t.body)===null||n===void 0?void 0:n[r],o=(0,en.readEtag)(t);return typeof i=="string"&&(0,rt.canonicalGuid)(i)===(0,rt.canonicalGuid)(e.id)&&(0,en.isVersionToken)(o)?o:void 0}async function $ae(e,t,n){var r,i,o,a;let s=(0,Kn.normalizeGuid)(t,"id"),u=n?.snapshot,l=u?(0,rt.parseCustomApiToken)((r=n?.token)!==null&&r!==void 0?r:null,{requestParameters:((i=u.requestParameters)!==null&&i!==void 0?i:[]).map(b=>(0,rt.canonicalGuid)(String(b.id))),responseProperties:((o=u.responseProperties)!==null&&o!==void 0?o:[]).map(b=>(0,rt.canonicalGuid)(String(b.id)))}):void 0;if(!l)throw new Zt.SdkError(en.DELETE_NO_ETAG_CODE,`Refusing to delete customApi '${s}': no usable concurrency token is held for it, so the delete could not be made conditional and could remove what another writer changed. Fetch it first (fetchArtifact).`);if(l.requestParameters.size+l.responseProperties.size>0&&!e.supportsAtomicBatch)throw new Zt.SdkError(ut.CUSTOM_API_NOT_ATOMIC_CODE,`Refusing to delete customApi '${s}': the injected HttpClient does not implement postRaw(), and the API's parameters and properties can only be deleted with it, each guarded, in one change set. Nothing was sent.`);await Lae(e,s);let d=await Uae(e,s),f=[],p=await qae(e,s,l,d.apiReferences,f);if(await Bae(e,s,p,d.messageReferences,f),f.length>0)throw new Zt.ArtifactInUseError("customApi",s,`Refusing to delete customApi '${s}': ${f.length} row(s) of other tables reference it or its message (${[...new Set(f.map(b=>b.table))].join(", ")}), and the platform would delete, unlink or refuse with them. Nothing was deleted. Remove those references first.`,f);let m=[...[...l.requestParameters].map(([b,E])=>({method:"DELETE",path:`/customapirequestparameters(${b})`,etag:E})),...[...l.responseProperties].map(([b,E])=>({method:"DELETE",path:`/customapiresponseproperties(${b})`,etag:E})),{method:"DELETE",path:hl(s),etag:l.api}],h,g=e.apiUrl(hl(s));if(m.length===1){let b=await e.delete(hl(s),{headers:{"If-Match":l.api}});h=b.status<200||b.status>=300?b:void 0}else{let{body:b,batchId:E,contentIds:w}=(0,ml.renderChangeSet)(e,m);g=e.apiUrl("/$batch");let _=await e.postBatch(b,E),I=(0,ml.parseChangeSetParts)(_.body,w),T=I?.find(O=>O.status<200||O.status>=300);if(h=T?(0,ml.partResponse)(T):void 0,!h&&((0,en.ensureSuccess)(_,g),!I||I.length!==m.length))throw new Zt.ConnectionError(g,_.status,`the delete of customApi '${s}' cannot be confirmed: its change-set answer ${I?`reported ${I.length} result(s) for ${m.length} operation(s)`:"could not be parsed"}, so whether it was deleted is unknown. Re-fetch it to see.`)}if(!h)return;let y=(0,p2.platformErrorCode)(h.body);if(h.status===412||h.status===404&&y==="0x80040217")throw new Zt.VersionConflictError("customApi",s,(a=n?.token)!==null&&a!==void 0?a:null,null,"Another writer changed or deleted the API or one of its rows since it was fetched; nothing was deleted.");if(y==="0x8004f01f"||y==="0x80040227"){let b;try{b=await(0,_ae.readDeleteDependents)(e,s,(await(0,m2.resolveCustomApiComponentTypes)(e)).api)}catch{b=void 0}throw new Zt.ArtifactInUseError("customApi",s,`Refusing to delete customApi '${s}': the platform refused it (${y}) because another component depends on it or on its message; nothing was deleted. Remove the dependency first.`,b)}(0,en.ensureSuccess)(h,g)}function hi(e,t,n){let r=new Zt.SdkError(ut.CUSTOM_API_DELETE_UNVERIFIABLE_CODE,`Refusing to delete customApi '${e}': the SDK cannot establish that the delete is safe \u2014 ${t}. Nothing was deleted; delete it in the maker portal, or retry.`);return n===void 0?r:(0,Zt.attachCause)(r,n)}var l2=new WeakMap;async function Lae(e,t){var n,r;let i=l2.get(e);try{if(!i){let l=(n=(0,en.ensureSuccess)(await e.get("/WhoAmI()"),e.apiUrl("/WhoAmI()")).body)===null||n===void 0?void 0:n.UserId;if(typeof l!="string"||!sC.test((0,rt.canonicalGuid)(l)))throw hi(t,"the caller could not be identified (WhoAmI answered without a user id)");i=(0,rt.canonicalGuid)(l),l2.set(e,i)}let o=`/systemusers(${i})${(0,Kn.odataQuery)([["$select","systemuserid"],["$expand","systemuserroles_association($select=_roletemplateid_value)"]])}`,a=(r=(0,en.ensureSuccess)(await e.get(o,Dp),e.apiUrl(o)).body)===null||r===void 0?void 0:r.systemuserroles_association;if(!Array.isArray(a)||a.some(u=>u===null||typeof u!="object"||Array.isArray(u)))throw hi(t,"the caller's roles could not be read");if(!a.some(u=>{let l=u._roletemplateid_value;return typeof l=="string"&&(0,rt.canonicalGuid)(l)===ut.SYSTEM_ADMINISTRATOR_ROLE_TEMPLATE}))throw new Zt.SdkError(ut.CUSTOM_API_DELETE_UNVERIFIABLE_CODE,`Refusing to delete customApi '${t}': the SDK cannot establish that it sees every row the delete would affect (the API's parameters and properties, rows of other tables that reference it, registrations on its message). It can only when the caller directly holds the System Administrator role, and this caller does not. This is a limit of the SDK, not a statement that you may not delete it: delete it in the maker portal. Nothing was deleted.`)}catch(o){throw o instanceof Zt.SdkError&&o.code===ut.CUSTOM_API_DELETE_UNVERIFIABLE_CODE?o:hi(t,"the caller's identity or roles could not be read",o)}}var Mae=new Set(["syncerror","asyncoperation","mailboxtrackingfolder","userentityinstancedata","processsession","bulkdeletefailure","principalobjectattributeaccess"]),xae=new Set(["customapirequestparameter","customapiresponseproperty"]),Fae=new Set(["sdkmessagefilter","sdkmessagepair","customapi"]);function c2(e,t,n){let r=e;if(!r||typeof r!="object"||!Array.isArray(r.value))throw hi(t,`${n} could not be read`);if(Object.prototype.hasOwnProperty.call(r,"@odata.nextLink")||(0,ss.moreRecordsClaim)(r)!=="none")throw hi(t,`${n} were answered incompletely (the answer says more rows exist)`);return r.value}var d2=new WeakMap;async function Uae(e,t){let n=d2.get(e);if(n)return n;try{let r=async(c,d)=>{let f=`/EntityDefinitions(LogicalName='${c}')/OneToManyRelationships${(0,Kn.odataQuery)([["$select","ReferencingEntity,ReferencingAttribute,ReferencedEntityNavigationPropertyName"]])}`;return c2((0,en.ensureSuccess)(await e.get(f),e.apiUrl(f)).body,t,`the relationships of '${c}'`).map(m=>{let h=m,g=h?.ReferencedEntityNavigationPropertyName,y=h?.ReferencingEntity;if(typeof g!="string"||typeof y!="string"||g===""||y==="")throw hi(t,`a relationship of '${c}' could not be read`);return{nav:g,table:y}}).filter(m=>!Mae.has(m.table)&&!d.has(m.table))},i=await r("customapi",xae),o=await r("sdkmessage",Fae),a=[...new Set([...i,...o].map(c=>c.table))],s=new Map;if(a.length>0){let c=`/EntityDefinitions${(0,Kn.odataQuery)([["$select","LogicalName,PrimaryIdAttribute"],["$filter",a.map(f=>`LogicalName eq '${(0,Kn.odataLiteral)(f)}'`).join(" or ")]])}`,d=c2((0,en.ensureSuccess)(await e.get(c),e.apiUrl(c)).body,t,"the referencing tables");for(let f of d){let p=f;typeof p?.LogicalName=="string"&&typeof p.PrimaryIdAttribute=="string"&&p.PrimaryIdAttribute&&s.set(p.LogicalName,p.PrimaryIdAttribute)}}let u=c=>c.map(d=>{let f=s.get(d.table);if(!f)throw hi(t,`the primary id of '${d.table}' could not be read`);return{...d,pk:f}}),l={apiReferences:u(i),messageReferences:u(o)};return d2.set(e,l),l}catch(r){throw r instanceof Zt.SdkError&&r.code===ut.CUSTOM_API_DELETE_UNVERIFIABLE_CODE?r:hi(t,"the relationships to inspect could not be read",r)}}var A0=15;function g2(e,t,n){let r=[e.slice(0,t)];for(let i=t;i<e.length;i+=n)r.push(e.slice(i,i+n));return r}var y2=e=>`${e.nav}($select=${e.pk};$top=1)`;function b2(e,t,n,r){for(let i of t){let o=e[i.nav];if(!Array.isArray(o))throw r(`the read did not answer '${i.nav}'`);if(o.length===0&&(0,ss.pageEnd)(e,i.nav).kind!=="end")throw r(`the read of '${i.nav}' carries no row but does not say it is the end`);for(let a of o){let s=a?.[i.pk];n.push({table:i.table,id:typeof s=="string"?(0,rt.canonicalGuid)(s):""})}}}async function qae(e,t,n,r,i){var o;let a=g2(r,A0-da.length,A0),s="";for(let u=0;u<a.length;u+=1){let l=u===0,c=[...l?[aC(h=>h.pk)]:[],...a[u].map(y2)].join(","),d=`${hl(t)}${(0,Kn.odataQuery)([["$select",l?"customapiid,_sdkmessageid_value":"customapiid"],...c?[["$expand",c]]:[]])}`,f=e.apiUrl(d),p=await e.get(d,Dp);if(p.status===404)throw new Zt.VersionConflictError("customApi",t,null,null,"The API no longer exists on the server (another writer deleted it); nothing was deleted.");if(p.status<200||p.status>=300)throw hi(t,`a safety read answered ${p.status}`,p.body);let m=(o=p.body)!==null&&o!==void 0?o:{};if(l){let h=m._sdkmessageid_value;if(typeof h!="string"||!sC.test((0,rt.canonicalGuid)(h)))throw hi(t,"the API's message could not be read");s=(0,rt.canonicalGuid)(h);for(let g of da){let y;try{y=await h2(e,m,g,t,f)}catch(w){throw hi(t,`the API's ${g.nav} could not be read completely`,w)}let b=new Set(y.map(w=>(0,rt.canonicalGuid)(String(w[g.pk])))),E=g.kind==="requestParameter"?n.requestParameters:n.responseProperties;if(b.size!==E.size||[...E.keys()].some(w=>!b.has(w)))throw new Zt.VersionConflictError("customApi",t,null,null,`The API has ${g.nav} other than the ones last fetched (another writer added or removed one); the platform would delete them with it. Nothing was deleted; re-fetch it first.`)}}b2(m,a[u],i,h=>hi(t,h))}return s}async function Bae(e,t,n,r,i){var o;for(let a of r.length===0?[]:g2(r,A0,A0)){let s=`/sdkmessages(${n})${(0,Kn.odataQuery)([["$select","sdkmessageid"],["$expand",a.map(y2).join(",")]])}`,u=await e.get(s,Dp);if(u.status<200||u.status>=300)throw hi(t,`the read of the API's message answered ${u.status}`,u.body);b2((o=u.body)!==null&&o!==void 0?o:{},a,i,l=>hi(t,l))}}ut.customApiApi={async get(e,t){let n=(0,Kn.normalizeGuid)(t,"id"),r=`${hl(n)}${(0,Kn.odataQuery)([["$select",Iae],["$expand",aC(u=>u.select)]])}`,i=e.apiUrl(r),o=(0,en.ensureSuccess)(await e.get(r,Dp),i),a=o.body;if(!a||typeof a!="object"||Array.isArray(a))throw Yc(i,"the custom API row");let s={...a};for(let u of da)s[u.nav]=await h2(e,a,u,n,i);return Tae(s,n),{raw:s,etag:s2((0,en.readEtag)(o),s)}},async list(e){let t=`/${E0}${(0,Kn.odataQuery)([["$select","customapiid,uniquename,displayname,boundentitylogicalname"]])}`;return(await(0,ss.collectPages)(e,t,"listArtifacts('customApi')")).map(r=>{var i;return{type:"customApi",id:String((i=r.customapiid)!==null&&i!==void 0?i:""),name:String(r.displayname||r.uniquename||""),...typeof r.boundentitylogicalname=="string"&&r.boundentitylogicalname?{entityLogicalName:r.boundentitylogicalname}:{},isDirty:!1}})},async create(e,t,n){let r=t,i=`/${E0}${(0,Kn.odataQuery)([["$select","customapiid"],["$expand",aC(c=>c.pk)]])}`,o=e.apiUrl(i),a=(0,en.ensureSuccess)(await e.post(i,r.create,{headers:{Prefer:"return=representation"}}),o),s=(0,en.resolveCreatedId)(a,"customapiid","custom API",n),u=a.body,l=null;if(u&&typeof u=="object"){let c=f=>{var p,m;return new Set(((m=(p=r.create)===null||p===void 0?void 0:p[f.nav])!==null&&m!==void 0?m:[]).map(h=>(0,rt.canonicalGuid)(String(h[f.pk]))))};l=da.every(f=>{let p=u[f.nav],m=u[`${f.nav}@odata.nextLink`];if(!Array.isArray(p)||p.length>=rt.EXPANSION_CAP||(0,ss.moreRecordsClaim)(u,f.nav)!=="none"||m!==void 0)return!1;let h=p.map(y=>y?.[f.pk]),g=c(f);return p.every(y=>(0,en.isVersionToken)(y?.["@odata.etag"]))&&h.length===g.size&&h.every(y=>typeof y=="string"&&g.has((0,rt.canonicalGuid)(y)))&&new Set(h.map(rt.canonicalGuid)).size===h.length})?s2((0,en.readEtag)(a),u):null}return{id:s,etag:l,warnings:[...r.warnings,...l===null?[`customApi '${s}' was created, but the server's answer did not carry every row's version \u2014 fetch it before the next push.`]:[]]}},async update(e,t,n,r){let i=n,o=(0,Kn.normalizeGuid)(t,"id"),a=(0,rt.parseCustomApiToken)(r,i.held);a||Oae(o,r);let s=Pae(o,i,a);if(s.length>1&&!e.supportsAtomicBatch)throw new Zt.SdkError(ut.CUSTOM_API_NOT_ATOMIC_CODE,`Refusing to push customApi '${o}': it writes ${s.length} rows, which must commit together in one change set, and the injected HttpClient does not implement postRaw(). Nothing was sent.`);i.labelEdits.length>0&&await Dae(e,o,i.labelEdits);let u=await Rae(e,s),l={api:a.api,requestParameter:new Map(a.requestParameters),responseProperty:new Map(a.responseProperties)},c=!1;s.forEach((f,p)=>{if(f.op.method==="DELETE"){l[f.target].delete(f.id);return}let m=kae(f,u[p]);if(m===void 0){c=!0;return}f.target==="api"?l.api=m:l[f.target].set(f.id,m)});let d=c?null:(0,rt.composeCustomApiToken)(l.api,{requestParameters:[...l.requestParameter],responseProperties:[...l.responseProperty]});return{id:o,etag:d,warnings:[...i.warnings,...c?[`customApi '${o}' was saved, but the server returned no version for a row it wrote \u2014 fetch it before the next push.`]:[]]}},delete(e,t,n){return $ae(e,t,n)}};async function v2(e,t,n){let r=`/${E0}${(0,Kn.odataQuery)([["$select","customapiid,uniquename"],["$filter",`uniquename eq '${(0,Kn.odataLiteral)(t)}'`],...n!==void 0?[["$top",String(n)]]:[]])}`,i=e.apiUrl(r),o;if(n===void 0)o=await(0,ss.collectPages)(e,r,"resolveArtifact('customApi')");else{let a=(0,en.ensureSuccess)(await e.get(r),i).body;if(o=a?.value,Array.isArray(o)&&!(0,ss.boundedPageComplete)(a,o.length,n))throw Yc(i,"the list of custom APIs (the answer says more rows exist)")}if(!Array.isArray(o))throw Yc(i,"the list of custom APIs");return o.map(a=>({id:String(a.customapiid),name:String(a.uniquename)}))}ut.resolveCustomApis=v2;async function Vae(e,t){let n=await v2(e,t,2);if(n.length>1)throw new Zt.AmbiguousArtifactError("customApi",t,n.length);return n.length===1?n[0].id:null}ut.findCustomApi=Vae;var f2=25;async function Gae(e,t){let n=t.filter(s=>s.customApi==="requestParameter"||s.customApi==="responseProperty"),r=new Map,i=[],o=[];for(let s of t)if(s.customApi==="api")try{let u=(0,Kn.normalizeGuid)(s.objectId,"objectid");r.set(u,{...s,objectId:u})}catch(u){o.push({component:s,error:u})}else s.customApi===void 0&&i.push(s);if(n.length>0){let s=(await(0,m2.resolveCustomApiComponentTypes)(e)).api;for(let u of da){let l=n.filter(c=>c.customApi===u.kind);for(let c=0;c<l.length;c+=f2){let d=l.slice(c,c+f2),f=[];for(let g of d)try{f.push((0,Kn.normalizeGuid)(g.objectId,"objectid"))}catch(y){o.push({component:g,error:y})}if(f.length===0)continue;let p=`/${u.set}${(0,Kn.odataQuery)([["$select",`${u.pk},_customapiid_value`],["$filter",f.map(g=>`${u.pk} eq ${g}`).join(" or ")]])}`,m,h;try{let g=await(0,ss.collectPages)(e,p,"fetchSolution custom API parents");m=new Map(g.filter(y=>typeof y[u.pk]=="string"&&typeof y._customapiid_value=="string").map(y=>[(0,rt.canonicalGuid)(String(y[u.pk])),(0,rt.canonicalGuid)(String(y._customapiid_value))]))}catch(g){h=g}for(let g of d){let y=m?.get((0,rt.canonicalGuid)(g.objectId));y&&s!==void 0?r.has(y)||r.set(y,{objectId:y,componentType:s,customApi:"api"}):o.some(b=>b.component===g)||o.push({component:g,error:h??Yc(e.apiUrl(p),`the custom API ${u.kind} '${g.objectId}' or its API`)})}}}}let a=s=>s.objectId.toLowerCase().replace(/^\{|\}$/g,"");return{components:[...i,...r.values()].sort((s,u)=>s.componentType-u.componentType||(a(s)<a(u)?-1:a(s)>a(u)?1:0)),failed:o}}ut.foldCustomApiChildComponents=Gae});var lC=C(qe=>{"use strict";Object.defineProperty(qe,"__esModule",{value:!0});qe.sameContent=qe.isRuleToken=qe.ruleToken=qe.projectAggregate=qe.statePath=qe.aggregatePath=qe.statusOf=qe.MATCH_CODES=qe.DUPLICATE_RULE_READ_INCOMPLETE=qe.CONDITIONS_NAV=qe.DUPLICATE_RULE_CONDITION_SET=qe.DUPLICATE_RULE_SET=void 0;var jae=Y(),Wae=Ke(),zae=r0(),w2=ae();qe.DUPLICATE_RULE_SET="duplicaterules";qe.DUPLICATE_RULE_CONDITION_SET="duplicateruleconditions";qe.CONDITIONS_NAV="DuplicateRule_DuplicateRuleConditions";qe.DUPLICATE_RULE_READ_INCOMPLETE="DUPLICATE_RULE_READ_INCOMPLETE";var Hae="duplicateruleid,name,description,baseentityname,matchingentityname,iscasesensitive,excludeinactiverecords,statecode,statuscode",Kae="duplicateruleconditionid,baseattributename,matchingattributename,operatorcode,operatorparam,ignoreblankvalues,_regardingobjectid_value";qe.MATCH_CODES={exact:0,firstCharacters:1,lastCharacters:2,sameDate:3,sameDateAndTime:4,exactChoiceLabel:5,exactChoiceValue:6};var Jae=new Map(Object.entries(qe.MATCH_CODES).map(([e,t])=>[t,e]));function E2(e,t){if(e===0&&t===0)return"unpublished";if(e===0&&t===1)return"publishing";if(e===1&&t===2)return"published"}qe.statusOf=E2;var Yae=/^\{?[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}\}?$/,Pp=e=>e.toLowerCase().replace(/^\{|\}$/g,"");function Qae(e){return`/${qe.DUPLICATE_RULE_SET}(${e})${(0,w2.odataQuery)([["$select",Hae],["$expand",`${qe.CONDITIONS_NAV}($select=${Kae})`]])}`}qe.aggregatePath=Qae;function Xae(e){return`/${qe.DUPLICATE_RULE_SET}(${e})${(0,w2.odataQuery)([["$select","statecode,statuscode"]])}`}qe.statePath=Xae;function Cr(e,t){return new jae.SdkError(qe.DUPLICATE_RULE_READ_INCOMPLETE,`Duplicate rule '${e}' could not be read completely: ${t}. Nothing is concluded from an incomplete read \u2014 an absent or malformed condition set is never taken as "no conditions".`)}function Zae(e,t){let n=Pp(String(t));if(e===null||typeof e!="object"||Array.isArray(e))throw Cr(n,"the answer is not an object");let r=e,i=l=>{let c=r[l];if(typeof c!="string"||c==="")throw Cr(n,`'${l}' is not a non-empty string`);return c},o=l=>{if(typeof r[l]!="boolean")throw Cr(n,`'${l}' is not a boolean`);return r[l]};if(typeof r.duplicateruleid!="string"||Pp(r.duplicateruleid)!==n)throw Cr(n,"the answer is not this rule");if(r.description!==null&&typeof r.description!="string")throw Cr(n,"'description' is neither a string nor null (absent from the answer)");let a=E2(r.statecode,r.statuscode);if(!a)throw Cr(n,`the state ${String(r.statecode)}/${String(r.statuscode)} is not a known pair`);if(r[`${qe.CONDITIONS_NAV}@odata.nextLink`]!==void 0)throw Cr(n,"the condition collection is paged");if((0,Wae.moreRecordsClaim)(r,qe.CONDITIONS_NAV)!=="none")throw Cr(n,"the condition collection says more rows exist");let s=r[qe.CONDITIONS_NAV];if(!Array.isArray(s))throw Cr(n,"the condition collection is absent");let u=s.map((l,c)=>ese(n,l,c));return{id:n,name:i("name"),description:r.description,entityLogicalName:i("baseentityname"),matchingEntityLogicalName:i("matchingentityname"),caseSensitive:o("iscasesensitive"),excludeInactiveRecords:o("excludeinactiverecords"),status:a,conditions:u.sort((l,c)=>l.id<c.id?-1:1)}}qe.projectAggregate=Zae;function ese(e,t,n){let r=`condition ${n}`;if(t===null||typeof t!="object")throw Cr(e,`${r} is not an object`);let i=t;if(typeof i.duplicateruleconditionid!="string"||!Yae.test(i.duplicateruleconditionid))throw Cr(e,`${r} has no id`);for(let a of["baseattributename","matchingattributename"])if(typeof i[a]!="string"||i[a]==="")throw Cr(e,`${r}: '${a}' is not a non-empty string`);let o=typeof i.operatorcode=="number"?Jae.get(i.operatorcode):void 0;if(!o)throw Cr(e,`${r}: operator ${String(i.operatorcode)} is not one of 0-6`);if(i.operatorparam!==null&&typeof i.operatorparam!="number")throw Cr(e,`${r}: 'operatorparam' is neither a number nor null`);if(typeof i.ignoreblankvalues!="boolean")throw Cr(e,`${r}: 'ignoreblankvalues' is not a boolean`);if(typeof i._regardingobjectid_value!="string"||Pp(i._regardingobjectid_value)!==e)throw Cr(e,`${r} does not belong to this rule`);return{id:Pp(i.duplicateruleconditionid),column:i.baseattributename,matchingColumn:i.matchingattributename,match:o,characters:i.operatorparam,ignoreBlankValues:i.ignoreblankvalues}}function tse(e){var t,n,r,i,o;return[Pp((t=e.id)!==null&&t!==void 0?t:""),e.column,(n=e.matchingColumn)!==null&&n!==void 0?n:e.column,(r=qe.MATCH_CODES[e.match])!==null&&r!==void 0?r:e.match,(i=e.characters)!==null&&i!==void 0?i:null,(o=e.ignoreBlankValues)!==null&&o!==void 0?o:!1]}function uC(e,t){var n,r,i,o,a;return[e.name,(n=e.description)!==null&&n!==void 0?n:null,e.entityLogicalName,(r=e.matchingEntityLogicalName)!==null&&r!==void 0?r:e.entityLogicalName,(i=e.caseSensitive)!==null&&i!==void 0?i:!1,(o=e.excludeInactiveRecords)!==null&&o!==void 0?o:!1,t,((a=e.conditions)!==null&&a!==void 0?a:[]).map(tse).sort((s,u)=>s[0]<u[0]?-1:s[0]>u[0]?1:0)]}function nse(e){return`dr1:${(0,zae.fnv128Hex)("duplicateRule",JSON.stringify(uC(e,e.status)))}`}qe.ruleToken=nse;function rse(e){return typeof e=="string"&&/^dr1:[0-9a-f]{32}$/.test(e)}qe.isRuleToken=rse;function ise(e,t){return JSON.stringify(uC(e,null))===JSON.stringify(uC(t,null))}qe.sameContent=ise});var S0=C(gt=>{"use strict";Object.defineProperty(gt,"__esModule",{value:!0});gt.foldDuplicateRuleConditionComponents=gt.findDuplicateRule=gt.resolveDuplicateRules=gt.duplicateRuleApi=gt.PUBLISH_WAIT_MS=gt.PUBLISH_POLL_MS=gt.DUPLICATE_RULE_READ_INCOMPLETE=gt.DUPLICATE_RULE_IDENTITY_MISMATCH=gt.DUPLICATE_RULE_UPDATE_NOT_ATOMIC=gt.DUPLICATE_RULE_PUBLISH_FAILED=void 0;var ou=Ke(),cC=Zo(),Zc=g0(),Pe=lC();Object.defineProperty(gt,"DUPLICATE_RULE_READ_INCOMPLETE",{enumerable:!0,get:function(){return Pe.DUPLICATE_RULE_READ_INCOMPLETE}});var vt=Y(),gl=pe(),ur=ae();gt.DUPLICATE_RULE_PUBLISH_FAILED="DUPLICATE_RULE_PUBLISH_FAILED";gt.DUPLICATE_RULE_UPDATE_NOT_ATOMIC="DUPLICATE_RULE_UPDATE_NOT_ATOMIC";gt.DUPLICATE_RULE_IDENTITY_MISMATCH="DUPLICATE_RULE_IDENTITY_MISMATCH";var T2="/CompoundUpdateDuplicateDetectionRule";gt.PUBLISH_POLL_MS=2e3;gt.PUBLISH_WAIT_MS=6e4;var Rp=e=>e instanceof Error?e:new Error(String(e));function fC(e){var t;let n=(t=e?.error)===null||t===void 0?void 0:t.message;return typeof n=="string"?n:""}async function Qc(e,t){let n=(0,Pe.aggregatePath)(t);try{let r=await e.get(n);if(r.status===404)return{kind:"gone"};(0,gl.ensureSuccess)(r,e.apiUrl(n));let i=await ose(e,t,e.apiUrl(n),r);return{kind:"read",rule:(0,Pe.projectAggregate)(i,t),raw:i}}catch(r){return{kind:"unusable",error:Rp(r)}}}async function ose(e,t,n,r){let i=r.body;if(i===null||typeof i!="object"||Array.isArray(i))return i;let o={...i},a=`${Pe.CONDITIONS_NAV}@odata.nextLink`,s=`${Pe.CONDITIONS_NAV}${ou.MORE_RECORDS_ANNOTATION}`,u=o[a];if((0,ou.pageEnd)(o,Pe.CONDITIONS_NAV).kind==="end")return delete o[a],o;let l;try{l=await(0,ou.continuePages)(e,{...r,body:{value:o[Pe.CONDITIONS_NAV],"@odata.nextLink":u,[ou.MORE_RECORDS_ANNOTATION]:o[s]}},n,`the conditions of duplicate rule '${t}'`)}catch(c){throw c instanceof vt.InvalidArgumentError||c instanceof vt.ConnectionError&&c.statusCode>=200&&c.statusCode<300?(0,vt.attachCause)(new vt.SdkError(Pe.DUPLICATE_RULE_READ_INCOMPLETE,`The conditions of duplicate rule '${t}' could not be read completely (${Rp(c).message}); a partial set is never taken as the whole one.`),c):c}return delete o[a],delete o[s],o[Pe.CONDITIONS_NAV]=l,o}function ed(e,t,n,r){return(0,vt.attachCause)(new vt.ConnectionError(e,n,`the outcome of the write of duplicateRule '${t}' is unknown \u2014 it may or may not have been applied, and it is not re-sent. Re-fetch the rule to see what the server holds.`),r)}var pC=e=>gl.AMBIGUOUS_WRITE_STATUSES.has(e)||e>=500;async function ase(e,t,n){let r=e.apiUrl(n.path),i=n.etag?{headers:{"If-Match":n.etag}}:void 0,o;try{o=n.method==="POST"?await e.post(n.path,n.body,i):n.method==="PATCH"?await e.patch(n.path,n.body,i):await e.delete(n.path,i)}catch(a){throw(0,Zc.isTransportFailure)(a)?ed(r,t,0,a):a}if(pC(o.status))throw ed(r,t,o.status,o.body);(0,gl.ensureSuccess)(o,r)}async function A2(e,t,n){var r;if(n.length===1){await ase(e,t,n[0]);return}let{body:i,batchId:o,contentIds:a}=(0,cC.renderChangeSet)(e,n),s=e.apiUrl("/$batch"),u;try{u=await e.postBatch(i,o)}catch(d){throw(0,Zc.isTransportFailure)(d)?ed(s,t,0,d):d}let l=(0,cC.parseChangeSetParts)(u.body,a),c=l?.find(d=>d.status<200||d.status>=300);if(c){let d=(0,cC.partResponse)(c),f=(r=(0,Zc.platformErrorCode)(d.body))!==null&&r!==void 0?r:"";throw new vt.ConnectionError(s,d.status,`the write of duplicateRule '${t}' was refused and changed nothing (the change set rolled back): HTTP `+`${d.status} ${f} ${fC(d.body)}`.trim(),d.body)}if(u.status<200||u.status>=300||!l||l.length!==n.length)throw ed(s,t,u.status,u.body)}function C2(e,t,n){var r,i,o,a;if(Xc((r=t?.desired)===null||r===void 0?void 0:r.id)!==e)throw iu(e,`the artifact names rule '${String((i=t?.desired)===null||i===void 0?void 0:i.id)}'`,!1);let u=`/${Pe.DUPLICATE_RULE_SET}(${e})`;for(let l of t.ops){let c=(o=l.body)!==null&&o!==void 0?o:{};if(l.path===`/${Pe.DUPLICATE_RULE_SET}`){if(!n||l.method!=="POST"||Xc(c.duplicateruleid)!==e)throw iu(e,`a create addresses rule '${String(c.duplicateruleid)}'`,!1)}else if(l.path.startsWith(`/${Pe.DUPLICATE_RULE_SET}(`)){if(l.path.toLowerCase()!==u)throw iu(e,`an operation addresses '${l.path}'`,!1)}else if(l.path===T2){let d=c.Entity;if(Xc(d?.duplicateruleid)!==e)throw iu(e,`the compound update names rule '${String(d?.duplicateruleid)}'`,!1)}else if(l.path===`/${Pe.DUPLICATE_RULE_CONDITION_SET}`&&l.method==="POST"){let d=String((a=c["[email protected]"])!==null&&a!==void 0?a:"");if(d.toLowerCase()!==u)throw iu(e,`a new condition is bound to '${d}'`,!1)}else if(!l.path.startsWith(`/${Pe.DUPLICATE_RULE_CONDITION_SET}(`))throw iu(e,`an operation addresses '${l.path}', which is not part of a duplicate rule`,!1)}}function sse(e,t,n){var r,i;let o=new Set(n.conditions.map(u=>u.id)),a=new Set(t.filter(u=>u.method==="POST"&&u.path===`/${Pe.DUPLICATE_RULE_CONDITION_SET}`).map(u=>{var l;return Xc((l=u.body)===null||l===void 0?void 0:l.duplicateruleconditionid)})),s=`/${Pe.DUPLICATE_RULE_CONDITION_SET}(`;for(let u of t){if(u.path.startsWith(s)){let l=Xc(u.path.slice(s.length,-1));if(!l||!o.has(l))throw iu(e,`an operation addresses condition '${u.path}', which the guard did not read on this rule`,!0)}if(u.path===T2){let l=(i=(r=u.body)===null||r===void 0?void 0:r.ChildEntities)!==null&&i!==void 0?i:[];for(let c of l){let d=Xc(c?.duplicateruleconditionid);if(!d||!o.has(d)&&!a.has(d))throw iu(e,`the compound update lists condition '${String(c?.duplicateruleconditionid)}', which is neither on this rule nor created by this push`,!0)}}}}function Xc(e){try{return typeof e=="string"?(0,ur.normalizeGuid)(e,"id"):void 0}catch{return}}function iu(e,t,n){return new vt.SdkError(gt.DUPLICATE_RULE_IDENTITY_MISMATCH,`Refusing to push duplicateRule '${e}': ${t}. A push writes only the rule it guarded, and a rule's id is fixed \u2014 to copy a rule, create a new one. Nothing was ${n?"written":"sent"}.`)}function S2(e,t,n){if(n.length>1&&!e.supportsAtomicBatch)throw new vt.SdkError(gt.DUPLICATE_RULE_UPDATE_NOT_ATOMIC,`Refusing to push duplicateRule '${t}': this change needs ${n.length} requests in one atomic change set, and the injected HttpClient has no postRaw() to send one. Nothing was sent.`)}var use={"0x80048419":"at most 5 rules can be published per table \u2014 unpublish one","0x80048410":"duplicate detection is off for this table (updateTable(table, { duplicateDetectionEnabled: true })) or for the organization","0x80048414":"a published rule needs a condition","0x80048434":"a publish is already running \u2014 re-fetch"};async function lse(e){await new Promise(t=>setTimeout(t,e))}async function cse(e,t,n,r){let i=n+gt.PUBLISH_WAIT_MS;for(;;){let o=i-Date.now();if(o<=0)return;await lse(Math.min(gt.PUBLISH_POLL_MS,o));let a;try{let s=await e.get((0,Pe.statePath)(t));if(s.status<200||s.status>=300)return;let u=s.body;a=(0,Pe.statusOf)(u?.statecode,u?.statuscode)}catch{return}if(a==="publishing"){r.sawPublishing=!0;continue}if(a==="published"||a===void 0||a==="unpublished"&&r.sawPublishing)return}}function dse(e,t,n,r){var i;if(!n){e.request="unknown",e.transportError=Rp(r);return}if(n.status>=200&&n.status<300){e.request="accepted";let a=(i=n.body)===null||i===void 0?void 0:i.asyncoperationid;typeof a=="string"&&(e.jobId=a);return}let o=new vt.ConnectionError(t,n.status,fC(n.body),n.body);if(pC(n.status)){e.request="unknown",e.transportError=o;return}e.request="refused",e.refusal={status:n.status,code:(0,Zc.platformErrorCode)(n.body),message:fC(n.body),error:o}}async function fse(e,t,n){let r=e.withoutSolution(),i=n.action==="publish"?`/${Pe.DUPLICATE_RULE_SET}(${t})/Microsoft.Dynamics.CRM.PublishDuplicateRule`:"/UnpublishDuplicateRule",o=n.action==="publish"?{}:{DuplicateRuleId:t},a=Date.now(),s,u;try{s=await r.post(i,o)}catch(l){if(!(0,Zc.isTransportFailure)(l))throw l;u=l}dse(n,r.apiUrl(i),s,u),n.action==="publish"&&n.request!=="refused"&&await cse(e,t,a,n)}async function O2(e,t,n){var r;if(n.request==="refused"&&n.refusal){let a=n.refusal.code?use[n.refusal.code]:void 0;return(0,vt.attachCause)(new vt.SdkError(gt.DUPLICATE_RULE_PUBLISH_FAILED,`Publishing duplicate rule '${t}' was refused (HTTP ${n.refusal.status} ${(r=n.refusal.code)!==null&&r!==void 0?r:""})${a?`: ${a}`:`: ${n.refusal.message}`}. The save is unaffected; push again once it is resolved.`),n.refusal.error)}let i="";if(n.jobId)try{let a=`/asyncoperations(${n.jobId})${(0,ur.odataQuery)([["$select","message,friendlymessage"]])}`,s=await e.get(a),u=s.body,l=u?.friendlymessage||u?.message;i=s.status===200&&typeof l=="string"&&l?` The publish job says: ${l}`:""}catch{i=""}let o=new vt.SdkError(gt.DUPLICATE_RULE_PUBLISH_FAILED,`Duplicate rule '${t}': the rule reads unpublished after the publish request${n.request==="unknown"?" (whose answer was lost)":""}.${i} The save is unaffected; push again to retry the publish.`);return n.transportError?(0,vt.attachCause)(o,n.transportError):o}async function pse(e,t,n,r,i){var o,a,s,u;let l=r.request==="accepted"||r.request==="unknown",c,d;if(n==="published"&&r.action==="publish"&&l)c={kind:"submitted"},d=`Duplicate rule '${t}' was saved and is still publishing \u2014 re-fetch to see the result.${i}`;else if(n==="published"&&r.action==="publish"&&r.request==="refused")c={kind:"failed",error:await O2(e,t,r)},d=`Duplicate rule '${t}' was saved, but its publish was refused and the rule reads publishing \u2014 another writer is publishing it; re-fetch to see the result.${i}`;else if(n==="published")c={kind:"failed",error:new vt.VersionConflictError("duplicateRule",t,null,null,"Saved, but another writer is publishing the rule; this push did not publish it.")},d=`Duplicate rule '${t}' was saved; the rule reads publishing \u2014 another writer is publishing it, this push did not; re-fetch to see the result.${i}`;else{c={kind:"notRequested"};let f=r.action!=="unpublish"||r.request==="none"?"":r.request==="refused"?` its unpublish was refused (HTTP ${(a=(o=r.refusal)===null||o===void 0?void 0:o.status)!==null&&a!==void 0?a:""} ${(u=(s=r.refusal)===null||s===void 0?void 0:s.code)!==null&&u!==void 0?u:""}),`:r.request==="unknown"?" its unpublish answer was lost,":" its unpublish was accepted,";d=`Duplicate rule '${t}' was saved;${f} and the rule reads publishing \u2014 another writer is publishing it, so it is not unpublished; re-fetch.${i}`}return{id:t,etag:null,publish:c,warnings:[d]}}async function mse(e,t,n,r,i){var o;let a=n.desired.status,u=n.heldStatus==="published"&&n.statusAfterContent==="unpublished"?" This edit took the published rule offline.":"";if(r.kind==="read"&&(0,Pe.sameContent)(r.rule,n.desired)){let d=r.rule.status;if(d===a)return{id:t,etag:(0,Pe.ruleToken)(r.rule),serverState:d,publish:a==="published"?{kind:"verified"}:{kind:"notRequested"}};if(d==="publishing")return pse(e,t,a,i,u);if(a==="published")return{id:t,etag:(0,Pe.ruleToken)(r.rule),serverState:d,publish:{kind:"failed",error:await O2(e,t,i)},warnings:[`Duplicate rule '${t}' was saved; the rule reads unpublished \u2014 it is NOT checking records.${u}`]};let f=i.request==="refused"&&i.refusal?`the platform refused it: HTTP ${i.refusal.status} ${(o=i.refusal.code)!==null&&o!==void 0?o:""} ${i.refusal.message}`.trim():"its outcome is unknown";return{id:t,etag:(0,Pe.ruleToken)(r.rule),serverState:d,publish:{kind:"notRequested"},warnings:[`Duplicate rule '${t}' was saved but could not be unpublished (${f}) \u2014 the rule is still checking records.`]}}let l=r.kind==="gone"?"the rule is gone \u2014 another writer deleted it after the save":r.kind==="unusable"?`the rule could not be read (${r.error.message})`:"the rule changed on the server after the save \u2014 another writer changed it",c={kind:"notRequested"};return a==="published"&&(i.g2Stopped?c={kind:"failed",error:r.kind==="unusable"?r.error instanceof vt.SdkError&&r.error.code===Pe.DUPLICATE_RULE_READ_INCOMPLETE?r.error:(0,vt.attachCause)(new vt.SdkError(Pe.DUPLICATE_RULE_READ_INCOMPLETE,`Saved, but ${l}; this push did not publish it.`),r.error):new vt.VersionConflictError("duplicateRule",t,null,null,`Saved, but ${l}; this push did not publish it.`)}:c={kind:"unverifiable",reason:l}),{id:t,etag:null,publish:c,warnings:[`Duplicate rule '${t}' was saved, but ${l}; whether it is published is unknown \u2014 re-fetch before the next push (it refuses until then).${u}`]}}async function N2(e,t,n){let r=n.desired.status,i=n.statusAfterContent,o={g2Stopped:!1,request:"none",sawPublishing:!1};r==="published"&&i==="unpublished"?o.action="publish":r==="unpublished"&&i==="published"&&(o.action="unpublish");try{let a;if(!o.action)a=await Qc(e,t);else{let s=await Qc(e,t);s.kind!=="read"||(0,Pe.ruleToken)(s.rule)!==(0,Pe.ruleToken)({...n.desired,status:i})?(o.g2Stopped=!0,a=s):(await fse(e,t,o),a=await Qc(e,t))}return await mse(e,t,n,a,o)}catch(a){return{id:t,etag:null,publish:r==="published"?{kind:"unverifiable",reason:`the publish step failed: ${Rp(a).message}`}:{kind:"notRequested"},warnings:[`Duplicate rule '${t}' was saved, but the step after the save failed (${Rp(a).message}); its state is unknown \u2014 re-fetch before the next push.`]}}}function D2(e,t,n,r){return new vt.VersionConflictError("duplicateRule",e,t,n.kind==="read"?(0,Pe.ruleToken)(n.rule):null,n.kind==="gone"?`Another writer deleted it since it was fetched; ${r}.`:`Another writer changed it since it was fetched; ${r}.`)}async function hse(e,t,n){var r;let i=(0,ur.normalizeGuid)(t,"id"),o=(r=n?.token)!==null&&r!==void 0?r:null;if(!(0,Pe.isRuleToken)(o))throw new vt.SdkError(gl.DELETE_NO_ETAG_CODE,`Refusing to delete duplicateRule '${i}': no usable version is held for it, so the delete could not be guarded and could remove what another writer changed. Fetch it first (fetchArtifact).`);let a=await Qc(e,i);if(a.kind==="unusable")throw a.error;if(a.kind==="gone"||(0,Pe.ruleToken)(a.rule)!==o)throw D2(i,o,a,"nothing was deleted");let s=`/${Pe.DUPLICATE_RULE_SET}(${i})`,u=e.apiUrl(s),l;try{l=await e.delete(s)}catch(c){throw(0,Zc.isTransportFailure)(c)?ed(u,i,0,c):c}if(l.status===404)throw new vt.VersionConflictError("duplicateRule",i,o,null,"It was deleted by another writer in between.");if(pC(l.status))throw ed(u,i,l.status,l.body);(0,gl.ensureSuccess)(l,u)}gt.duplicateRuleApi={async get(e,t){let n=(0,ur.normalizeGuid)(t,"id"),r=await Qc(e,n);if(r.kind==="gone"){let i=(0,Pe.aggregatePath)(n);throw new vt.ConnectionError(e.apiUrl(i),404,`duplicate rule '${n}' does not exist`)}if(r.kind==="unusable")throw r.error;return{raw:r.raw,etag:(0,Pe.ruleToken)(r.rule)}},async list(e,t){let n=`/${Pe.DUPLICATE_RULE_SET}${(0,ur.odataQuery)([["$select","duplicateruleid,name,baseentityname"],["$filter",t?.entityLogicalName?`baseentityname eq '${(0,ur.odataLiteral)(t.entityLogicalName)}'`:void 0]])}`;return(await(0,ou.collectPages)(e,n,"fetchArtifactList('duplicateRule')")).map(i=>{var o,a,s;return{type:"duplicateRule",id:(0,ur.normalizeGuid)(String((o=i.duplicateruleid)!==null&&o!==void 0?o:""),"duplicateruleid"),name:String((a=i.name)!==null&&a!==void 0?a:""),entityLogicalName:String((s=i.baseentityname)!==null&&s!==void 0?s:""),isDirty:!1}})},async create(e,t,n){let r=t,i=(0,ur.normalizeGuid)(n??r.desired.id,"id");return C2(i,r,!0),S2(e,i,r.ops),await A2(e,i,r.ops),N2(e,i,r)},async update(e,t,n,r){let i=(0,ur.normalizeGuid)(t,"id"),o=n;if(!(0,Pe.isRuleToken)(r))throw new vt.SdkError(gl.UPDATE_NO_ETAG_CODE,`Refusing to push duplicateRule '${i}': ${r?`the version held for it ('${r}') is not a duplicate-rule version`:"no version is held for it"}, so the write could not be guarded. Re-fetch the rule and re-apply the change.`);C2(i,o,!1),S2(e,i,o.ops);let a=await Qc(e,i);if(a.kind==="unusable")throw a.error;if(a.kind==="gone"||(0,Pe.ruleToken)(a.rule)!==r)throw D2(i,r,a,"nothing was written");return sse(i,o.ops,a.rule),await A2(e,i,o.ops),N2(e,i,o)},delete(e,t,n){return hse(e,t,n)}};async function P2(e,t,n,r){let i=`name eq '${(0,ur.odataLiteral)(t)}'${n?` and baseentityname eq '${(0,ur.odataLiteral)(n)}'`:""}`,o=`/${Pe.DUPLICATE_RULE_SET}${(0,ur.odataQuery)([["$select","duplicateruleid,name"],["$filter",i],...r!==void 0?[["$top",String(r)]]:[]])}`,a=e.apiUrl(o),s;if(r===void 0)s=await(0,ou.collectPages)(e,o,"resolveArtifact('duplicateRule')");else{let u=(0,gl.ensureSuccess)(await e.get(o),a).body;if(s=u?.value,Array.isArray(s)&&!(0,ou.boundedPageComplete)(u,s.length,r))throw new vt.ConnectionError(a,200,"the list of duplicate rules is incomplete (the answer says more rows exist), so it proves neither absence nor a single match")}if(!Array.isArray(s))throw new vt.ConnectionError(a,200,"the response could not be read as a list of duplicate rules");return s.map(u=>{var l,c;return{id:(0,ur.normalizeGuid)(String((l=u.duplicateruleid)!==null&&l!==void 0?l:""),"duplicateruleid"),name:String((c=u.name)!==null&&c!==void 0?c:"")}})}gt.resolveDuplicateRules=P2;async function gse(e,t,n){let r=await P2(e,t,n,2);if(r.length>1)throw new vt.AmbiguousArtifactError("duplicateRule",t,r.length);return r.length===1?r[0].id:null}gt.findDuplicateRule=gse;var dC=4414,_2=4416,I2=50;async function yse(e,t){let n=[],r=[],i=t.filter(d=>d.componentType===_2);if(i.length===0&&!t.some(d=>d.componentType===dC))return{components:t,failed:n,orphaned:r};let o=new Set,a=[];for(let d of t)if(d.componentType===dC)try{o.add((0,ur.normalizeGuid)(d.objectId,"objectid"))}catch(f){n.push({component:d,error:f})}else d.componentType!==_2&&a.push(d);let s=new Map;for(let d of i)try{s.set((0,ur.normalizeGuid)(d.objectId,"objectid"),d)}catch(f){n.push({component:d,error:f})}let u=[...s.keys()];for(let d=0;d<u.length;d+=I2){let f=u.slice(d,d+I2),p=`/${Pe.DUPLICATE_RULE_CONDITION_SET}${(0,ur.odataQuery)([["$select","duplicateruleconditionid,_regardingobjectid_value"],["$filter",f.map(m=>`duplicateruleconditionid eq ${m}`).join(" or ")]])}`;try{let m=await(0,ou.collectPages)(e,p,"fetchSolution (duplicate rule conditions)"),h=new Map;for(let g of m)typeof g.duplicateruleconditionid=="string"&&h.set(g.duplicateruleconditionid.toLowerCase(),g._regardingobjectid_value);for(let g of f){let y=s.get(g),b=h.get(g);typeof b=="string"?o.add((0,ur.normalizeGuid)(b,"_regardingobjectid_value")):r.push({component:y,detail:"A duplicate-rule condition that no longer exists (or has no rule), so there is no rule to fetch for it."})}}catch(m){for(let h of f)n.push({component:s.get(h),error:m})}}let l=[...o].map(d=>({objectId:d,componentType:dC})),c=d=>d.objectId.toLowerCase().replace(/^\{|\}$/g,"");return{components:[...a,...l].sort((d,f)=>d.componentType-f.componentType||(c(d)<c(f)?-1:c(d)>c(f)?1:0)),failed:n,orphaned:r}}gt.foldDuplicateRuleConditionComponents=yse});var gC=C(He=>{"use strict";Object.defineProperty(He,"__esModule",{value:!0});He.compileGenPage=He.legacyEnumsNeeded=He.createGenPageTypeScriptLoader=He.acceptGenPageTypeScript=He.isLoadableGenPageOutput=He.runtimeTypesImportSpans=He.resolveGenPageIteration=He.GENPAGE_ITERATION_DEFAULT=He.GENPAGE_RUNTIME_TYPES_END=He.GENPAGE_RUNTIME_TYPES_BEGIN=He.GENPAGE_TYPESCRIPT_VERSION=void 0;var au=Y();He.GENPAGE_TYPESCRIPT_VERSION="5.8.3";He.GENPAGE_RUNTIME_TYPES_BEGIN="// --- BEGIN GENERATED RUNTIME TYPES ---";He.GENPAGE_RUNTIME_TYPES_END="// --- END GENERATED RUNTIME TYPES ---";He.GENPAGE_ITERATION_DEFAULT="iterator";function bse(e){if(e===void 0)return He.GENPAGE_ITERATION_DEFAULT;if(e==="legacy"||e==="iterator")return e;throw new au.InvalidArgumentError(`genPageIteration must be 'legacy' or 'iterator', or omitted (got ${typeof e=="string"?`'${e}'`:String(e)}).`)}He.resolveGenPageIteration=bse;var _o="./RuntimeTypes",vse="'\"`",R2=/\s/;function wse(e){return e===10||e===13||e===8232||e===8233}function Ese(e,t){let n=[];e.lastIndex=0;for(let r=e.exec(t);r!==null;r=e.exec(t))n.push(r.index);return n}function M2(e){let t=[],n=_o.length;for(let u=e.indexOf(_o);u!==-1;u=e.indexOf(_o,u+1)){let l=u-1;l>=0&&vse.includes(e[l])&&e[l+1+n]===e[l]&&t.push(l)}let r=[];if(t.length===0)return r;let i=-1,o=u=>{if(i<u)for(i=u;i<e.length&&e[i]!=="'"&&e[i]!=='"';)i+=1;return i},a=-1,s=u=>{for(;a+1<t.length&&t[a+1]<=u;)a+=1;return a>=0?t[a]:-1/0};for(let u=e.indexOf("import");u!==-1;){let l=u+1;if(u+6<e.length&&R2.test(e[u+6])){let c=s(o(u+6));if(c>=u+8){let d=c+2+n;for(e[d]===";"&&(d+=1);d<e.length&&R2.test(e[d]);)d+=1;r.push({start:u,end:d}),l=d}}u=e.indexOf("import",l)}return r}He.runtimeTypesImportSpans=M2;var Ase=/\b(?:import\s*['"]|export\s)/;function Cse(e){let t=Ese(/from\s+['"]/g,e);if(t.length===0)return!1;let n=/\bimport\s/g,r=-1,i=0;for(let o=n.exec(e);o!==null;o=n.exec(e)){let a=o.index+7;if(a>r)for(r=a;r<e.length&&!wse(e.charCodeAt(r));)r+=1;for(;i<t.length&&t[i]<a+1;)i+=1;if(i<t.length&&t[i]<r)return!0}return!1}function Sse(e){return e!==void 0&&e!==""&&(Ase.test(e)||Cse(e))}He.isLoadableGenPageOutput=Sse;var k2=["transpileModule","createSourceFile","createProgram","getParseTreeNode","flattenDiagnosticMessageText","forEachChild","getModifiers","canHaveModifiers","isImportDeclaration","isExportDeclaration","isExportAssignment","isStringLiteral"];function x2(e){var t;let n=s=>s!==null&&(typeof s=="object"||typeof s=="function")?s:void 0,r=n(e);r&&typeof r.transpileModule!="function"&&(r=(t=n(r.default))!==null&&t!==void 0?t:r);let i=r?k2.filter(s=>typeof r?.[s]!="function"):[...k2];if(!r||i.length>0)throw new au.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@${He.GENPAGE_TYPESCRIPT_VERSION}'s lib/typescript.js.`);let o=typeof r.version=="string"?r.version:"",a=He.GENPAGE_TYPESCRIPT_VERSION.split(".").slice(0,2).join(".");if(o.split(".").slice(0,2).join(".")!==a)throw new au.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 (${He.GENPAGE_TYPESCRIPT_VERSION}). Another version can emit different JavaScript for the same page. Supply typescript@${He.GENPAGE_TYPESCRIPT_VERSION}.`);return r}He.acceptGenPageTypeScript=x2;function Nse(e){let t;return()=>{if(!t){if(e===void 0)return Promise.reject(new au.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@${He.GENPAGE_TYPESCRIPT_VERSION}'s lib/typescript.js. Nothing was written.`));t=Promise.resolve().then(()=>typeof e=="function"?e():e).then(x2).catch(n=>{throw t=void 0,n instanceof au.SdkError?n:new au.SdkError("GENPAGE_COMPILER_UNAVAILABLE",`The TypeScript compiler could not be loaded, so a generative page cannot be compiled (${n instanceof Error?n.message:String(n)}). Nothing was written.`)})}return t}}He.createGenPageTypeScriptLoader=Nse;var F2=e=>`${e.kind}:${e.pos}:${e.end}`;function _se(e,t){return()=>n=>{let r=i=>{let o=e.getParseTreeNode(i);o&&t.add(F2(o)),e.forEachChild(i,r)};return r(n),n}}function hC(e,t){return{target:e.ScriptTarget.ES5,module:e.ModuleKind.ES2020,jsx:e.JsxEmit.React,...t==="iterator"?{downlevelIteration:!0}:{}}}var Ise="The generative page could not be compiled because compilation exceeded this JavaScript engine's call-stack limit. Reduce nested JSX or expression complexity and retry. The page was not written.";function U2(e){if(typeof e!="object"||e===null)return!1;let{name:t,message:n}=e;return t==="RangeError"&&n==="Maximum call stack size exceeded"}var Tse=2301;function $2(e,t,n,r){var i;let o=e.transpileModule(t,{compilerOptions:hC(e,n),reportDiagnostics:!0,...r?{transformers:{after:[_se(e,r)]}}:{}}),a=((i=o.diagnostics)!==null&&i!==void 0?i:[]).filter(s=>s.category===e.DiagnosticCategory.Error).map(s=>{let u=s.file&&typeof s.start=="number"?s.file.getLineAndCharacterOfPosition(s.start):{line:0,character:0};return{line:u.line+1,column:u.character+1,rule:"genpage-source-syntax",code:s.code,message:e.flattenDiagnosticMessageText(s.messageText,`+`)}});return{code:o.outputText,diagnostics:a}}var L2=e=>e.startsWith(".")||e.startsWith("/"),N0={line:1,column:1};function mC(e,t){let n=o=>{let a=t.getLineAndCharacterOfPosition(o.getStart(t));return{line:a.line+1,column:a.character+1}},r=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)&&r(a)===o);return{statement(o,a){let s=t.statements.find(u=>r(u)===o&&(a==="import"?e.isImportDeclaration(u):e.isExportDeclaration(u)));return s?n(s):N0},element(o,a){var s;for(let u of i(o)){let l=(s=u.importClause)===null||s===void 0?void 0:s.namedBindings,c=l&&e.isNamedImports(l)?l.elements.find(d=>d.name.text===a):void 0;if(c)return n(c)}return this.statement(o,"import")},binding(o){var a,s;for(let u of t.statements)if(e.isImportDeclaration(u)&&u.importClause){let l=u.importClause,c=l.namedBindings,d=((a=l.name)===null||a===void 0?void 0:a.text)===o?l.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 n(d)}else{if((e.isFunctionDeclaration(u)||e.isClassDeclaration(u))&&((s=u.name)===null||s===void 0?void 0:s.text)===o)return n(u.name);if(e.isVariableStatement(u)){let l=u.declarationList.declarations.find(c=>e.isIdentifier(c.name)&&c.name.text===o);if(l)return n(l.name)}}return N0}}}function Ose(e,t,n,r){var i,o;let a=[],s=mC(e,n),u=(m,h,g)=>{a.push({...m,rule:h,code:0,message:g})},l=(m,h)=>{var g;return(e.canHaveModifiers(m)?(g=e.getModifiers(m))!==null&&g!==void 0?g:[]:[]).some(y=>y.kind===h)},c=(m,h)=>u(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)){l(m,e.SyntaxKind.ExportKeyword)&&l(m,e.SyntaxKind.DefaultKeyword)&&(f=!0),m.name&&p.add(m.name.text);continue}if(e.isExportDeclaration(m)){let b=m.exportClause;b&&e.isNamedExports(b)&&b.elements.some(w=>w.name.text==="default")&&(f=!0);let E=m.moduleSpecifier&&e.isStringLiteral(m.moduleSpecifier)?m.moduleSpecifier.text:void 0;E===_o?u(s.statement(E,"export"),d,"a page cannot re-export from './RuntimeTypes': that module does not exist at runtime"):E!==void 0&&L2(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!==_o){L2(h)&&c(s.statement(h,"import"),h),g?.name&&p.add(g.name.text);let b=g?.namedBindings;b&&e.isNamespaceImport(b)?p.add(b.name.text):b&&e.isNamedImports(b)&&b.elements.forEach(E=>p.add(E.name.text));continue}if(!g){u(s.statement(h,"import"),d,"a side-effect import of './RuntimeTypes' cannot resolve at runtime; import the names it declares");continue}g.name&&u(s.binding(g.name.text),d,"'./RuntimeTypes' has no default export at runtime; import its names");let y=g.namedBindings;if(y&&e.isNamespaceImport(y))u(s.binding(y.name.text),d,"a namespace import of './RuntimeTypes' is undefined at runtime \u2014 its enums are inlined under their own names; import the names instead");else if(y&&e.isNamedImports(y))for(let b of y.elements){let E=b.name.text,w=(o=(i=b.propertyName)===null||i===void 0?void 0:i.text)!==null&&o!==void 0?o:E,_=s.element(h,E);w!==E?u(_,d,`'${w} as ${E}' would be undefined at runtime: the enum is inlined as '${w}', so import it under its own name`):r?.text?r.enums.has(E)||u(_,"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'.`):u(_,"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||u(N0,"genpage-no-default-export","the page has no default export \u2014 the runtime renders the module's default export as the page component"),r?.text)for(let m of p)r.enums.has(m)&&u(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 q2(e,t,n){let r,i=()=>{if(!r){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={...n,noLib:!0,noResolve:!0,allowJs:!0,types:[],alwaysStrict:!0,moduleDetection:e.ModuleDetectionKind.Force};r=e.createProgram({rootNames:[t.fileName],options:h,host:m})}return r},o,a=()=>(o||(o=i().getTypeChecker()),o),s,u=()=>{if(!s){s=new Map;try{for(let m of i().getSemanticDiagnostics(t))m.code===Tse&&typeof m.start=="number"&&s.set(m.start,e.flattenDiagnosticMessageText(m.messageText," "))}catch(m){if(U2(m))throw m}}return s},l=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=l(m);return h!==void 0&&e.isImportDeclaration(h)&&e.isStringLiteral(h.moduleSpecifier)&&h.moduleSpecifier.text===_o},d=m=>{var h;for(let g=m;g;g=g.parent)if(e.canHaveModifiers(g)&&((h=e.getModifiers(g))!==null&&h!==void 0?h:[]).some(y=>y.kind===e.SyntaxKind.DeclareKeyword))return!0;return!1},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=>u().get(m.getStart(t))}}function Dse(e,t,n,r,i){let o=[],a=n?.enums;if(!a||a.size===0)return o;let s=(c,d,f)=>{let p=t.getLineAndCharacterOfPosition(c.getStart(t));o.push({line:p.line+1,column:p.character+1,rule:d,code:0,message:f})},u=q2(e,t,hC(e,i)),l=c=>{let d,f;if(e.isPropertyAccessExpression(c)&&e.isIdentifier(c.expression))d=c.expression,f=c.name.text;else if(e.isElementAccessExpression(c)&&e.isIdentifier(c.expression)){let m=c.argumentExpression;e.isStringLiteral(m)||e.isNoSubstitutionTemplateLiteral(m)?(d=c.expression,f=m.text):e.isNumericLiteral(m)&&(d=c.expression,f=String(Number(m.text)))}let p=d&&a.has(d.text)&&r.has(F2(c))&&!u.pageOwns(d)?a.get(d.text):void 0;if(d&&p&&f!==void 0){let m=e.isPropertyAccessExpression(c)?`${p.name}.${f}`:`${p.name}[${JSON.stringify(f)}]`,h=Object.prototype.hasOwnProperty.call(p.runtime,f)?p.runtime[f]:void 0,g=p.labels.get(f),y;h===void 0?y={rule:"genpage-enum-member-unknown",message:`${m} is undefined at runtime: '${p.name}' has no member '${f}' in this environment's metadata \u2014 members are the column's choice labels, so a renamed or differently localized label no longer matches. Known: ${[...p.labels.keys()].map(E=>`'${E}'`).join(", ")}`}:g&&typeof h!="number"?y={rule:"genpage-enum-member-clobbered",message:`${m} is the string '${String(h)}' at runtime, not a choice value: the label '${f}' looks like a number, and another option's reverse mapping overwrites it. Use the choice's numeric value instead.`}:g&&g.length>1&&(y={rule:"genpage-enum-member-ambiguous",message:`${m} labels more than one choice (${g.join(", ")}); the compiled value is whichever option comes last. Use the choice's numeric value instead.`});let b=y?u.initializerShadow(d):void 0;y&&b!==void 0?s(c,"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 '${d.text}'. If you meant the constructor's '${d.text}', move the assignment into the constructor body, or make it a parameter property and read \`this.${d.text}\`. If you meant the choice enum, rename the constructor's parameter or local.`):y&&s(c,y.rule,y.message)}e.forEachChild(c,l)};return l(t),o}function Pse(e,t){return e.createSourceFile("page.js",t,e.ScriptTarget.ES2020,!1,e.ScriptKind.JS).statements.some(r=>(e.isImportDeclaration(r)||e.isExportDeclaration(r))&&r.moduleSpecifier!==void 0&&e.isStringLiteral(r.moduleSpecifier)&&r.moduleSpecifier.text===_o)}function B2(e,t){return t.statements.filter(n=>e.isImportDeclaration(n)&&e.isStringLiteral(n.moduleSpecifier)&&n.moduleSpecifier.text===_o).map(n=>n.getStart(t))}function Rse(e,t){let n=e.createSourceFile("page.js",t,e.ScriptTarget.ES2020,!0,e.ScriptKind.JS),r=B2(e,n),i=new Set(r),o,a="",s=0;for(let u of M2(t))!o&&!i.has(u.start)&&(o={swallows:r.some(l=>l>u.start&&l<u.end),text:t.slice(u.start,u.end).trimEnd()}),a+=t.slice(s,u.start),s=u.end;return a+=t.slice(s),{code:a,inexact:o}}function kse(e,t,n){let r=new Set(B2(e,t));for(let i=t.text.indexOf(n);i!==-1;i=t.text.indexOf(n,i+1))if(!r.has(i)){let o=t.getLineAndCharacterOfPosition(i);return{line:o.line+1,column:o.character+1}}return N0}function V2(e,t,n,r=He.GENPAGE_ITERATION_DEFAULT){if(!n||n.size===0)return[];let i=q2(e,t,{...hC(e,r),target:e.ScriptTarget.ESNext}),o=new Set,a=u=>{var l,c;let d=u.parent;if(e.isImportSpecifier(d)){let f=d.parent.parent.parent;e.isImportDeclaration(f)&&e.isStringLiteral(f.moduleSpecifier)&&f.moduleSpecifier.text===_o&&((l=d.propertyName)!==null&&l!==void 0?l:d.name)===u&&o.add(u.text);return}if(e.isExportSpecifier(d)){!(d.parent.parent.moduleSpecifier!==void 0)&&((c=d.propertyName)!==null&&c!==void 0?c:d.name)===u&&!i.pageOwnsLocalExport(d)&&o.add(u.text);return}e.isPropertyAccessExpression(d)&&d.name===u||e.isBindingElement(d)&&d.propertyName===u||e.isLabeledStatement(d)||e.isBreakOrContinueStatement(d)||i.pageOwns(u)||o.add(u.text)},s=u=>{e.isIdentifier(u)&&n.has(u.text)&&a(u),e.forEachChild(u,s)};return s(t),[...n.keys()].filter(u=>o.has(u))}He.legacyEnumsNeeded=V2;function $se(e,t,n){if(!e?.text||!t||n.length===0)return e;let r=new Map(e.enums),i=e.text;for(let o of n){let a=t.get(o);a&&(i+=a.declaration,r.set(o,a.model))}return{text:i,enums:r}}function Lse(e,t,n,r,i){try{return Mse(e,t,n,r,i)}catch(o){throw U2(o)?new au.SdkError("GENPAGE_COMPILE_DEPTH_EXCEEDED",Ise):o}}He.compileGenPage=Lse;function Mse(e,t,n,r,i){var o,a;let s=(o=i?.iteration)!==null&&o!==void 0?o:He.GENPAGE_ITERATION_DEFAULT,u=new Set,l=$2(e,t,s,u);if(l.diagnostics.length>0)return l;let c=e.createSourceFile("page.tsx",t,e.ScriptTarget.ES2020,!0,e.ScriptKind.TSX),d=e.createSourceFile("page.js",l.code,e.ScriptTarget.ES2020,!0,e.ScriptKind.JS),f=$se(n,r,V2(e,d,r,s)),p=[...Ose(e,d,c,f),...Dse(e,c,f,u,s)];if(!f?.text)return{code:l.code,diagnostics:p};let m=$2(e,f.text,s);if(m.diagnostics.length>0)throw new au.SdkError("GENPAGE_RUNTIME_TYPES_INVALID",`The generated runtime types do not compile (${m.diagnostics.map(b=>`${b.line}:${b.column} ${b.message}`).join("; ")}). This is an SDK defect: the page was not written.`);let h=Rse(e,l.code),g=h.code;if(p.length===0&&(!((a=h.inexact)===null||a===void 0)&&a.swallows))p.push({...mC(e,c).statement(_o,"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(p.length===0&&h.inexact){let{text:b}=h.inexact;p.push({...kse(e,c,b),rule:"genpage-runtime-types-import-form",code:0,message:`the maker portal's patch would delete \`${b.length>80?`${b.slice(0,79)}\u2026`:b}\` 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 p.length===0&&Pse(e,g)&&p.push({...mC(e,c).statement(_o,"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:[He.GENPAGE_RUNTIME_TYPES_BEGIN,m.code,He.GENPAGE_RUNTIME_TYPES_END,g].join(`-`),diagnostics:c}}ke.compileGenPage=Y5});var xg=v(ys=>{"use strict";Object.defineProperty(ys,"__esModule",{value:!0});ys.isFailureAfterPrimaryWrite=ys.failedAfterPrimaryWrite=void 0;var QN=Symbol.for("cds-maker-sdk.createFailedAfterPrimaryWrite");function Q5(e){return typeof e=="object"&&e!==null&&(e[QN]=!0),e}ys.failedAfterPrimaryWrite=Q5;function X5(e){return typeof e=="object"&&e!==null&&e[QN]===!0}ys.isFailureAfterPrimaryWrite=X5});var zd=v(Xn=>{"use strict";Object.defineProperty(Xn,"__esModule",{value:!0});Xn.appApi=Xn.deleteAppResolvingOnce=Xn.mainFormSetShapeIssues=Xn.unpublishedAppModulesQuery=void 0;var mo=Lt(),Z5=zg(),e8=bg(),XN=Qr(),t8=Fd(),r8=xg(),fe=ye(),Ce=le(),Mg=pt(),Ug=Kl(),de=Q(),n8=(0,Ce.odataQuery)([["$select","appmoduleid,name,uniquename,description,aiappdescription"]]),Bg="appmoduleid,name,uniquename,description,aiappdescription";function uu(e,t,r){return"/appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,Ce.odataQuery)([["$select",e],["$filter",t],["$top",r]])}Xn.unpublishedAppModulesQuery=uu;function qg(e,t){return uu(e,t?`appmoduleid eq ${t}`:void 0,t?1:void 0)}function Gd(e,t){return"/sitemaps/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,Ce.odataQuery)([["$select",t],["$filter",`sitemapid eq ${e}`],["$top",1]])}function su(e){var t;let r=(t=e.body)===null||t===void 0?void 0:t.value;if(Array.isArray(r))return r[0]}function i8(e){let t=e?.["@odata.etag"];return typeof t=="string"?t:null}function Wd(e,t){if(typeof e!="string")return!1;try{return(0,Ce.normalizeGuid)(e,"sitemapid")===t}catch{return!1}}function na(e){let t=new Set,r=[];for(let n of e??[])n&&!t.has(n)&&(t.add(n),r.push(n));return r}function o8(e){return`cdsapp_${(e||"").replace(/[^a-zA-Z0-9]/g,"")||"app"}`}async function a8(e,t){var r,n;let i=u=>{throw new de.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,Ce.odataQuery)([["$select","sitemapid"],["$filter",`sitemapnameunique eq '${(0,Ce.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 s8(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,Ce.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 ZN="627090ff-40a3-4053-8790-584edc5be201";function Dr(e){return e instanceof Error?e.message:String(e)}async function l8(e,t){var r;try{let n=`/roles${(0,Ce.odataQuery)([["$select","roleid,_parentrootroleid_value"],["$filter",`_roletemplateid_value eq ${ZN}`]])}`,i=await(0,mo.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 ${ZN}) 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,fe.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 (${Dr(n)}); it will not be visible or playable until a role is granted access to it.`}}async function u8(e,t,r=!0){let n=[];async function i(l,u,c){try{return(await(0,mo.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}' (${Dr(d)}); they were NOT added to the app.`),[]}}let[o,a,s]=await Promise.all([r?i(`/systemforms${(0,Ce.odataQuery)([["$select","formid"],["$filter",`objecttypecode eq '${(0,Ce.odataLiteral)(t)}' and type eq 2 and formactivationstate eq 1`]])}`,"formid","forms"):Promise.resolve([]),i(`/savedqueries${(0,Ce.odataQuery)([["$select","savedqueryid"],["$filter",`returnedtypecode eq '${(0,Ce.odataLiteral)(t)}' and querytype eq 0 and statecode eq 0`]])}`,"savedqueryid","views"),i(`/savedqueryvisualizations${(0,Ce.odataQuery)([["$select","savedqueryvisualizationid"],["$filter",`primaryentitytypecode eq '${(0,Ce.odataLiteral)(t)}'`]])}`,"savedqueryvisualizationid","charts")]);return{forms:o,views:a,charts:s,warnings:n}}var e_=new WeakMap;async function c8(e,t){let r=e_.get(e);r||(r=new Map,e_.set(e,r));let n=r.get(t);if(n!==void 0)return n;let i=await d8(e,t);return i&&r.set(t,i),i}async function t_(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 d8(e,t){let r=`/EntityDefinitions(LogicalName='${(0,Ce.odataPathLiteral)(t)}')${(0,Ce.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 r_(e,t,r){let n=[],i=na(t.entities),o=4,a=await t_(i,o,g=>c8(e,g)),s=i.filter((g,b)=>!a[b]);if(s.length>0)throw new de.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 na(t.components.forms))n.push({"@odata.type":"Microsoft.Dynamics.CRM.systemform",formid:g});for(let g of na(t.components.views))n.push({"@odata.type":"Microsoft.Dynamics.CRM.savedquery",savedqueryid:g});for(let g of na(t.components.charts))n.push({"@odata.type":"Microsoft.Dynamics.CRM.savedqueryvisualization",savedqueryvisualizationid:g});for(let g of na(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 t_(i,o,g=>u8(e,g,!f.has(g.toLowerCase()))),p=m.flatMap(g=>g.warnings),h=new Set([...na(t.components.forms),...na(t.components.dashboards)].map(at));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 at(e){let t=String(e).trim();return(t.startsWith("{")&&t.endsWith("}")?t.slice(1,-1):t).toLowerCase()}var bs=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,Vg="/components/mainFormsByTable",n_=50;function f_(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}function p_(e,t){if(e===void 0)return[];if(e===null||typeof e!="object"||Array.isArray(e))return[{pointer:Vg,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=`${Vg}/${f_(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"||!bs.test(at(c))?r.push({pointer:f,rule:"app-main-form-set-shape",message:`'${String(c)}' is not a form id`}):u.has(at(c))?r.push({pointer:f,rule:"app-main-form-set-shape",message:`form '${c}' is listed twice`}):u.add(at(c))})}return r}Xn.mainFormSetShapeIssues=p_;async function i_(e,t,r){let n=t.components.mainFormsByTable;if(n===void 0)return;let i=p_(n,t.entities);if(i.length>0)throw new de.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,mo.collectPages)(e,`/systemforms${(0,Ce.odataQuery)([["$select","formid,formactivationstate"],["$filter",`objecttypecode eq '${(0,Ce.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(at(h.formid)),Number(h.formactivationstate)===1&&m.add(at(h.formid)));let p=u.map(at);p.forEach((h,g)=>{let b=`${Vg}/${f_(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=at(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 de.ValidationError("app",r,o);return a}async function Wg(e,t){var r,n;let i=u=>({kind:"inconclusive",reason:u}),o=await e.get(uu("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"||!bs.test(at(l))?i(`no single current layer among ${a.length} app row(s)`):{kind:"read",unique:at(l)}}function qd(e,t){let r;return()=>r??(r=Wg(e,t))}var m_=62;function f8(e,t,r,n,i){let o=i.map(a=>`'${a}'`).join(", ");return t==="delete"?new de.SdkError("APP_SITEMAP_SHARED",`Refusing to delete app '${e}': its sitemap '${r.sitemapId}' is also the navigation of app ${o}. The delete removes an app's sitemap with it, and the platform does not stop that for a sitemap another app uses, so those apps would be left without navigation. Nothing was deleted. Remove the sitemap from the other app first, then retry.`):new de.SdkError("APP_SITEMAP_SHARED",`Refusing to ${t} app '${e}': it has no SiteMap component, and the sitemap named like it ('${n??""}', '${r.sitemapId}') is the navigation of app ${o}, so it is not this app's. Nothing was ${t==="fetch"?"saved":"modified"}.`)}async function lu(e,t,r,n,i=!1){var o;let a=c=>{throw new de.SdkError("APP_SITEMAP_UNRESOLVED",`Refusing to ${n} app '${t}': ${c}, so it cannot be determined which sitemap is this app's. Nothing was ${n==="fetch"?"saved":n==="delete"?"deleted":"modified"}. Retry.`)},s;try{s=await Wg(e,t)}catch(c){return a(`reading its current layer failed (${Dr(c)})`)}if(s.kind==="inconclusive")return a(`its current layer could not be read (${s.reason})`);let l;try{l=await(0,mo.collectPages)(e,`/appmodulecomponents${(0,Ce.odataQuery)([["$select","objectid"],["$filter",`_appmoduleidunique_value eq ${s.unique} and componenttype eq ${m_}`]])}`,`app SiteMap component ('${t}')`)}catch(c){return a(`reading its SiteMap component failed (${Dr(c)})`)}let u;if(l.length>1)return a(`its current layer carries ${l.length} SiteMap components, where an app can hold one`);if(l.length===1){let c=(o=l[0])===null||o===void 0?void 0:o.objectid;if(typeof c!="string"||!bs.test(at(c)))return a(`its SiteMap component carries an object id that is not a GUID ('${String(c)}')`);u={sitemapId:at(c),by:"component"}}else{let c=await a8(e,r);if(!c)return;let d;try{d=(0,Ce.normalizeGuid)(c,"sitemapId")}catch{return a(`the sitemap lookup by unique name returned a sitemapid that is not a GUID ('${String(c)}')`)}u={sitemapId:d,by:"name"}}if(i||u.by==="name"){let c=await p8(e,u.sitemapId,t,a);if(c.length>0)throw f8(t,n,u,r,c)}return u}async function p8(e,t,r,n){var i;let o;try{o=await(0,mo.collectPages)(e,`/appmodulecomponents${(0,Ce.odataQuery)([["$select","_appmoduleidunique_value"],["$filter",`componenttype eq ${m_} and objectid eq ${t}`]])}`,`apps using sitemap '${t}'`)}catch(u){return n(`reading which apps use sitemap '${t}' failed (${Dr(u)})`)}let a=new Set;for(let u of o){let c=u?._appmoduleidunique_value;if(typeof c!="string"||!bs.test(at(c)))return n(`a SiteMap component naming sitemap '${t}' carries no app layer id`);a.add(at(c))}let s=at(r),l=[];for(let u of a){let c;try{c=await e.get(uu("appmoduleid",`appmoduleidunique eq ${u}`))}catch(f){return n(`resolving app layer '${u}' failed (${Dr(f)})`)}if(c.status<200||c.status>=300)return n(`resolving app layer '${u}' returned HTTP ${c.status}`);let d=(i=c.body)===null||i===void 0?void 0:i.value;if(!Array.isArray(d))return n(`resolving app layer '${u}' returned a malformed body`);for(let f of d){let m=f?.appmoduleid;if(typeof m!="string"||!bs.test(at(m)))return n(`app layer '${u}' resolved to a row with no app id`);let p=at(m);if(p===s||l.includes(p))continue;let h;try{h=await Wg(e,p)}catch(g){return n(`reading the current layer of app '${p}' failed (${Dr(g)})`)}if(h.kind==="inconclusive")return n(`the current layer of app '${p}' could not be read (${h.reason})`);h.unique===u&&l.push(p)}}return l}async function h_(e,t,r,n=qd(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,mo.collectPages)(e,`/appmodulecomponents${(0,Ce.odataQuery)([["$select","objectid"],["$filter",`_appmoduleidunique_value eq ${at(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=>at(String(p.objectid)))}catch(m){return i(`reading its form components failed (${Dr(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=>!bs.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+=n_){let p=u.slice(m,m+n_);try{let h=await(0,mo.collectPages)(e,`/systemforms${(0,Ce.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=at(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 (${Dr(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 m8(e,t,r,n){let i=await h_(e,t,r,n);if(i.kind==="inconclusive")throw new de.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 de.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 h8(e,t,r,n){let i;try{i=await h_(e,t,r,n)}catch(a){i={kind:"inconclusive",reason:Dr(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 o_(e,t,r){if(r.length===0)return;let n="/AddAppComponents";(0,fe.ensureSuccess)(await e.post(n,{AppId:t,Components:r}),e.apiUrl(n))}async function a_(e,t,r,n=qd(e,t)){var i;if(r.length===0)return;let o=await n();if(o.kind==="inconclusive")throw new de.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,Ce.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 de.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 de.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 de.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 g8(e,t,r){let n=`/appmodules(${t})`,i=`/sitemaps(${r.sitemapId})`,o;try{o=await b8(e,r.sitemapId,r.sitemapNameUnique)}catch(l){return{outcome:"kept",reason:`whether its sitemap row exists could not be determined (${Dr(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 (${Dr(l.error)})`,...l.lock?{lock:!0}:{}}:{outcome:"unconfirmed",foreignSitemap:a,reason:`its delete was sent but its outcome is unknown (${Dr(l.error)})`,...l.lock?{lock:!0}:{}};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,fe.resendAppSearchIndexRace)(()=>e.delete(n));if(l.status===404)return s({kind:"deleted"});let u=Gg(l,e.apiUrl(n));return s(u.kind!=="deleted"&&(0,fe.isConcurrencyLockRefusal)(l)?{...u,lock:!0}:u)}return e.supportsAtomicBatch?r.sitemapWriteToken?s(await y_(e,[{path:n},{path:i,etag:r.sitemapWriteToken}],{reportLock:!0})):{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 y8(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}')`}.`,s="Once the lock frees \u2014 another customization operation holds it \u2014 check that the rows exist and are this create's own before removing them.";return t.lock&&t.outcome==="kept"?e.message+=` The partial app this create wrote was KEPT \u2014 its rollback deleted nothing, because the environment's customization lock refused it (another customization operation was running): ${i}. ${s} While it exists, ${a}`:t.lock?e.message+=` Whether the partial app this create wrote was removed could not be confirmed, because the environment's customization lock refused or interrupted its rollback, so it may not have run. Check for ${i}. ${s} While any of it exists, ${a}`: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 b8(e,t,r){var n,i,o;let a=Gd(t,"sitemapid,sitemapnameunique"),s=await e.get(a);if(s.status<200||s.status>=300)throw new de.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 de.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 v8(e,t){var r;let n;try{n=await e.get(uu("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!Wd(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 g_(e,t){var r;let n=(0,Ce.normalizeGuid)(t,"id"),i=w=>{throw new de.SdkError("APP_SITEMAP_UNRESOLVED",`Refusing to delete app '${n}': ${w} Deleting the app would destroy the only pointer to its sitemap, stranding that row and reserving its unique name forever. Retry.`)},o=`/appmodules(${n})${n8}`,a;try{a=await e.get(o)}catch(w){return i(`reading the app failed (${w.message}).`)}let s,l=!1;if(a.status===404){let w=await v8(e,n);if(w.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; ${w.why}.`);s=w.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,fe.readEtag)(a)},c=await lu(e,n,s,"delete");if(!c)return{uniquename:s,...u};let d=c.sitemapId,f=await Vd(e,d),m=Gd(d,"sitemapid,sitemapnameunique,sitemapxml"),p;try{p=await e.get(m)}catch(w){return i(`reading sitemap '${d}' failed (${w.message}).`)}if(p.status<200||p.status>=300)return i(`reading sitemap '${d}' returned HTTP ${p.status}.`);let h=su(p);if(!h)return i(`sitemap '${d}' was not returned by the unpublished-aware read.`);if(c.by==="name"&&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(!Wd(h.sitemapid,d))return i(`sitemap '${d}' was read back as a row carrying sitemapid '${String(h.sitemapid)}'.`);let g=h.sitemapxml;if(typeof g!="string")return i(`sitemap '${d}' returned no sitemapxml.`);let b=await lu(e,n,s,"delete",!0);return b?.sitemapId!==d||b.by!==c.by?i(`its sitemap link changed while it was read (sitemap '${d}' by ${c.by}, then ${b?`'${b.sitemapId}' by ${b.by}`:"none"}).`):{sitemapId:d,uniquename:s,sitemapXml:g,...u,sitemapEtag:f}}async function w8(e,t,r){let n=(0,Ce.normalizeGuid)(t,"id"),i=await g_(e,n);await r?.(i.sitemapXml),await v_(e,n,i)}Xn.deleteAppResolvingOnce=w8;async function C8(e,t){let r=await y_(e,t);if(r.kind!=="deleted")throw r.error}function Gg(e,t){try{return(0,fe.ensureSuccess)(e,t),{kind:"deleted"}}catch(r){return b_(e.status)?{kind:"refused",error:r}:{kind:"unknown",error:r}}}function E8(e,t){var r;if(e.status!==400&&(e.status<200||e.status>=300))return!1;let n=(r=(0,Ug.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,fe.namesAppSearchIndexRace)(i.text))}async function y_(e,t,r={}){let n=`batch_${(0,Mg.newId)()}`,i=`changeset_${(0,Mg.newId)()}`,o=t.map((p,h)=>[`--${i}`,"Content-Type: application/http","Content-Transfer-Encoding: binary",`Content-ID: ${h+1}`,"",`DELETE ${e.apiUrl(p.path)} HTTP/1.1`,...p.etag?[`If-Match: ${p.etag}`]:[],""].join(`\r-`)),a=[`--${n}`,`Content-Type: multipart/mixed;boundary=${i}`,"",...o,`--${i}--`,`--${n}--`,""].join(`\r-`),s=e.apiUrl("/$batch"),l=o.map((p,h)=>String(h+1)),u;try{u=await(0,fe.resendWhile)(p=>E8(p,l),()=>e.postBatch(a,n),fe.DEADLOCK_BACKOFF_MS)}catch(p){return{kind:"unknown",error:p}}if(r.reportLock){if((0,Ug.isChangeSetLockRefusal)(u,l))return{kind:"refused",lock:!0,error:new de.ConnectionError(s,u.status,`atomic delete of app '${t[0].path}' was refused whole by the customization lock, so it deleted nothing`)};if((0,fe.isConcurrencyLockRefusal)(u)){let p=Gg(u,s);return p.kind==="deleted"?p:{...p,lock:!0}}}let c=Gg(u,s);if(c.kind!=="deleted")return c;let d=`app '${t[0].path}'`;if(typeof u.body!="string"||u.body.length===0)return{kind:"unknown",error:new de.ConnectionError(s,u.status,`atomic delete of ${d} cannot be confirmed: the $batch response had no readable body, so the change set's outcome is unknown`)};let f=(0,Ug.parseChangeSetStatuses)(u.body,l);if(f===void 0)return{kind:"unknown",error:new de.ConnectionError(s,u.status,`atomic delete of ${d} cannot be confirmed: the $batch response could not be parsed as a change set, so the outcome is unknown`)};let m=f.find(p=>p<200||p>=300);return m!==void 0?{kind:"refused",error:new de.ConnectionError(s,m,`atomic delete of ${d} was rolled back: the change set reported HTTP ${m}`)}:f.length!==o.length?{kind:"unknown",error:new de.ConnectionError(s,u.status,`atomic delete of ${d} cannot be confirmed: the $batch response reported ${f.length} operation result(s), expected exactly ${o.length}`)}:{kind:"deleted"}}async function Vd(e,t){try{let r=await e.get(`/sitemaps(${t})?$select=sitemapid`);return r.status<200||r.status>=300?null:(0,fe.readEtag)(r)}catch{return null}}async function s_(e,t){let r=`/appmodules(${t})?$select=appmoduleid`,n=await e.get(r);if(n.status!==404)return(0,fe.ensureSuccess)(n,e.apiUrl(r)),(0,fe.readEtag)(n)}function l_(e){return{sitemapxml:e.sitemapxml,...e.sitemapname!==void 0?{sitemapname:e.sitemapname}:{}}}async function Fg(e,t,r,n){if(!n)return null;let i=await Vd(e,t);if(!i)return null;try{let o=await e.get(Gd(t,"sitemapid,sitemapname,sitemapnameunique,sitemapxml"));if(o.status<200||o.status>=300)return null;let a=su(o);return!a||!Wd(a.sitemapid,t)||a.sitemapnameunique!==n||a.sitemapxml!==r.sitemapxml||r.sitemapname!==void 0&&a.sitemapname!==r.sitemapname?null:i}catch{return null}}function b_(e){return e>=400&&e<500&&e!==408&&e!==429}function u_(e,t,r){if(!e)throw new de.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 v_(e,t,r){let n=`/appmodules(${t})`,i=r.draft?void 0:u_(r.appEtag,t,"app");if(!r.sitemapId){if(r.draft){(0,fe.ensureSuccess)(await(0,fe.resendAppSearchIndexRace)(()=>e.delete(n)),e.apiUrl(n));return}await A8(e,n,i);return}if(!e.supportsAtomicBatch)throw new de.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 C8(e,[{path:n,etag:i},{path:`/sitemaps(${r.sitemapId})`,etag:u_(r.sitemapEtag,t,"sitemap")}])}async function A8(e,t,r){(0,fe.ensureSuccess)(await(0,fe.resendAppSearchIndexRace)(()=>e.delete(t,{headers:{"If-Match":r}})),e.apiUrl(t))}async function c_(e,t){if(!/GenPageId/i.test(t))return;let r;try{r=[...new Set((0,Z5.collectGenPageIds)(t))]}catch(i){throw new de.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 (${Dr(i)}).`)}if(r.length===0)return;let n=await(0,e8.findMissingGenPages)(e,r,"sitemap generative-page preflight");if(n.length>0)throw new de.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 S8(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")}function N8(e,t){var r;let n=[["name",e.appModuleName],["description",e.appModuleDescription],["aiappdescription",e.appModuleAiDescription]],i={};for(let[o,a]of n)a!==void 0&&(t!==void 0&&String((r=t[o])!==null&&r!==void 0?r:"")===String(a??"")||(i[o]=a));return i}async function d_(e,t,r){var n;let i=(0,Ce.normalizeGuid)(t,"id"),o=r==="tokens-first",a=o?await s_(e,i):null,s=qg(Bg,i),l=(0,fe.ensureSuccess)(await e.get(s),e.apiUrl(s)),u=(n=su(l))!==null&&n!==void 0?n:{};if(!u.appmoduleid)throw new de.SdkError("APP_NOT_FOUND",`App '${i}' was not found (checked the unpublished-aware projection, which includes drafts).`);let c=await lu(e,i,u.uniquename,"fetch"),d=c?.sitemapId,f=null;if(c&&d){o&&(f=await Vd(e,d));let p=Gd(d,"sitemapid,sitemapname,sitemapnameunique,sitemapxml"),h=(0,fe.ensureSuccess)(await e.get(p),e.apiUrl(p)),g=su(h),b=C=>{throw new de.SdkError("APP_SITEMAP_UNRESOLVED",`Refusing to fetch app '${i}': its sitemap '${d}' was located by its ${c.by==="component"?"SiteMap component":"unique name"}, but ${C}, 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(c.by==="name"&&g.sitemapnameunique!==u.uniquename)throw new de.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(!Wd(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");let w=await lu(e,i,u.uniquename,"fetch");if(w?.sitemapId!==d||w.by!==c.by)throw new de.SdkError("APP_SITEMAP_UNRESOLVED",`Refusing to fetch app '${i}': its sitemap link changed while it was read (sitemap '${d}' by ${c.by}, then ${w?`'${w.sitemapId}' by ${w.by}`:"none"}). Nothing was saved. Retry.`);u.$sitemap=g,o||(f=await Vd(e,d))}o||(a=await s_(e,i));let m=a??i8(u);return{raw:u,etag:f,...u.appmoduleid?{siblingEtags:{[(0,Ce.normalizeGuid)(u.appmoduleid,"appmoduleid")]:m}}:{}}}Xn.appApi={get(e,t){return d_(e,t,"tokens-first")},readContentThenToken(e,t){return d_(e,t,"content-first")},async list(e,t){let r=qg(Bg);return(await(0,mo.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;if(typeof n.appModuleName!="string"||n.appModuleName.trim()==="")throw new de.ValidationError("app",n.appModuleId,[{pointer:"/name",rule:"app-name-required",message:"an app needs a name to be created, and its 'name' is missing or blank \u2014 set it (updateElement('app', id, '/name', \u2026), or addElement when the key was removed) and push again. Nothing was written."}]);await c_(e,n.sitemapxml);let i=await i_(e,n,n.appModuleId),o=n.iconWebResourceId?void 0:await s8(e),a=n.iconWebResourceId||o?.id;if(!a)throw new de.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||o8(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,fe.ensureSuccess)(await(0,fe.resendDeadlockVictim)(()=>e.post(c,(0,fe.withClientMintedId)(u,"appmoduleid",r))),e.apiUrl(c)),f=(0,fe.resolveCreatedId)(d,"appmoduleid","app module",r),m=null,p=null,h=[];s&&h.push(s);let g={kind:"notRequested"},b=n.sitemapId?(0,Ce.normalizeGuid)(n.sitemapId,"sitemapId"):(0,Mg.newId)(),w=!1,C=l_(n);try{let O="/sitemaps",k=(0,fe.echoWrite)("sitemapid"),I=await e.post(`${O}${k.query}`,{sitemapid:b,sitemapnameunique:l,...C},k.options);w=b_(I.status);let D=(0,fe.ensureSuccess)(I,e.apiUrl(O));p=(0,fe.readEtag)(D),m=p??await Fg(e,b,C,l);let P=await r_(e,n,i);h.push(...P.warnings);let x=P.components;x.unshift({"@odata.type":"Microsoft.Dynamics.CRM.sitemap",sitemapid:b}),await o_(e,f,x);let K=qd(e,f);await a_(e,f,P.tables,K),i&&await m8(e,f,i,K);let Oe=await l8(e,f);Oe&&h.push(Oe),n.appSettings&&Object.keys(n.appSettings).length>0&&h.push(...await(0,t8.applyAppSettings)(e,f,n.appSettings)),n.published!==!1&&(await(0,XN.publishAppModule)(e,f),g={kind:"submitted"})}catch(O){let k=await g8(e,f,{sitemapId:b,sitemapNameUnique:l,serverRefusedSitemap:w,sitemapWriteToken:p});throw(0,r8.failedAfterPrimaryWrite)(y8(O,k,{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,fe.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;let u=r,c=(0,Ce.normalizeGuid)(t,"id");if(await c_(e,u.sitemapxml),!u.sitemapId)throw new de.ValidationError("app",c,[{pointer:"/sitemapId",rule:"app-sitemap-identity-missing",message:`missing sitemap identity \u2014 re-fetch the app before pushing edits: fetchArtifact('app', '${c}', { 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', '${c}'), clear the local copy with deleteArtifact('app', '${c}'), then author the app again and push.`}]);let d=(0,Ce.normalizeGuid)(u.sitemapId,"sitemapId");if(!(0,fe.isVersionToken)(n))throw new de.SdkError("APP_UPDATE_NO_ETAG",`Refusing to push app '${c}': ${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 f=await i_(e,u,c),m=await r_(e,u,f),p=`/appmodules(${c})`,h=(a=o?.[c])!==null&&a!==void 0?a:null,g,b;try{let Ne=qg(Bg,c),se=await e.get(Ne);if(se.status>=200&&se.status<300){let We=su(se);if(typeof We=="object"&&We!==null&&!Array.isArray(We)){g=We;let ir=g.uniquename;b=typeof ir=="string"&&ir?ir:void 0}}}catch{}let w=N8(u,g),C=await lu(e,c,b||u.appModuleUniqueName,"push");if(C?.sitemapId!==d)throw new de.SdkError("APP_SITEMAP_UNRESOLVED",`Refusing to push app '${c}': ${C?`its sitemap is now '${C.sitemapId}'`:"it has no sitemap now"}, not '${d}', the one this copy holds \u2014 the app's sitemap is no longer the one this copy was fetched with. Nothing was modified. Re-fetch the app (fetchArtifact('app', '${c}', { overwrite: true })) and re-apply the change.`);let S=h;if(Object.keys(w).length>0){if(!(0,fe.isVersionToken)(h))throw new de.SdkError("APP_UPDATE_NO_ETAG",`Refusing to push app '${c}': ${h?`the concurrency token held for its appmodule header ('${h}') 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', '${c}', { overwrite: true })) and re-apply the change.`);let Ne=(0,fe.echoWrite)("appmoduleid",{"If-Match":h}),se=await e.patch(`${p}${Ne.query}`,w,Ne.options);if(S8(se))throw new de.SdkError("APP_DRAFT_HEADER_NOT_WRITABLE",`Refusing to update app '${c}': 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,fe.ensureSuccess)(se,e.apiUrl(p)),S=(0,fe.readEtag)(se)}let O=l_(u),k=u.sitemapNameUnique||b||u.appModuleUniqueName||void 0,I=(0,fe.echoWrite)("sitemapid",{"If-Match":n}),D=`/sitemaps(${d})`,P;try{P=(0,fe.ensureSuccess)(await e.patch(`${D}${I.query}`,{...O},I.options),e.apiUrl(D))}catch(Ne){throw(0,de.withPartialTokens)(Ne,{siblingEtags:{[c]:S}})}let x=[...m.warnings],K=qd(e,c);try{await o_(e,c,m.components),await a_(e,c,m.tables,K)}catch(Ne){x.push(`App '${c}': one or more components were not pinned (${Ne.message}). Navigation may reference content not included in the app; re-push to retry.`)}f&&x.push(...await h8(e,c,f,K));let Oe={kind:"notRequested"},Vt=S,Xe=(s=(0,fe.readEtag)(P))!==null&&s!==void 0?s:await Fg(e,d,O,k);if(u.published===!0){try{await(0,XN.publishAppModule)(e,c),Oe={kind:"submitted"}}catch(Ne){Oe={kind:"failed",error:Ne},x.push(`App '${c}': saved, but publishing failed (${Ne.message}). The app remains unpublished; re-push to retry.`)}if(Oe.kind==="submitted"){Vt=null;try{let Ne=await e.get(`/appmodules(${c})?$select=appmoduleid`);Ne.status>=200&&Ne.status<300&&(Vt=(0,fe.readEtag)(Ne)),Xe=(l=await Fg(e,d,O,k))!==null&&l!==void 0?l:Xe}catch{}}}return{id:c,etag:Xe,siblingEtags:{[c]:Vt},publish:Oe,...x.length>0?{warnings:x}:{}}},async delete(e,t){let r=(0,Ce.normalizeGuid)(t,"id");await v_(e,r,await g_(e,r))}}});var zg=v(vs=>{"use strict";Object.defineProperty(vs,"__esModule",{value:!0});vs.deleteAppCascade=vs.collectGenPageIds=void 0;var _8=zd(),T8=Q(),jg=le(),D8=ns();function w_(e){let t=[],r=s=>l=>t.push(`${s}: ${l}`),n=new D8.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 T8.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,jg.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}vs.collectGenPageIds=w_;async function I8(e,t,r){let n=(0,jg.normalizeGuid)(t,"appModuleId");(0,jg.normalizeGuid)(r,"appModuleIdUnique");let i=[],o=[],a=[];await(0,_8.deleteAppResolvingOnce)(e,n,l=>{l!==void 0&&a.push(...w_(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}}vs.deleteAppCascade=I8});var C_={};Jr(C_,{Guid:()=>U});var U,ht=L(()=>{"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,Xt=L(()=>{"use strict";st();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 E_={};Jr(E_,{ScriptUtilities:()=>R});var R,st=L(()=>{"use strict";ht();Xt();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 jd,Hd,ia,Kd,Hg,Jd,Kg=L(()=>{"use strict";(function(e){e[e.FormElementNodeChange=0]="FormElementNodeChange",e[e.FormElementAttributeChange=1]="FormElementAttributeChange"})(jd||(jd={}));Hd=class{type;targetNode;constructor(t,r){this.type=t,this.targetNode=r}},ia=class extends Hd{key;oldValue;newValue;constructor(t,r,n,i){super(jd.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)}},Kd=class extends Hd{property;oldValue;newValue;constructor(t,r,n,i){super(jd.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)}},Hg=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()})}},Jd=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 Hg(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 A_={};Jr(A_,{ChartGridMode:()=>ln,ColumnLayoutWidths:()=>L8,ComponentCategory:()=>Qd,ComponentType:()=>Jg,ControlLayoutTypes:()=>r0,DisplayConditionsInfo:()=>R8,ElementNames:()=>E,ElementProperties:()=>y,ElementType:()=>Qg,EntityAttributeProperty:()=>Xg,EventType:()=>cu,FormActivationState:()=>t0,FormCanvasServiceScope:()=>j8,FormDesignerSideBarTab:()=>Yg,FormPresentation:()=>Zg,FormState:()=>Yd,FormType:()=>gt,HeaderDensityType:()=>ho,LookUpTable:()=>Zn,MORE_TAB_PREFIX:()=>x8,NavBarChildElementType:()=>e0,PREVIEW_ID_HEADER_FLYOUT:()=>B8,PREVIEW_ID_HEADER_OVERFLOW_BUTTON:()=>V8,PREVIEW_ID_NAVIGATION_AREA:()=>M8,PREVIEW_ID_QUICKCREATE_ROOT:()=>W8,PREVIEW_ID_TAB:()=>G8,PREVIEW_ID_TAB_LIST:()=>q8,PREVIEW_ID_TAB_PANEL:()=>U8,PropertyModelKeys:()=>o0,PropertyModelSectionKeys:()=>$8,RELATED_TAB_ID:()=>a0,RELATED_TAB_PREFIX:()=>F8,SectionDefaultProperties:()=>k8,SectionLayoutTypes:()=>je,TabContentType:()=>n0,TabDefaultProperties:()=>go,TabLayoutTypes:()=>ze,TelemetryPropertyNames:()=>z8,UnboundControlPropertyKeys:()=>i0,compositeAddressFields:()=>P8,compositeFieldNames:()=>zr,compositeFields:()=>O8});var gt,Jg,Yg,E,y,Qg,zr,O8,P8,Xg,Zn,Yd,ho,Zg,R8,e0,t0,ze,k8,go,je,r0,n0,L8,i0,o0,$8,cu,ln,a0,x8,F8,M8,U8,B8,q8,V8,G8,W8,z8,Qd,j8,ue=L(()=>{"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"})(gt||(gt={}));(function(e){e[e.Form=0]="Form",e[e.Dialog=1]="Dialog"})(Jg||(Jg={}));(function(e){e[e.Components=0]="Components",e[e.Properties=1]="Properties",e[e.Relationship=2]="Relationship",e[e.BusinessRules=3]="BusinessRules"})(Yg||(Yg={}));(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"})(Qg||(Qg={}));zr={fullname:"fullname",yomifullname:"yomifullname",address1_composite:"address1_composite",address2_composite:"address2_composite",address3_composite:"address3_composite",billto:"billto_composite",shipto:"shipto_composite"},O8=[zr.fullname,zr.yomifullname,zr.address1_composite,zr.address2_composite,zr.address3_composite,zr.billto,zr.shipto],P8=[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"})(Xg||(Xg={}));(function(e){e[e.DependencyFieldTable=0]="DependencyFieldTable",e[e.LockedFieldTable=1]="LockedFieldTable"})(Zn||(Zn={}));(function(e){e[e.Published=0]="Published",e[e.Draft=1]="Draft",e[e.New=2]="New",e[e.SaveAs=3]="SaveAs"})(Yd||(Yd={}));(function(e){e.Low="Low",e.HighReadOnlyValues="HighReadOnlyValues",e.HighWithControls="HighWithControls"})(ho||(ho={}));(function(e){e[e.ClassicForm=0]="ClassicForm",e[e.AirForm=1]="AirForm",e[e.ConvertedICForm=2]="ConvertedICForm"})(Zg||(Zg={}));R8={TopOrderFormId:"topOrderFormId",NextDisplayOrder:"nextDisplayOrder"};(function(e){e[e.NavBarRelationShipItem=0]="NavBarRelationShipItem",e[e.NavBarItem=1]="NavBarItem"})(e0||(e0={}));(function(e){e[e.InActive=0]="InActive",e[e.Active=1]="Active"})(t0||(t0={}));(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={}));k8={ShowLabel:"false",LockLevel:"0",IsUserDefined:"0",LabelWidth:"115",columns:"1",ShowBar:"false",Layout:"varwidth",namePrefix:"_section_"},go={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"})(r0||(r0={}));(function(e){e.cardSections="cardSections",e.singleComponent="singleComponent",e.default="default",e.expandAvailableSpace="expandAvailableSpace"})(n0||(n0={}));L8={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"})(i0||(i0={}));(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"})(o0||(o0={}));$8={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"})(cu||(cu={}));(function(e){e.All="All",e.Chart="Chart",e.Grid="Grid"})(ln||(ln={}));a0="tab_related3b554255-7717-4d17-bb7f-9936fb1e75ca",x8="more_tab_",F8="related_tab_",M8="preview_id_navigation_area",U8="tab-section",B8="headerFieldsFlyout",q8="tablist",V8="header_overflowButton",G8="tab",W8="quickCreateRoot",z8={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"})(Qd||(Qd={}));j8="CellCanvasServiceScope"});var S_={};Jr(S_,{Attribute:()=>Xd,FormElementNode:()=>re});var Xd,re,It=L(()=>{"use strict";st();Xt();Kg();ue();ht();Xd=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 Xd(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 ia(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 ia(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 ia(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 Kd(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 ia(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 N_={};Jr(N_,{ControlClassId:()=>N,ControlNamePrefixes:()=>Zd,getControlDisplayNames:()=>H8});function H8(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,oa=L(()=>{"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 aa=v((Ble,T_)=>{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{}}}),__=function(){return du};Object.setPrototypeOf(__,du);T_.exports=__});var cr,Ri,D_,I_,ws=L(()=>{"use strict";cr="cds-designer-models",Ri="FormCustomControl",D_="FormCell",I_="Form"});var sa,s0=L(()=>{"use strict";Wl();ue();sa=class e{static lockedFieldCount=new ar;static dependencyFieldCount=new ar;static getNecessaryLookUpTable(t){switch(t){case Zn.DependencyFieldTable:return e.dependencyFieldCount;case Zn.LockedFieldTable:return e.lockedFieldCount}}static initCanvasLockedFieldLookUp(t){switch(t){case Zn.DependencyFieldTable:e.dependencyFieldCount=new ar;case Zn.LockedFieldTable:e.lockedFieldCount=new ar}}}});var ef,O_=L(()=>{"use strict";ht();st();ue();It();ef=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 ki(){return ei||(ei=window._makerConfig,ei&&window?.location?.search?.indexOf("useProductionConfig")>-1&&(ei={...ei,region:"prod",graphQLEndpoint:"https://graph.make.powerapps.com/"}),ei?.region==="prod"&&(ei={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/"}}},...ei}),ei||{aadClientId:"a8f7a65c-f5ba-4859-b2d6-df772c264e9d",location:"cus",region:"test",publicPath:"/",graphQLEndpoint:"https://graph.make.test.powerapps.com/"})}var ei,tf=L(()=>{"use strict";});function P_(e,t,r){if(!e)return rf.has(e)||(window._ppux?.log?.("PPUX/Geo/NonExistent",{eventType:"Trace",team:"Shell",severity:"Error",errorCode:"GeoIsEmpty"}),rf.add("")),!1;if(e){if(e=e.toLowerCase(),rf.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}}),rf.add(e),!1}return!0}function K8(e){return P_(e,l0,"Location dictionary")?l0[e.toLowerCase()]:"us"}function J8(){let e=ki().location.toLowerCase();return P_(e,l0,"Current location dictionary")?e:"us"}var rf,l0,Zle,R_=L(()=>{"use strict";tf();rf=new Set,l0={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"};Zle=K8(J8())});var Y,tue,k_=L(()=>{"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"},tue={[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 L_=L(()=>{"use strict";tf();});var fu=L(()=>{"use strict";tf();R_();k_();L_();});function pu(e,t){return $_?$_.isOverridden(e,t):{overridden:!1}}var $_,mu=L(()=>{"use strict";});var u0=L(()=>{"use strict";fu();mu();});function Y8(e,t){let{region:r}=ki();return()=>{let n=e.settings[t];if(n.allowOverrides){let s=pu(e.packageName,t);if(s.overridden)return typeof s.value=="string"?Q8(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 Q8(e){return isNaN(Number(e))?e==="true"?!0:e==="false"?!1:e:Number(e)}function X8(e){let t=e.packageName;if(nf.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=>d0(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=>!af(i))){let i=`error parsing settings config for package ${t}, setting ${r} has invalid region`;throw console.error(i),new Error(i)}})}function hu(e){X8(e);let t={};return Object.keys(e.settings).forEach(r=>{t[r]={enumerable:!0,get:Y8(e,r)}}),nf.set(e.packageName,e),Object.defineProperties({},t)}function c0(e,t){return nf.has(e)?!!nf.get(e).settings[t]:!1}var nf,of=L(()=>{"use strict";fu();mu();f0();gu();nf=new Map});function x_(e,t){let{region:r}=ki();return()=>{let n=pu(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 Z8(e){let t=e.packageName;if(sf.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=>c0(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=>!af(i))){let i=`error parsing feature gates config for package ${t}, feature ${r} has invalid region`;throw console.error(i),new Error(i)}})}function p0(e){Z8(e);let t={};Object.keys(e.features).forEach(i=>{t[i]={enumerable:!0,configurable:!0,get:x_(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:x_(e,o.toString())}}),Object.defineProperties(r,i),n.clear()}},sf.set(e.packageName,e),Object.defineProperties(r,t)}function d0(e,t){return sf.has(e)?!!sf.get(e).features[t]:!1}var sf,f0=L(()=>{"use strict";fu();gu();mu();of();sf=new Map});var M_=v((_ue,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 q_=v(m0=>{"use strict";var e6=Object.prototype.hasOwnProperty,t6;function U_(e){try{return decodeURIComponent(e.replace(/\+/g," "))}catch{return null}}function B_(e){try{return encodeURIComponent(e)}catch{return null}}function r6(e){for(var t=/([^=?#&]+)=?([^&]*)/g,r={},n;n=t.exec(e);){var i=U_(n[1]),o=U_(n[2]);i===null||o===null||i in r||(r[i]=o)}return r}function n6(e,t){t=t||"";var r=[],n,i;typeof t!="string"&&(t="?");for(i in e)if(e6.call(e,i)){if(n=e[i],!n&&(n===null||n===t6||isNaN(n))&&(n=""),i=B_(i),n=B_(n),i===null||n===null)continue;r.push(i+"="+n)}return r.length?t+r.join("&"):""}m0.stringify=n6;m0.parse=r6});var y0=v((Due,H_)=>{"use strict";var G_=M_(),lf=q_(),W_=/[\n\r\t]/g,i6=/^[A-Za-z][A-Za-z0-9+-.]*:\/\//,o6=/^([a-z][a-z0-9.+-]*:)?(\/\/)?([\\/]+)?([\S\s]*)/i,a6=/^[a-zA-Z]:/,s6=/^[\x00-\x20\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]+/;function g0(e){return(e||"").toString().replace(s6,"")}var h0=[["#","hash"],["?","query"],function(t,r){return ti(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]],V_={hash:1,query:1};function z_(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 ri(unescape(e.pathname),{});else if(i==="string"){n=new ri(e,{});for(o in V_)delete n[o]}else if(i==="object"){for(o in e)o in V_||(n[o]=e[o]);n.slashes===void 0&&(n.slashes=i6.test(e.href))}return n}function ti(e){return e==="file:"||e==="ftp:"||e==="http:"||e==="https:"||e==="ws:"||e==="wss:"}function j_(e,t){e=g0(e),e=e.replace(W_,""),t=t||{};var r=o6.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)):ti(n)?s=r[4]:n?i&&(s=s.slice(2)):a>=2&&ti(t.protocol)&&(s=r[4]),{protocol:n,slashes:i||ti(n),slashesCount:a,rest:s}}function l6(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 ri(e,t,r){if(e=g0(e),e=e.replace(W_,""),!(this instanceof ri))return new ri(e,t,r);var n,i,o,a,s,l,u=h0.slice(),c=typeof t,d=this,f=0;for(c!=="object"&&c!=="string"&&(r=t,t=null),r&&typeof r!="function"&&(r=lf.parse),t=z_(t),i=j_(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||a6.test(e))||!i.slashes&&(i.protocol||i.slashesCount<2||!ti(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=l6(d.pathname,t.pathname)),d.pathname.charAt(0)!=="/"&&ti(d.protocol)&&(d.pathname="/"+d.pathname),G_(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:"&&ti(d.protocol)&&d.host?d.protocol+"//"+d.host:"null",d.href=d.toString()}function u6(e,t,r){var n=this;switch(e){case"query":typeof t=="string"&&t.length&&(t=(r||lf.parse)(t)),n[e]=t;break;case"port":n[e]=t,G_(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<h0.length;a++){var s=h0[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:"&&ti(n.protocol)&&n.host?n.protocol+"//"+n.host:"null",n.href=n.toString(),n}function c6(e){(!e||typeof e!="function")&&(e=lf.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||ti(r.protocol)?"//":"");return r.username?(o+=r.username,r.password&&(o+=":"+r.password),o+="@"):r.password?(o+=":"+r.password,o+="@"):r.protocol!=="file:"&&ti(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}ri.prototype={set:u6,toString:c6};ri.extractProtocol=j_;ri.location=z_;ri.trimLeft=g0;ri.qs=lf;H_.exports=ri});var d6,K_=L(()=>{"use strict";d6=Ae(y0());});function b0(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 uf=L(()=>{"use strict";});var v0,w0,C0=L(()=>{"use strict";uf();v0=class{features=new Map;register(t,r){let n=b0(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()}},w0=new v0});var E0=L(()=>{"use strict";});function af(e){return f6.has(e)}var f6,gu=L(()=>{"use strict";u0();f0();of();mu();u0();K_();C0();uf();E0();f6=new Set(["tie","test","prod","preview","preprod","gov","high","dod","mooncake","ex","rx"])});var p6,J_=L(()=>{"use strict";gu();p6=hu({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 Z_,S0,Cs,la,A0,cf,Es,Li,Ue,Y_,Q_,X_,Tn=L(()=>{"use strict";Z_={ThreeEqColumn_FirstColumn:34,ThreeEqColumn_SecondColumn:33,ThreeEqColumn_ThirdColumn:33,FiveEqColumn:20},S0={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"})(Cs||(Cs={}));(function(e){e.Left="Left",e.Right="Right",e.Center="Center"})(la||(la={}));(function(e){e[e.Mobile=0]="Mobile",e[e.Tablet=1]="Tablet",e[e.Web=2]="Web"})(A0||(A0={}));cf=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"})(Es||(Es={}));Li=class{static StartTag="<"},Ue={ShowLabel:"true",LockLevel:"0",IsUserDefined:"0",LabelWidth:"115",columns:"1",ShowBar:"false",Layout:"varwidth",namePrefix:"_section_",labelAlignment:la.Left,labelPosition:Es.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"})(Y_||(Y_={}));(function(e){e.TabWithLockedFieldRemoval="TabWithLockedFieldRemoval",e.SectionWithLockedFieldRemoval="SectionWithLockedFieldRemoval",e.LockedSectionRemoval="LockedSectionRemoval",e.LockedFieldRemoval="LockedFieldRemoval",e.RequiredFieldRemoval="RequiredFieldRemoval",e.LastRemainingTab="LastRemainingTab",e.UnknownRemoval="UnknownRemoval"})(Q_||(Q_={}));(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"})(X_||(X_={}))});var N0,eT=L(()=>{"use strict";(function(e){e.DefaultValue="defaultValue",e.Loaded="loaded"})(N0||(N0={}))});var nT,m6,tT,Ace,Sce,yu,rT,Nce,_ce,iT=L(()=>{"use strict";nT=Ae(aa());st();ws();J_();os();Tn();Ho();ue();m6=Ae(Qi());eT();(function(e){e.Model="Model",e.Canvas="Canvas",e.CustomPages="CustomPages"})(tT||(tT={}));Ace={Read:io.Read,Edit:io.Edit,Both:io.Both,Container:io.Container},Sce={input:jo.Input,bound:jo.Bound,output:jo.Output};(function(e){e[e.dataset=0]="dataset",e[e.property=1]="property",e[e.groups=2]="groups",e[e.group=3]="group"})(yu||(yu={}));(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"})(rT||(rT={}));Nce=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]),_ce={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 Dn,df,oT=L(()=>{"use strict";Dn=Ae(aa());ht();st();Xt();ws();Ho();iT();os();ue();It();Tn();df=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(Ht.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===Ht.name)?.value}getParameterChildrenValues(t,r,n){if(this.isDataSet(t)){let i=r.find(u=>u.key===Ht.name)?.value,o={Name:i,Type:F.Grid,Columns:[]},l=this.getParameters().get(Ht.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(Li.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:qh.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===yu.dataset?o.get(Ht.dataset)?.some(m=>this.getDatasetName(m)===d)||r.push({Name:d,Value:{Name:d,Columns:[],Type:F.Grid}}):c.propertyType===yu.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,Dn.trackInfoTrace)(cr,{eventName:`${Ri}/parametersToJSON`,eventData:{message:`Configuration metadata for custom control parameter ${a} is not available for custom control : ${this.name}.`}}),r=[];break}}}else(0,Dn.trackErrorTrace)(cr,{eventName:`${Ri}/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,Dn.trackErrorTrace)(cr,{eventName:`${Ri}/parametersToJSON`,eventData:{message:"Custom Control Manifest not found"}},new Error(`No custom control manifest found for ${this.name}`))}catch(n){(0,Dn.trackErrorTrace)(cr,{eventName:`${Ri}/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===Ht.name)?.value;if(o)return this.getParameterChildrenValues(t,r);{let s=new Error(`No dataset manifest info for ${a}`);(0,Dn.trackErrorTrace)(cr,{eventName:`${Ri}/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=>!fd.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===Ti.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(Bh.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,Dn.trackErrorTrace)(cr,{eventName:`${Ri}/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,Dn.trackErrorTrace)(cr,{eventName:`${Ri}/parameterJSON`,eventData:{message:"Missing property type info"}},f)}else{let l=new Error(`No property manifest info for ${t}`);(0,Dn.trackWarningTrace)(cr,{eventName:`${Ri}/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 fd.includes(t)}isNumberTypeProperty(t,r){return pd.includes(r)||t.ofTypeGroup.some(n=>pd.includes(n))}isDataSet(t){return Ht.dataset===t}isGroups(t){return!!t[0].getAllProperties().find(n=>n.key==="isGroup"&&n.value==="true")}}});var ee,_0=L(()=>{"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 aT={};Jr(aT,{CustomControlUniqueId:()=>ua,DeprecatedControlClassIds:()=>G,FieldControlTypes:()=>lt,mapFieldTypeToControl:()=>h6});function h6(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,ua,lt,bu=L(()=>{"use strict";ht();Wl();st();Xt();os();oa();_0();Tn();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"}};ua=class{static get RelationshipAssistant(){return"3ff9a528-dd50-4aca-8f10-2e5ed73513ad"}static get PredictiveLeadScoring(){return"6f503f2a-d033-4106-b62c-f8f2e5f01a57"}},lt=class e{static FieldControlIds=e.initializeFieldControls();static UnboundControlIds=e.initializeUnboundControls();static ControlsAllowedForReferencePanel=e.initializeReferencePanelControls();static ControlsAllowedForFooter=e.initializeFooterControls();static CustomControlIdMap=new ar;static initializeFieldControls(){let t=new ar,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 k=e.getControlName($.MultipleLineofText,W.TextArea);t.add(k,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 Oe=e.getControlName($.TwoOptions,"Radio");t.add(Oe,new U(G.RadioControl));let Vt=e.getControlName($.TwoOptions,"CheckBox");t.add(Vt,new U(G.CheckBoxControl));let Xe=e.getControlName($.TwoOptions,"List");t.add(Xe,new U(G.PicklistControl));let Ne=e.getControlName($.State,W.None);t.add(Ne,new U(G.PicklistControl));let se=e.getControlName($.Status,W.None);t.add(se,new U(G.PicklistStatusControl));let We=e.getControlName($.OwnerType,W.None);t.add(We,new U(G.LookupControl));let ir=e.getControlName($.PartyListType,W.None);t.add(ir,new U(G.PartyListControl));let PU=e.getControlName($.LookupType,W.Regarding);t.add(PU,new U(G.RegardingControl));let RU=e.getControlName($.MultiSelectOptionSet,W.None);return t.add(RU,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 ar;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(ua.RelationshipAssistant,ee.CustomControl),t}static initializeReferencePanelControls(){let t=new ar;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 is;return t.add(Cs.IFRAME,!0),t.add(Cs.SPACER,!0),t.add(Cs.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(Ue.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===ua.RelationshipAssistant||t.guidString===ua.PredictiveLeadScoring)}static isRelationshipAssistantControl(t){return!R.IsNullOrUndefined(t)&&e.isRelationshipAssistant(t.UniqueId)}static isRelationshipAssistant(t){return!R.IsNullOrUndefined(t)&&t.guidString===ua.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 ff,sT=L(()=>{"use strict";ff=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,As,lT,uT,yo,cT,dT,T0=L(()=>{"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"})(As||(As={}));(function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle"})(lT||(lT={}));(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"})(uT||(uT={}));(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"})(yo||(yo={}));(function(e){e[e.None=0]="None",e[e.SystemRequired=1]="SystemRequired",e[e.ApplicationRequired=2]="ApplicationRequired",e[e.Recommended=3]="Recommended"})(cT||(cT={}));(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"})(dT||(dT={}))});var Ss,fT=L(()=>{"use strict";gu();Ss=p0({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 pT(e){return{...e,extractConfig:t=>g6(t,Object.keys(e.fallback))}}function g6(e,t){let r={};for(let n of t)typeof e[n]<"u"&&(r[n]=e[n]);return r}var D0=L(()=>{"use strict";});var I0=v((Zce,hT)=>{var vu=new Proxy(function(){return vu},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:vu},apply:function(){return vu},construct:function(){return{}}}),mT=function(){return vu};Object.setPrototypeOf(mT,vu);hT.exports=mT});var bT=v((ede,yT)=>{var wu=new Proxy(function(){return wu},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:wu},apply:function(){return wu},construct:function(){return{}}}),gT=function(){return wu};Object.setPrototypeOf(gT,wu);yT.exports=gT});var O0=v((tde,wT)=>{var Cu=new Proxy(function(){return Cu},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:Cu},apply:function(){return Cu},construct:function(){return{}}}),vT=function(){return Cu};Object.setPrototypeOf(vT,Cu);wT.exports=vT});var ET=v((rde,CT)=>{function y6(){this.__data__=[],this.size=0}CT.exports=y6});var Ns=v((nde,AT)=>{function b6(e,t){return e===t||e!==e&&t!==t}AT.exports=b6});var Eu=v((ide,ST)=>{var v6=Ns();function w6(e,t){for(var r=e.length;r--;)if(v6(e[r][0],t))return r;return-1}ST.exports=w6});var _T=v((ode,NT)=>{var C6=Eu(),E6=Array.prototype,A6=E6.splice;function S6(e){var t=this.__data__,r=C6(t,e);if(r<0)return!1;var n=t.length-1;return r==n?t.pop():A6.call(t,r,1),--this.size,!0}NT.exports=S6});var DT=v((ade,TT)=>{var N6=Eu();function _6(e){var t=this.__data__,r=N6(t,e);return r<0?void 0:t[r][1]}TT.exports=_6});var OT=v((sde,IT)=>{var T6=Eu();function D6(e){return T6(this.__data__,e)>-1}IT.exports=D6});var RT=v((lde,PT)=>{var I6=Eu();function O6(e,t){var r=this.__data__,n=I6(r,e);return n<0?(++this.size,r.push([e,t])):r[n][1]=t,this}PT.exports=O6});var Au=v((ude,kT)=>{var P6=ET(),R6=_T(),k6=DT(),L6=OT(),$6=RT();function _s(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])}}_s.prototype.clear=P6;_s.prototype.delete=R6;_s.prototype.get=k6;_s.prototype.has=L6;_s.prototype.set=$6;kT.exports=_s});var $T=v((cde,LT)=>{var x6=Au();function F6(){this.__data__=new x6,this.size=0}LT.exports=F6});var FT=v((dde,xT)=>{function M6(e){var t=this.__data__,r=t.delete(e);return this.size=t.size,r}xT.exports=M6});var UT=v((fde,MT)=>{function U6(e){return this.__data__.get(e)}MT.exports=U6});var qT=v((pde,BT)=>{function B6(e){return this.__data__.has(e)}BT.exports=B6});var P0=v((mde,VT)=>{var q6=typeof global=="object"&&global&&global.Object===Object&&global;VT.exports=q6});var In=v((hde,GT)=>{var V6=P0(),G6=typeof self=="object"&&self&&self.Object===Object&&self,W6=V6||G6||Function("return this")();GT.exports=W6});var Su=v((gde,WT)=>{var z6=In(),j6=z6.Symbol;WT.exports=j6});var KT=v((yde,HT)=>{var zT=Su(),jT=Object.prototype,H6=jT.hasOwnProperty,K6=jT.toString,Nu=zT?zT.toStringTag:void 0;function J6(e){var t=H6.call(e,Nu),r=e[Nu];try{e[Nu]=void 0;var n=!0}catch{}var i=K6.call(e);return n&&(t?e[Nu]=r:delete e[Nu]),i}HT.exports=J6});var YT=v((bde,JT)=>{var Y6=Object.prototype,Q6=Y6.toString;function X6(e){return Q6.call(e)}JT.exports=X6});var da=v((vde,ZT)=>{var QT=Su(),Z6=KT(),ez=YT(),tz="[object Null]",rz="[object Undefined]",XT=QT?QT.toStringTag:void 0;function nz(e){return e==null?e===void 0?rz:tz:XT&&XT in Object(e)?Z6(e):ez(e)}ZT.exports=nz});var $i=v((wde,eD)=>{function iz(e){var t=typeof e;return e!=null&&(t=="object"||t=="function")}eD.exports=iz});var pf=v((Cde,tD)=>{var oz=da(),az=$i(),sz="[object AsyncFunction]",lz="[object Function]",uz="[object GeneratorFunction]",cz="[object Proxy]";function dz(e){if(!az(e))return!1;var t=oz(e);return t==lz||t==uz||t==sz||t==cz}tD.exports=dz});var nD=v((Ede,rD)=>{var fz=In(),pz=fz["__core-js_shared__"];rD.exports=pz});var aD=v((Ade,oD)=>{var R0=nD(),iD=(function(){var e=/[^.]+$/.exec(R0&&R0.keys&&R0.keys.IE_PROTO||"");return e?"Symbol(src)_1."+e:""})();function mz(e){return!!iD&&iD in e}oD.exports=mz});var k0=v((Sde,sD)=>{var hz=Function.prototype,gz=hz.toString;function yz(e){if(e!=null){try{return gz.call(e)}catch{}try{return e+""}catch{}}return""}sD.exports=yz});var uD=v((Nde,lD)=>{var bz=pf(),vz=aD(),wz=$i(),Cz=k0(),Ez=/[\\^$.*+?()[\]{}|]/g,Az=/^\[object .+?Constructor\]$/,Sz=Function.prototype,Nz=Object.prototype,_z=Sz.toString,Tz=Nz.hasOwnProperty,Dz=RegExp("^"+_z.call(Tz).replace(Ez,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function Iz(e){if(!wz(e)||vz(e))return!1;var t=bz(e)?Dz:Az;return t.test(Cz(e))}lD.exports=Iz});var dD=v((_de,cD)=>{function Oz(e,t){return e?.[t]}cD.exports=Oz});var bo=v((Tde,fD)=>{var Pz=uD(),Rz=dD();function kz(e,t){var r=Rz(e,t);return Pz(r)?r:void 0}fD.exports=kz});var mf=v((Dde,pD)=>{var Lz=bo(),$z=In(),xz=Lz($z,"Map");pD.exports=xz});var _u=v((Ide,mD)=>{var Fz=bo(),Mz=Fz(Object,"create");mD.exports=Mz});var yD=v((Ode,gD)=>{var hD=_u();function Uz(){this.__data__=hD?hD(null):{},this.size=0}gD.exports=Uz});var vD=v((Pde,bD)=>{function Bz(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t}bD.exports=Bz});var CD=v((Rde,wD)=>{var qz=_u(),Vz="__lodash_hash_undefined__",Gz=Object.prototype,Wz=Gz.hasOwnProperty;function zz(e){var t=this.__data__;if(qz){var r=t[e];return r===Vz?void 0:r}return Wz.call(t,e)?t[e]:void 0}wD.exports=zz});var AD=v((kde,ED)=>{var jz=_u(),Hz=Object.prototype,Kz=Hz.hasOwnProperty;function Jz(e){var t=this.__data__;return jz?t[e]!==void 0:Kz.call(t,e)}ED.exports=Jz});var ND=v((Lde,SD)=>{var Yz=_u(),Qz="__lodash_hash_undefined__";function Xz(e,t){var r=this.__data__;return this.size+=this.has(e)?0:1,r[e]=Yz&&t===void 0?Qz:t,this}SD.exports=Xz});var TD=v(($de,_D)=>{var Zz=yD(),ej=vD(),tj=CD(),rj=AD(),nj=ND();function Ts(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])}}Ts.prototype.clear=Zz;Ts.prototype.delete=ej;Ts.prototype.get=tj;Ts.prototype.has=rj;Ts.prototype.set=nj;_D.exports=Ts});var OD=v((xde,ID)=>{var DD=TD(),ij=Au(),oj=mf();function aj(){this.size=0,this.__data__={hash:new DD,map:new(oj||ij),string:new DD}}ID.exports=aj});var RD=v((Fde,PD)=>{function sj(e){var t=typeof e;return t=="string"||t=="number"||t=="symbol"||t=="boolean"?e!=="__proto__":e===null}PD.exports=sj});var Tu=v((Mde,kD)=>{var lj=RD();function uj(e,t){var r=e.__data__;return lj(t)?r[typeof t=="string"?"string":"hash"]:r.map}kD.exports=uj});var $D=v((Ude,LD)=>{var cj=Tu();function dj(e){var t=cj(this,e).delete(e);return this.size-=t?1:0,t}LD.exports=dj});var FD=v((Bde,xD)=>{var fj=Tu();function pj(e){return fj(this,e).get(e)}xD.exports=pj});var UD=v((qde,MD)=>{var mj=Tu();function hj(e){return mj(this,e).has(e)}MD.exports=hj});var qD=v((Vde,BD)=>{var gj=Tu();function yj(e,t){var r=gj(this,e),n=r.size;return r.set(e,t),this.size+=r.size==n?0:1,this}BD.exports=yj});var hf=v((Gde,VD)=>{var bj=OD(),vj=$D(),wj=FD(),Cj=UD(),Ej=qD();function Ds(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])}}Ds.prototype.clear=bj;Ds.prototype.delete=vj;Ds.prototype.get=wj;Ds.prototype.has=Cj;Ds.prototype.set=Ej;VD.exports=Ds});var WD=v((Wde,GD)=>{var Aj=Au(),Sj=mf(),Nj=hf(),_j=200;function Tj(e,t){var r=this.__data__;if(r instanceof Aj){var n=r.__data__;if(!Sj||n.length<_j-1)return n.push([e,t]),this.size=++r.size,this;r=this.__data__=new Nj(n)}return r.set(e,t),this.size=r.size,this}GD.exports=Tj});var L0=v((zde,zD)=>{var Dj=Au(),Ij=$T(),Oj=FT(),Pj=UT(),Rj=qT(),kj=WD();function Is(e){var t=this.__data__=new Dj(e);this.size=t.size}Is.prototype.clear=Ij;Is.prototype.delete=Oj;Is.prototype.get=Pj;Is.prototype.has=Rj;Is.prototype.set=kj;zD.exports=Is});var HD=v((jde,jD)=>{var Lj="__lodash_hash_undefined__";function $j(e){return this.__data__.set(e,Lj),this}jD.exports=$j});var JD=v((Hde,KD)=>{function xj(e){return this.__data__.has(e)}KD.exports=xj});var QD=v((Kde,YD)=>{var Fj=hf(),Mj=HD(),Uj=JD();function gf(e){var t=-1,r=e==null?0:e.length;for(this.__data__=new Fj;++t<r;)this.add(e[t])}gf.prototype.add=gf.prototype.push=Mj;gf.prototype.has=Uj;YD.exports=gf});var ZD=v((Jde,XD)=>{function Bj(e,t){for(var r=-1,n=e==null?0:e.length;++r<n;)if(t(e[r],r,e))return!0;return!1}XD.exports=Bj});var tI=v((Yde,eI)=>{function qj(e,t){return e.has(t)}eI.exports=qj});var $0=v((Qde,rI)=>{var Vj=QD(),Gj=ZD(),Wj=tI(),zj=1,jj=2;function Hj(e,t,r,n,i,o){var a=r&zj,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&jj?new Vj: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(!Gj(t,function(b,w){if(!Wj(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}rI.exports=Hj});var x0=v((Xde,nI)=>{var Kj=In(),Jj=Kj.Uint8Array;nI.exports=Jj});var oI=v((Zde,iI)=>{function Yj(e){var t=-1,r=Array(e.size);return e.forEach(function(n,i){r[++t]=[i,n]}),r}iI.exports=Yj});var sI=v((efe,aI)=>{function Qj(e){var t=-1,r=Array(e.size);return e.forEach(function(n){r[++t]=n}),r}aI.exports=Qj});var fI=v((tfe,dI)=>{var lI=Su(),uI=x0(),Xj=Ns(),Zj=$0(),e7=oI(),t7=sI(),r7=1,n7=2,i7="[object Boolean]",o7="[object Date]",a7="[object Error]",s7="[object Map]",l7="[object Number]",u7="[object RegExp]",c7="[object Set]",d7="[object String]",f7="[object Symbol]",p7="[object ArrayBuffer]",m7="[object DataView]",cI=lI?lI.prototype:void 0,F0=cI?cI.valueOf:void 0;function h7(e,t,r,n,i,o,a){switch(r){case m7:if(e.byteLength!=t.byteLength||e.byteOffset!=t.byteOffset)return!1;e=e.buffer,t=t.buffer;case p7:return!(e.byteLength!=t.byteLength||!o(new uI(e),new uI(t)));case i7:case o7:case l7:return Xj(+e,+t);case a7:return e.name==t.name&&e.message==t.message;case u7:case d7:return e==t+"";case s7:var s=e7;case c7:var l=n&r7;if(s||(s=t7),e.size!=t.size&&!l)return!1;var u=a.get(e);if(u)return u==t;n|=n7,a.set(e,t);var c=Zj(s(e),s(t),n,i,o,a);return a.delete(e),c;case f7:if(F0)return F0.call(e)==F0.call(t)}return!1}dI.exports=h7});var mI=v((rfe,pI)=>{function g7(e,t){for(var r=-1,n=t.length,i=e.length;++r<n;)e[i+r]=t[r];return e}pI.exports=g7});var vo=v((nfe,hI)=>{var y7=Array.isArray;hI.exports=y7});var yI=v((ife,gI)=>{var b7=mI(),v7=vo();function w7(e,t,r){var n=t(e);return v7(e)?n:b7(n,r(e))}gI.exports=w7});var vI=v((ofe,bI)=>{function C7(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}bI.exports=C7});var CI=v((afe,wI)=>{function E7(){return[]}wI.exports=E7});var SI=v((sfe,AI)=>{var A7=vI(),S7=CI(),N7=Object.prototype,_7=N7.propertyIsEnumerable,EI=Object.getOwnPropertySymbols,T7=EI?function(e){return e==null?[]:(e=Object(e),A7(EI(e),function(t){return _7.call(e,t)}))}:S7;AI.exports=T7});var _I=v((lfe,NI)=>{function D7(e,t){for(var r=-1,n=Array(e);++r<e;)n[r]=t(r);return n}NI.exports=D7});var wo=v((ufe,TI)=>{function I7(e){return e!=null&&typeof e=="object"}TI.exports=I7});var II=v((cfe,DI)=>{var O7=da(),P7=wo(),R7="[object Arguments]";function k7(e){return P7(e)&&O7(e)==R7}DI.exports=k7});var M0=v((dfe,RI)=>{var OI=II(),L7=wo(),PI=Object.prototype,$7=PI.hasOwnProperty,x7=PI.propertyIsEnumerable,F7=OI((function(){return arguments})())?OI:function(e){return L7(e)&&$7.call(e,"callee")&&!x7.call(e,"callee")};RI.exports=F7});var LI=v((ffe,kI)=>{function M7(){return!1}kI.exports=M7});var yf=v((Du,Os)=>{var U7=In(),B7=LI(),FI=typeof Du=="object"&&Du&&!Du.nodeType&&Du,$I=FI&&typeof Os=="object"&&Os&&!Os.nodeType&&Os,q7=$I&&$I.exports===FI,xI=q7?U7.Buffer:void 0,V7=xI?xI.isBuffer:void 0,G7=V7||B7;Os.exports=G7});var bf=v((pfe,MI)=>{var W7=9007199254740991,z7=/^(?:0|[1-9]\d*)$/;function j7(e,t){var r=typeof e;return t=t??W7,!!t&&(r=="number"||r!="symbol"&&z7.test(e))&&e>-1&&e%1==0&&e<t}MI.exports=j7});var U0=v((mfe,UI)=>{var H7=9007199254740991;function K7(e){return typeof e=="number"&&e>-1&&e%1==0&&e<=H7}UI.exports=K7});var qI=v((hfe,BI)=>{var J7=da(),Y7=U0(),Q7=wo(),X7="[object Arguments]",Z7="[object Array]",eH="[object Boolean]",tH="[object Date]",rH="[object Error]",nH="[object Function]",iH="[object Map]",oH="[object Number]",aH="[object Object]",sH="[object RegExp]",lH="[object Set]",uH="[object String]",cH="[object WeakMap]",dH="[object ArrayBuffer]",fH="[object DataView]",pH="[object Float32Array]",mH="[object Float64Array]",hH="[object Int8Array]",gH="[object Int16Array]",yH="[object Int32Array]",bH="[object Uint8Array]",vH="[object Uint8ClampedArray]",wH="[object Uint16Array]",CH="[object Uint32Array]",$e={};$e[pH]=$e[mH]=$e[hH]=$e[gH]=$e[yH]=$e[bH]=$e[vH]=$e[wH]=$e[CH]=!0;$e[X7]=$e[Z7]=$e[dH]=$e[eH]=$e[fH]=$e[tH]=$e[rH]=$e[nH]=$e[iH]=$e[oH]=$e[aH]=$e[sH]=$e[lH]=$e[uH]=$e[cH]=!1;function EH(e){return Q7(e)&&Y7(e.length)&&!!$e[J7(e)]}BI.exports=EH});var GI=v((gfe,VI)=>{function AH(e){return function(t){return e(t)}}VI.exports=AH});var zI=v((Iu,Ps)=>{var SH=P0(),WI=typeof Iu=="object"&&Iu&&!Iu.nodeType&&Iu,Ou=WI&&typeof Ps=="object"&&Ps&&!Ps.nodeType&&Ps,NH=Ou&&Ou.exports===WI,B0=NH&&SH.process,_H=(function(){try{var e=Ou&&Ou.require&&Ou.require("util").types;return e||B0&&B0.binding&&B0.binding("util")}catch{}})();Ps.exports=_H});var vf=v((yfe,KI)=>{var TH=qI(),DH=GI(),jI=zI(),HI=jI&&jI.isTypedArray,IH=HI?DH(HI):TH;KI.exports=IH});var q0=v((bfe,JI)=>{var OH=_I(),PH=M0(),RH=vo(),kH=yf(),LH=bf(),$H=vf(),xH=Object.prototype,FH=xH.hasOwnProperty;function MH(e,t){var r=RH(e),n=!r&&PH(e),i=!r&&!n&&kH(e),o=!r&&!n&&!i&&$H(e),a=r||n||i||o,s=a?OH(e.length,String):[],l=s.length;for(var u in e)(t||FH.call(e,u))&&!(a&&(u=="length"||i&&(u=="offset"||u=="parent")||o&&(u=="buffer"||u=="byteLength"||u=="byteOffset")||LH(u,l)))&&s.push(u);return s}JI.exports=MH});var wf=v((vfe,YI)=>{var UH=Object.prototype;function BH(e){var t=e&&e.constructor,r=typeof t=="function"&&t.prototype||UH;return e===r}YI.exports=BH});var V0=v((wfe,QI)=>{function qH(e,t){return function(r){return e(t(r))}}QI.exports=qH});var ZI=v((Cfe,XI)=>{var VH=V0(),GH=VH(Object.keys,Object);XI.exports=GH});var tO=v((Efe,eO)=>{var WH=wf(),zH=ZI(),jH=Object.prototype,HH=jH.hasOwnProperty;function KH(e){if(!WH(e))return zH(e);var t=[];for(var r in Object(e))HH.call(e,r)&&r!="constructor"&&t.push(r);return t}eO.exports=KH});var Pu=v((Afe,rO)=>{var JH=pf(),YH=U0();function QH(e){return e!=null&&YH(e.length)&&!JH(e)}rO.exports=QH});var iO=v((Sfe,nO)=>{var XH=q0(),ZH=tO(),eK=Pu();function tK(e){return eK(e)?XH(e):ZH(e)}nO.exports=tK});var aO=v((Nfe,oO)=>{var rK=yI(),nK=SI(),iK=iO();function oK(e){return rK(e,iK,nK)}oO.exports=oK});var uO=v((_fe,lO)=>{var sO=aO(),aK=1,sK=Object.prototype,lK=sK.hasOwnProperty;function uK(e,t,r,n,i,o){var a=r&aK,s=sO(e),l=s.length,u=sO(t),c=u.length;if(l!=c&&!a)return!1;for(var d=l;d--;){var f=s[d];if(!(a?f in t:lK.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}lO.exports=uK});var dO=v((Tfe,cO)=>{var cK=bo(),dK=In(),fK=cK(dK,"DataView");cO.exports=fK});var pO=v((Dfe,fO)=>{var pK=bo(),mK=In(),hK=pK(mK,"Promise");fO.exports=hK});var hO=v((Ife,mO)=>{var gK=bo(),yK=In(),bK=gK(yK,"Set");mO.exports=bK});var yO=v((Ofe,gO)=>{var vK=bo(),wK=In(),CK=vK(wK,"WeakMap");gO.exports=CK});var NO=v((Pfe,SO)=>{var G0=dO(),W0=mf(),z0=pO(),j0=hO(),H0=yO(),AO=da(),Rs=k0(),bO="[object Map]",EK="[object Object]",vO="[object Promise]",wO="[object Set]",CO="[object WeakMap]",EO="[object DataView]",AK=Rs(G0),SK=Rs(W0),NK=Rs(z0),_K=Rs(j0),TK=Rs(H0),fa=AO;(G0&&fa(new G0(new ArrayBuffer(1)))!=EO||W0&&fa(new W0)!=bO||z0&&fa(z0.resolve())!=vO||j0&&fa(new j0)!=wO||H0&&fa(new H0)!=CO)&&(fa=function(e){var t=AO(e),r=t==EK?e.constructor:void 0,n=r?Rs(r):"";if(n)switch(n){case AK:return EO;case SK:return bO;case NK:return vO;case _K:return wO;case TK:return CO}return t});SO.exports=fa});var kO=v((Rfe,RO)=>{var K0=L0(),DK=$0(),IK=fI(),OK=uO(),_O=NO(),TO=vo(),DO=yf(),PK=vf(),RK=1,IO="[object Arguments]",OO="[object Array]",Cf="[object Object]",kK=Object.prototype,PO=kK.hasOwnProperty;function LK(e,t,r,n,i,o){var a=TO(e),s=TO(t),l=a?OO:_O(e),u=s?OO:_O(t);l=l==IO?Cf:l,u=u==IO?Cf:u;var c=l==Cf,d=u==Cf,f=l==u;if(f&&DO(e)){if(!DO(t))return!1;a=!0,c=!1}if(f&&!c)return o||(o=new K0),a||PK(e)?DK(e,t,r,n,i,o):IK(e,t,l,r,n,i,o);if(!(r&RK)){var m=c&&PO.call(e,"__wrapped__"),p=d&&PO.call(t,"__wrapped__");if(m||p){var h=m?e.value():e,g=p?t.value():t;return o||(o=new K0),i(h,g,r,n,o)}}return f?(o||(o=new K0),OK(e,t,r,n,i,o)):!1}RO.exports=LK});var FO=v((kfe,xO)=>{var $K=kO(),LO=wo();function $O(e,t,r,n,i){return e===t?!0:e==null||t==null||!LO(e)&&!LO(t)?e!==e&&t!==t:$K(e,t,r,n,$O,i)}xO.exports=$O});var UO=v((Lfe,MO)=>{var xK=FO();function FK(e,t){return xK(e,t)}MO.exports=FK});var J0=v(($fe,BO)=>{var MK=bo(),UK=(function(){try{var e=MK(Object,"defineProperty");return e({},"",{}),e}catch{}})();BO.exports=UK});var Ef=v((xfe,VO)=>{var qO=J0();function BK(e,t,r){t=="__proto__"&&qO?qO(e,t,{configurable:!0,enumerable:!0,value:r,writable:!0}):e[t]=r}VO.exports=BK});var Y0=v((Ffe,GO)=>{var qK=Ef(),VK=Ns();function GK(e,t,r){(r!==void 0&&!VK(e[t],r)||r===void 0&&!(t in e))&&qK(e,t,r)}GO.exports=GK});var zO=v((Mfe,WO)=>{function WK(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}}WO.exports=WK});var HO=v((Ufe,jO)=>{var zK=zO(),jK=zK();jO.exports=jK});var XO=v((Ru,ks)=>{var HK=In(),QO=typeof Ru=="object"&&Ru&&!Ru.nodeType&&Ru,KO=QO&&typeof ks=="object"&&ks&&!ks.nodeType&&ks,KK=KO&&KO.exports===QO,JO=KK?HK.Buffer:void 0,YO=JO?JO.allocUnsafe:void 0;function JK(e,t){if(t)return e.slice();var r=e.length,n=YO?YO(r):new e.constructor(r);return e.copy(n),n}ks.exports=JK});var tP=v((Bfe,eP)=>{var ZO=x0();function YK(e){var t=new e.constructor(e.byteLength);return new ZO(t).set(new ZO(e)),t}eP.exports=YK});var nP=v((qfe,rP)=>{var QK=tP();function XK(e,t){var r=t?QK(e.buffer):e.buffer;return new e.constructor(r,e.byteOffset,e.length)}rP.exports=XK});var oP=v((Vfe,iP)=>{function ZK(e,t){var r=-1,n=e.length;for(t||(t=Array(n));++r<n;)t[r]=e[r];return t}iP.exports=ZK});var lP=v((Gfe,sP)=>{var eJ=$i(),aP=Object.create,tJ=(function(){function e(){}return function(t){if(!eJ(t))return{};if(aP)return aP(t);e.prototype=t;var r=new e;return e.prototype=void 0,r}})();sP.exports=tJ});var Q0=v((Wfe,uP)=>{var rJ=V0(),nJ=rJ(Object.getPrototypeOf,Object);uP.exports=nJ});var dP=v((zfe,cP)=>{var iJ=lP(),oJ=Q0(),aJ=wf();function sJ(e){return typeof e.constructor=="function"&&!aJ(e)?iJ(oJ(e)):{}}cP.exports=sJ});var pP=v((jfe,fP)=>{var lJ=Pu(),uJ=wo();function cJ(e){return uJ(e)&&lJ(e)}fP.exports=cJ});var gP=v((Hfe,hP)=>{var dJ=da(),fJ=Q0(),pJ=wo(),mJ="[object Object]",hJ=Function.prototype,gJ=Object.prototype,mP=hJ.toString,yJ=gJ.hasOwnProperty,bJ=mP.call(Object);function vJ(e){if(!pJ(e)||dJ(e)!=mJ)return!1;var t=fJ(e);if(t===null)return!0;var r=yJ.call(t,"constructor")&&t.constructor;return typeof r=="function"&&r instanceof r&&mP.call(r)==bJ}hP.exports=vJ});var X0=v((Kfe,yP)=>{function wJ(e,t){if(!(t==="constructor"&&typeof e[t]=="function")&&t!="__proto__")return e[t]}yP.exports=wJ});var Z0=v((Jfe,bP)=>{var CJ=Ef(),EJ=Ns(),AJ=Object.prototype,SJ=AJ.hasOwnProperty;function NJ(e,t,r){var n=e[t];(!(SJ.call(e,t)&&EJ(n,r))||r===void 0&&!(t in e))&&CJ(e,t,r)}bP.exports=NJ});var wP=v((Yfe,vP)=>{var _J=Z0(),TJ=Ef();function DJ(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?TJ(r,s,l):_J(r,s,l)}return r}vP.exports=DJ});var EP=v((Qfe,CP)=>{function IJ(e){var t=[];if(e!=null)for(var r in Object(e))t.push(r);return t}CP.exports=IJ});var SP=v((Xfe,AP)=>{var OJ=$i(),PJ=wf(),RJ=EP(),kJ=Object.prototype,LJ=kJ.hasOwnProperty;function $J(e){if(!OJ(e))return RJ(e);var t=PJ(e),r=[];for(var n in e)n=="constructor"&&(t||!LJ.call(e,n))||r.push(n);return r}AP.exports=$J});var ey=v((Zfe,NP)=>{var xJ=q0(),FJ=SP(),MJ=Pu();function UJ(e){return MJ(e)?xJ(e,!0):FJ(e)}NP.exports=UJ});var TP=v((epe,_P)=>{var BJ=wP(),qJ=ey();function VJ(e){return BJ(e,qJ(e))}_P.exports=VJ});var kP=v((tpe,RP)=>{var DP=Y0(),GJ=XO(),WJ=nP(),zJ=oP(),jJ=dP(),IP=M0(),OP=vo(),HJ=pP(),KJ=yf(),JJ=pf(),YJ=$i(),QJ=gP(),XJ=vf(),PP=X0(),ZJ=TP();function eY(e,t,r,n,i,o,a){var s=PP(e,r),l=PP(t,r),u=a.get(l);if(u){DP(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),m=!f&&KJ(l),p=!f&&!m&&XJ(l);c=l,f||m||p?OP(s)?c=s:HJ(s)?c=zJ(s):m?(d=!1,c=GJ(l,!0)):p?(d=!1,c=WJ(l,!0)):c=[]:QJ(l)||IP(l)?(c=s,IP(s)?c=ZJ(s):(!YJ(s)||JJ(s))&&(c=jJ(l))):d=!1}d&&(a.set(l,c),i(c,l,n,o,a),a.delete(l)),DP(e,r,c)}RP.exports=eY});var ty=v((rpe,$P)=>{var tY=L0(),rY=Y0(),nY=HO(),iY=kP(),oY=$i(),aY=ey(),sY=X0();function LP(e,t,r,n,i){e!==t&&nY(t,function(o,a){if(i||(i=new tY),oY(o))iY(e,t,a,r,LP,n,i);else{var s=n?n(sY(e,a),o,a+"",e,t,i):void 0;s===void 0&&(s=o),rY(e,a,s)}},aY)}$P.exports=LP});var ry=v((npe,xP)=>{function lY(e){return e}xP.exports=lY});var MP=v((ipe,FP)=>{function uY(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=uY});var qP=v((ope,BP)=>{var cY=MP(),UP=Math.max;function dY(e,t,r){return t=UP(t===void 0?e.length-1:t,0),function(){for(var n=arguments,i=-1,o=UP(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),cY(e,this,s)}}BP.exports=dY});var GP=v((ape,VP)=>{function fY(e){return function(){return e}}VP.exports=fY});var jP=v((spe,zP)=>{var pY=GP(),WP=J0(),mY=ry(),hY=WP?function(e,t){return WP(e,"toString",{configurable:!0,enumerable:!1,value:pY(t),writable:!0})}:mY;zP.exports=hY});var KP=v((lpe,HP)=>{var gY=800,yY=16,bY=Date.now;function vY(e){var t=0,r=0;return function(){var n=bY(),i=yY-(n-r);if(r=n,i>0){if(++t>=gY)return arguments[0]}else t=0;return e.apply(void 0,arguments)}}HP.exports=vY});var YP=v((upe,JP)=>{var wY=jP(),CY=KP(),EY=CY(wY);JP.exports=EY});var XP=v((cpe,QP)=>{var AY=ry(),SY=qP(),NY=YP();function _Y(e,t){return NY(SY(e,t,AY),e+"")}QP.exports=_Y});var eR=v((dpe,ZP)=>{var TY=Ns(),DY=Pu(),IY=bf(),OY=$i();function PY(e,t,r){if(!OY(r))return!1;var n=typeof t;return(n=="number"?DY(r)&&IY(t,r.length):n=="string"&&t in r)?TY(r[t],e):!1}ZP.exports=PY});var ny=v((fpe,tR)=>{var RY=XP(),kY=eR();function LY(e){return RY(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&&kY(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})}tR.exports=LY});var nR=v((ppe,rR)=>{var $Y=ty(),xY=ny(),FY=xY(function(e,t,r,n){$Y(e,t,r,n)});rR.exports=FY});var un,ku=L(()=>{"use strict";(function(e){e[e.NotLoaded=0]="NotLoaded",e[e.Initialized=1]="Initialized",e[e.ConfigsLoaded=2]="ConfigsLoaded",e[e.Error=3]="Error"})(un||(un={}))});function oR(e,t,r="PROD"){let n=i=>`ShellSettings_ECS_ClientCache_${e}_${iR.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 iR,MY,aR=L(()=>{"use strict";iR=Ae(O0()),MY=Ae(I0());});var iy,sR=L(()=>{"use strict";of();iy=hu({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 uR,cR,dR,fR,oy,UY,Af,lR,ay=L(()=>{"use strict";uR=Ae(I0()),cR=Ae(bT()),dR=Ae(O0()),fR=Ae(UO()),oy=Ae(nR());ku();aR();sR();UY=60*1e3,Af=class{clientName;logger;ecsEndpoint;resolveLoadingPromise;loadingPromise=new Promise(t=>this.resolveLoadingPromise=t);_status=un.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"?iy.prodEcsEndpoint:iy.integrationEcsEndpoint}client=new cR.default;init=async({clientVersion:t,getFilters:r,cacheStorage:n=uR.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:[dR.EcsConfigType.Default],hosts:[this.ecsEndpoint],initialAppActiveState:!0,getEcsParameters:a,databaseInterface:oR(this.clientName,n,this.endpointType),...o}),this.client.requestUpdate(),this._status===un.NotLoaded&&(this._status=un.Initialized)}catch(s){this._status=un.Error,this.resolveLoadingPromise(),this.logEvent("FeaturesClient/initializationFailed",{ecsClientName:this.clientName,error:s},"Error")}i&&window.setInterval(()=>this.client.requestUpdate(),i*UY)};getConfig=t=>{let r=this.getMergedClientConfigByTeamName(t.teamName),n=r?t.extractConfig(r):{};return(0,oy.default)({},t.fallback,n,t.override,lR)};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,fR.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,oy.default)({},this.client.getConfig()?.config,this.clientConfigOverride,lR);getMergedClientConfigByTeamName=t=>this.getMergedClientConfig()?.[t];handleConfigUpdated=()=>{let t=this.client.getConfig();if(t===void 0)return;this.resolveLoadingPromise(),this._status=un.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})}},lR=(e,t)=>{if(Array.isArray(t))return t}});var mR=v((Epe,pR)=>{"use strict";var BY=()=>{let e={};return e.promise=new Promise((t,r)=>{e.resolve=t,e.reject=r}),e};pR.exports=BY});var sy=v((Ape,gR)=>{var Lu=new Proxy(function(){return Lu},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:Lu},apply:function(){return Lu},construct:function(){return{}}}),hR=function(){return Lu};Object.setPrototypeOf(hR,Lu);gR.exports=hR});var vR=v((Spe,bR)=>{var $u=new Proxy(function(){return $u},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:$u},apply:function(){return $u},construct:function(){return{}}}),yR=function(){return $u};Object.setPrototypeOf(yR,$u);bR.exports=yR});var _R=v((Npe,NR)=>{"use strict";var ly=vR(),qY={childContextTypes:!0,contextType:!0,contextTypes:!0,defaultProps:!0,displayName:!0,getDefaultProps:!0,getDerivedStateFromError:!0,getDerivedStateFromProps:!0,mixins:!0,propTypes:!0,type:!0},VY={name:!0,length:!0,prototype:!0,caller:!0,callee:!0,arguments:!0,arity:!0},GY={$$typeof:!0,render:!0,defaultProps:!0,displayName:!0,propTypes:!0},AR={$$typeof:!0,compare:!0,defaultProps:!0,displayName:!0,propTypes:!0,type:!0},uy={};uy[ly.ForwardRef]=GY;uy[ly.Memo]=AR;function wR(e){return ly.isMemo(e)?AR:uy[e.$$typeof]||qY}var WY=Object.defineProperty,zY=Object.getOwnPropertyNames,CR=Object.getOwnPropertySymbols,jY=Object.getOwnPropertyDescriptor,HY=Object.getPrototypeOf,ER=Object.prototype;function SR(e,t,r){if(typeof t!="string"){if(ER){var n=HY(t);n&&n!==ER&&SR(e,n,r)}var i=zY(t);CR&&(i=i.concat(CR(t)));for(var o=wR(e),a=wR(t),s=0;s<i.length;++s){var l=i[s];if(!VY[l]&&!(r&&r[l])&&!(a&&a[l])&&!(o&&o[l])){var u=jY(t,l);try{WY(e,l,u)}catch{}}}}return e}NR.exports=SR});function DR(e,t,r){let[n,i]=(0,Ls.useState)(e.getConfig(t));return(0,Ls.useEffect)(()=>{if(!r?.subscribe&&e.status===un.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 DR(e,t,r)}}function OR(e,t,r,n){let i=o=>{let a=DR(e,t,n),s={...o,...a};return Ls.default.createElement(r,{...s})};return(0,TR.default)(i,r),i.displayName=`WithFeature(${r.name})`,i}function PR(e,t,r,n){return t.reduce((i,o)=>OR(e,o,i,n),r)}function RR(e){return function(t,r,n){return OR(e,t,r,n)}}var TR,Ls,cy=L(()=>{"use strict";TR=Ae(_R()),Ls=Ae(sy());ku();});var LR=v((Dpe,kR)=>{var KY=ty(),JY=ny(),YY=JY(function(e,t,r){KY(e,t,r)});kR.exports=YY});var Sf=v((Ipe,$R)=>{var QY=da(),XY=wo(),ZY="[object Symbol]";function eQ(e){return typeof e=="symbol"||XY(e)&&QY(e)==ZY}$R.exports=eQ});var FR=v((Ope,xR)=>{var tQ=vo(),rQ=Sf(),nQ=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,iQ=/^\w*$/;function oQ(e,t){if(tQ(e))return!1;var r=typeof e;return r=="number"||r=="symbol"||r=="boolean"||e==null||rQ(e)?!0:iQ.test(e)||!nQ.test(e)||t!=null&&e in Object(t)}xR.exports=oQ});var BR=v((Ppe,UR)=>{var MR=hf(),aQ="Expected a function";function dy(e,t){if(typeof e!="function"||t!=null&&typeof t!="function")throw new TypeError(aQ);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(dy.Cache||MR),r}dy.Cache=MR;UR.exports=dy});var VR=v((Rpe,qR)=>{var sQ=BR(),lQ=500;function uQ(e){var t=sQ(e,function(n){return r.size===lQ&&r.clear(),n}),r=t.cache;return t}qR.exports=uQ});var WR=v((kpe,GR)=>{var cQ=VR(),dQ=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,fQ=/\\(\\)?/g,pQ=cQ(function(e){var t=[];return e.charCodeAt(0)===46&&t.push(""),e.replace(dQ,function(r,n,i,o){t.push(i?o.replace(fQ,"$1"):n||r)}),t});GR.exports=pQ});var jR=v((Lpe,zR)=>{function mQ(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}zR.exports=mQ});var XR=v(($pe,QR)=>{var HR=Su(),hQ=jR(),gQ=vo(),yQ=Sf(),bQ=1/0,KR=HR?HR.prototype:void 0,JR=KR?KR.toString:void 0;function YR(e){if(typeof e=="string")return e;if(gQ(e))return hQ(e,YR)+"";if(yQ(e))return JR?JR.call(e):"";var t=e+"";return t=="0"&&1/e==-bQ?"-0":t}QR.exports=YR});var e2=v((xpe,ZR)=>{var vQ=XR();function wQ(e){return e==null?"":vQ(e)}ZR.exports=wQ});var r2=v((Fpe,t2)=>{var CQ=vo(),EQ=FR(),AQ=WR(),SQ=e2();function NQ(e,t){return CQ(e)?e:EQ(e,t)?[e]:AQ(SQ(e))}t2.exports=NQ});var i2=v((Mpe,n2)=>{var _Q=Sf(),TQ=1/0;function DQ(e){if(typeof e=="string"||_Q(e))return e;var t=e+"";return t=="0"&&1/e==-TQ?"-0":t}n2.exports=DQ});var s2=v((Upe,a2)=>{var IQ=Z0(),OQ=r2(),PQ=bf(),o2=$i(),RQ=i2();function kQ(e,t,r,n){if(!o2(e))return e;t=OQ(t,e);for(var i=-1,o=t.length,a=o-1,s=e;s!=null&&++i<o;){var l=RQ(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=o2(c)?c:PQ(t[i+1])?[]:{})}IQ(s,l,u),s=s[l]}return e}a2.exports=kQ});var u2=v((Bpe,l2)=>{var LQ=s2();function $Q(e,t,r){return e==null?e:LQ(e,t,r)}l2.exports=$Q});function p2(e){let{query:t}=(0,f2.default)(window.location.href,!0);return FQ(e,t),e}function FQ(e,t){let r=xQ+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+m2,u={};if(o===r)u=s;else if(o.startsWith(l)){let c=o.substring(l.length);(0,d2.default)(u,c,s)}(0,c2.default)(i,u)}catch{}}),Object.keys(i).length>0&&e.overrideClientConfig(i)}var c2,d2,f2,m2,xQ,h2=L(()=>{"use strict";c2=Ae(LR()),d2=Ae(u2()),f2=Ae(y0());m2=".",xQ="ecs"+m2});function _f(e,t,r){let n=p2(new Af(e,t,r));function i(o){(0,Nf.useEffect)(()=>{n.init(o)},[])}return{featuresClient:n,createFeature:UQ(n),useFeaturesClientInitParams:i,withFeatures:(o,a,s)=>PR(n,o,a,s)}}function UQ(e){let t=IR(e),r=RR(e);return function(i){let o=pT(i);return o.getConfig=()=>e.getConfig(o),o.isLoaded=()=>e.status===un.ConfigsLoaded,w0.register(o,e.clientName),{useFeature:a=>t(o,a),withFeature:(a,s)=>r(o,a,s),feature:o}}}var MQ,Nf,fy=L(()=>{"use strict";MQ=Ae(mR()),Nf=Ae(sy());D0();ay();ku();cy();h2();C0();});var g2=L(()=>{"use strict";D0();ay();fy();ku();cy();uf();E0();});function Tf(e){return{logEvent:(t,r,n)=>{switch(n){case"Error":(0,$s.trackErrorTrace)(e,{eventName:t,eventData:r});break;case"Warning":(0,$s.trackWarningTrace)(e,{eventName:t,eventData:r});break;default:(0,$s.trackInfoTrace)(e,{eventName:t,eventData:r});break}}}}var $s,py=L(()=>{"use strict";$s=Ae(aa());});var ame,sme,lme,y2=L(()=>{"use strict";g2();py();({featuresClient:ame,createFeature:sme,useFeaturesClientInitParams:lme}=_f("PowerApps-Shell-Test",Tf("shell-features")))});var w2=v((cme,v2)=>{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{}}}),b2=function(){return xu};Object.setPrototypeOf(b2,xu);v2.exports=b2});var BQ,qQ,C2=L(()=>{"use strict";fu();BQ=Ae(w2()),qQ=Ae(aa());});var E2=L(()=>{"use strict";y2();py();C2();});var vme,xs,wme,A2=L(()=>{"use strict";E2();fy();({featuresClient:vme,createFeature:xs,useFeaturesClientInitParams:wme}=_f("PowerApps-MakerPortal",Tf("powerapps-features")))});var S2,N2,Sme,Nme,_me,Tme,my=L(()=>{"use strict";fT();A2();({feature:S2}=xs({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:Ss.enableAutoInsertionOfCellInRow}})),{feature:N2}=xs({teamName:"MakerPortal",owners:["aansu"],description:"Enable the one grid events for form designer",createdOn:"08/21/2024",fallback:{enableOneGridEventsForFormDesigner:Ss.enableOneGridEvents}}),{feature:Sme}=xs({teamName:"MakerPortal",owners:["adekulkarni"],description:"Disables PBI components and cleans them up from the form",createdOn:"01/03/2023",fallback:{enableFallbackFormTemplate:Ss.disablePBIComponents}}),{feature:Nme}=xs({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:Ss.enableAgentResponse}}),{feature:_me,useFeature:Tme}=xs({teamName:"MakerPortal",owners:["aansu"],description:"Enables delayed localization of custom control",createdOn:"06/08/2025",fallback:{enableDelayedLocalizationForCustomControls:Ss.enableDelayedLocalizationForCustomControls}})});var D2=v((Ime,T2)=>{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{}}}),_2=function(){return Fu};Object.setPrototypeOf(_2,Fu);T2.exports=_2});var Zt,Co=L(()=>{"use strict";ht();st();Xt();bu();ue();It();Zt=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=lt.getUniqueIdentifierForControl(t);return!R.IsNullOrUndefined(r)&<.isUnboundFormControlByIdentifier(r)}else return!1}IsAllowedUBCForAvailableOnPhone(){let t=this.getFirstChild(E.formControl);if(t){let n=lt.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=lt.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 Fs,hy=L(()=>{"use strict";Xt();ue();It();Fs=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 I2,Ms,gy=L(()=>{"use strict";st();hy();ue();It();Co();(function(e){e[e.Form=0]="Form",e[e.Cell=1]="Cell",e[e.Tab=2]="Tab",e[e.Control=3]="Control"})(I2||(I2={}));Ms=class extends Zt{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 Fs(r,n.toString()))}}}});var On,Mu=L(()=>{"use strict";ht();Wl();st();oa();ue();It();Tn();On=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 ar,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=(Li.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)===Li.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 ar;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()===gt.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 Us,yy=L(()=>{"use strict";Xt();Ho();Mu();ue();It();Us=class extends On{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 ln.Chart:return ln.Chart;case ln.Grid:return ln.Grid;default:return ln.All}}set chartGridMode(t){this.setParameter(y.chartGridMode,t)}updateChartGridMode(t){t?this.chartGridMode=ln.Chart:this.chartGridMode=this.enableChartPicker?ln.All:ln.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(Ht.dataset)?n[i].getParameters().get(Ht.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 Bs,by=L(()=>{"use strict";Xt();Ho();Mu();ue();Bs=class extends On{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(Ht.value)?n[i].getParameters().get(Ht.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,vy,Ir,Uu=L(()=>{"use strict";O2=Ae(D2());Co();ue();st();ht();gy();Mu();bu();_0();s0();Tn();oa();ws();yy();by();wy();os();vy="_",Ir=class e extends Zt{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 On?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:!sa.dependencyFieldCount.containsKey(this.control.id):!sa.dependencyFieldCount.containsKey(this.control.dataFieldName)}createOnLoadEvent(){this.addEvent(new Ms(this,cu.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&&Zd[i])o=Zd[i].replace(/ /g,vy)+vy;else{o="Control_";let u=new Error("Control class id does not exist or is undefined");(0,O2.trackErrorTrace)(cr,{eventName:`${D_}/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===cn.Grid?(l=new Us(this),l.indicationOfSubgrid=!0):o===cn.Lookup?l=new Bs(this):l=new On(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=lt.getUniqueIdentifierForControl(l);R.IsNullOrUndefined(d)||(lt.getControlDataTypeByControlOrUniqueId(d)===ee.QuickFormCollectionControl||!lt.isUnboundFormControlByIdentifier(d)?o!==cn.Grid&&a&&u!==N.IframeControl&&u!==N.SubgridControl&&u!==N.ReferencePanelSubgridControl&&(l.dataFieldName=a,e.prototype.setProperty.call(l,y.disabled,"false")):(this.rowspan=lt.GetRowSpan(l),(lt.getControlDataTypeByControlOrUniqueId(d)===ee.NotesControl||lt.getControlDataTypeByControlOrUniqueId(d)===ee.TimeLineControl)&&(e.prototype.setProperty.call(l,y.disabled,"false"),l.id=ee.NotesControl)),(lt.getUnboundControlNameFromIdentifier(n)===ee.SubGridControl||lt.getUnboundControlNameFromIdentifier(n)===ee.NotesControl||lt.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(S0.ONE_COLUMN),n=Number(S0.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===oo.ApplicationRequired||a===oo.SystemRequired)&&!o||this.isCellLockedByExternal(t)&&!o)return!0}}return!1}getRequiredLevel(t){return!this.control?.dataFieldName||!this.control?.id||this.IsNewField||!this.control?.ClassId?oo.None:t.getEntityAttributeByName(this.control.dataFieldName)?.requiredLevel?.toString()??oo.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)===vy&&(r++,n=parseInt(t.substr(r,t.length-r),10)),n}}});var qs,Cy=L(()=>{"use strict";Xt();ue();It();qs=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 pa,Ey=L(()=>{"use strict";st();Uu();ue();It();pa=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 Ir(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 VQ(e){switch(e){case la.Left:return ca.Left;case la.Right:return ca.Right;case la.Center:return ca.Center;default:return ca.Left}}function GQ(e){switch(e){case Es.Left:return As.Left;case Es.Top:return As.Top;default:return As.Left}}function P2(e){switch(e){case 1:return 1;case 2:return 11;case 3:return 111;case 4:return 1111;default:return 1}}var WQ,ni,Bu=L(()=>{"use strict";T0();ht();st();Xt();my();Uu();ue();Tn();Co();Ey();WQ=115,ni=class e extends Zt{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=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===je.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),R.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 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 pa(null);if(this.addGrandChild(E.formRows,r),S2.getConfig().enableAutoInsertionOfCellInRow)for(let n=0;n<t;n++){let i=new Ir(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 P2(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=Ue.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)?Ue.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?WQ: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:VQ(this.fieldLabelAlignment),Position:GQ(this.fieldLabelPosition)},Columns:P2(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(Ue.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 Eo,Df=L(()=>{"use strict";ue();It();Bu();Eo=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 ni(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 If,R2=L(()=>{"use strict";ht();ue();Tn();Bu();If=class extends ni{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 Of,k2=L(()=>{"use strict";Df();ue();R2();Of=class extends Eo{addAndIntializeNavBarSection(t,r,n,i){let o=new If(E.formSection,null);return o.initializeNavArea(t,r,i),this.addGrandChildAtIndex(E.formSections,o,n),o}}});var xi,Pf=L(()=>{"use strict";ht();st();Xt();Df();ue();It();Co();xi=class extends Zt{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,go.namePrefix+t.toString()),this.addProperty(y.id,new U(U.NewGuid()).guidString),this.addProperty(y.IsUserDefined,go.IsUserDefined),this.addProperty(y.locklevel,go.LockLevel),this.addProperty(y.showlabel,go.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 Eo(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 ma,Ay=L(()=>{"use strict";ht();ue();It();Tn();k2();Pf();ma=class extends xi{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<cf.FIVE_COLUMN;t++){let r=new Of(this.getChildren(E.formColumns)[0]);r.initializeDefaultProperties(Z_.FiveEqColumn),this.addGrandChild(E.formColumns,r)}}}});function jQ(e){switch(e){case gt.Main:return yo.Main;case gt.QuickCreate:return yo.QuickCreate;case gt.QuickViewForm:return yo.Quick;case gt.Dialog:return yo.Dialog;default:return yo.None}}function HQ(e,t){if(t===gt.Main){if(e)switch(e.toLowerCase()){case"low":return ho.Low;case"highreadonlyvalues":return ho.HighReadOnlyValues;default:return ho.HighWithControls}return ho.Low}}var kf,zQ,Rf,L2=L(()=>{"use strict";sT();kf=Ae(aa());T0();st();Xt();ws();my();ue();Ho();Kg();oa();Uu();ue();Co();Cy();Ay();Pf();zQ="1920";Rf=class e extends Zt{_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 Jd,this._metadataChangeEvent=new ff}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 Ir).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 Ir){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 qs(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,kf.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))?zQ: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===gt.Main?this.setProperty(y.HeaderDensityType,t):this.formType!==gt.Main&&this.headerDensityType&&this.removeProperty(y.HeaderDensityType)}IsMainOrQuickCreateForm(){return this.formType===gt.Main||this.formType===gt.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 xi(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 xi(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===go.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 ma)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 Ir))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 Ir&&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,Ti.EditableGridControl)||N2.getConfig()?.enableOneGridEventsForFormDesigner&&this.cellHasCustomControlWithName(t,Ti.PowerAppsOneGrid)}isCellCanvasAppControl(t){return t?.control?.ClassId.guidString.toUpperCase()===N.CustomControl&&this.cellHasCustomControlWithName(t,Ti.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 ma)){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,kf.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===gt.Main?{HeaderDensity:HQ(this.headerDensityType,this.formType)}:{},InlineEditGridRow:[],InlineQuickForms:[],QuickFormEntities:[],EventHandlers:[],LinkControlSections:[],FormType:jQ(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 Lf,Sy,$2=L(()=>{"use strict";ht();st();ue();It();Co();Lf=class extends Zt{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 Sy(this))}},Sy=class extends re{constructor(t){super(E.formEveryOne,t)}}});var $f,x2=L(()=>{"use strict";ue();It();$f=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 Vs,Ny=L(()=>{"use strict";ue();Bu();Vs=class extends ni{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 qu,F2=L(()=>{"use strict";ue();Ny();qu=class extends Vs{_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 Vu,M2=L(()=>{"use strict";ue();Ny();Vu=class extends Vs{_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 Or,ha=L(()=>{"use strict";ht();Xt();ue();Co();Or=class e extends Zt{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 Gu,U2=L(()=>{"use strict";(function(e){e[e.NavLinkNotAvailable=-1]="NavLinkNotAvailable",e[e.NavLinkIdConflict=-2]="NavLinkIdConflict",e[e.NavBarNotAvailable=-3]="NavBarNotAvailable"})(Gu||(Gu={}))});var xf,B2=L(()=>{"use strict";st();ue();ha();U2();xf=class extends Or{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)?Gu.NavLinkNotAvailable:r.length===1?this.deleteChild(r[0]):Gu.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 xe,KQ,q2,b0e,Gs,_y=L(()=>{"use strict";ht();ue();ha();(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"})(xe||(xe={}));KQ=new Map([[xe.Info,"Info"],[xe.Sales,"Sales"],[xe.Service,"Service"],[xe.Marketing,"Marketing"],[xe.ProcessCenter,"ProcessCenter"]]),q2=new Map([["Info",xe.Info],["Sales",xe.Sales],["Service",xe.Service],["Marketing",xe.Marketing],["ProcessCenter",xe.ProcessCenter]]),b0e=new Map([[xe.Info,9e3],[xe.Sales,9200],[xe.Service,9400],[xe.Marketing,9600],[xe.ProcessCenter,9800],[xe.InternetMarketing,1e4],[xe.Async,10200]]),Gs=class extends Or{constructor(t,r){super(E.formNavBarArea,r)}setDefaultPropertiesByType(t,r,n){this.AreaId=KQ.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 Ws,Ty=L(()=>{"use strict";ue();ha();Ws=class extends Or{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 Ff,V2=L(()=>{"use strict";st();ue();ha();Ff=class extends Or{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 Mf,G2=L(()=>{"use strict";ue();ha();Mf=class extends Or{constructor(t){super(E.formNavBarItem,t)}get Url(){return this.getProperty(y.url)}set Url(t){this.setProperty(y.url,t)}}});var Uf,W2=L(()=>{"use strict";ht();ue();_y();Ty();ha();Uf=class extends Or{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=[xe.Info,xe.Sales,xe.Service,xe.Marketing,xe.ProcessCenter];if(this.navBarAreas){let i=this.navBarAreas?.AllNavBarAreaItems;if(i&&i.length>0){let o=new Set(i.map(a=>q2.get(a.AreaId)));n=n.filter(a=>!o.has(a))}}else{let i=new Ws(E.formNavBarAreas,this);i.isTransient=!0,this.addChild(i)}return n.length>0?(n.forEach(i=>{let o=new Gs(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(a0,!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 z2={};Jr(z2,{ControlType:()=>cn,DeserializationService:()=>Oy,DeserializationServiceScope:()=>Iy,DeserializedFormElementNode:()=>Pr});var Dy,Pr,Iy,cn,Oy,wy=L(()=>{"use strict";Dy=Ae(aa());ht();st();Xt();ws();s0();oa();O_();oT();bu();L2();Uu();Df();Mu();hy();ue();ue();$2();It();Tn();gy();x2();F2();yy();by();M2();Cy();Ey();Bu();Pf();B2();_y();Ty();V2();G2();W2();Pr=class extends re{constructor(t,r){super(t,r)}insertProperty(t,r){this.addProperty(t,r)}insertChild(t){this.addChild(t)}},Iy="DeserializationService";(function(e){e.Grid="Grid",e.Lookup="Lookup",e.Base="Base"})(cn||(cn={}));Oy=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,Dy.trackErrorTrace)(cr,{eventName:Iy,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!==gt.Dialog&&this.appendDefaultDisplayCondition(f),f}upsertFieldCount(t,r){let n=sa.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 Rf(r,n,i,o,a,s,l,u,c);return this.populateElementProperties(d,t.attributes),this.populateElementChildren(d,t.childNodes),s===gt.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 Vu(r,!0):new qu(r,!0);Pr.prototype.insertProperty.call(i,y.id,"{"+U.NewGuid()+"}"),Pr.prototype.insertProperty.call(i,y.Fieldlabelposition,"Top"),Pr.prototype.insertProperty.call(i,y.columnName,Ue.MarginalControlColumns),Pr.prototype.insertProperty.call(i,y.LabelWidth,Ue.LabelWidth),Pr.prototype.insertProperty.call(i,y.Fieldlabelalignment,"Left");let o=null,a=new pa(o);for(let s=0;s<i.maxColumns;s++){let l=new Ir(a);Pr.prototype.insertProperty.call(l,y.id,"{"+U.NewGuid()+"}"),l.setDisplayName(q.EmptyString,this.lcid),Pr.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 Pr(`<${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,Dy.trackErrorTrace)(cr,{eventName:Iy,eventData:{error:n}}),new Error(n)}for(let n=0;n<r.length;n++){let i=r.item(n);i&&(Pr.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&&Pr.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 xi(r);case E.formColumn:return new Eo(r);case E.formHeader:return new Vu(r,!1);case E.formFooter:return new qu(r,!1);case E.formSection:return new ni(E.formSection,r);case E.formRow:return new pa(r);case E.formCell:return new Ir(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=cn.Grid;else if(l.name===y.classid&&l.value?.toLocaleUpperCase()===`{${N.LookupControl}}`)o=cn.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=cn.Lookup)}return o===cn.Grid?new Us(r):o===cn.Lookup?new Bs(r):new On(r);case E.formEvent:return new Ms(r,q.EmptyString);case E.dependency:return this.populateDependencyTable(t),new Fs(r,q.EmptyString);case E.Handler:let a=[];return new $f(a,r);case E.formNavigation:return new Uf(t.nodeName,r);case E.formNavBarArea:return new Gs(t.nodeName,r);case E.formNavBarAreas:return new Ws(t.nodeName,r);case E.formNavBar:return new xf(r);case E.formNavBarByRelationshipItem:return new Ff(r);case E.formNavBarItem:return new Mf(r);case E.formDisplayConditions:return new Lf(r);case E.library:return new qs(r,q.EmptyString,q.EmptyString);case E.controlDescription:return new ef(r);case E.customControl:return this.populateCustomControlConfigurationId(t),new df(r);default:return new Pr(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,Zn.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);lt.CustomControlIdMap.upsert(l,o);break}}break}}}}});var j2={};Jr(j2,{SerializationService:()=>Py,SerializationServiceScope:()=>JQ,SerializedFormElementNode:()=>zs});var JQ,zs,Py,H2=L(()=>{"use strict";Xt();It();Tn();Ay();JQ="SerializationService",zs=class extends re{fetchNodeName(){return this.getNodeName()}enumerateProperties(){return this.getAllProperties()}enumerateChildren(){return this.getAllChildren()}},Py=class{langCode;constructor(t){this.langCode=t}serializeFormXmlNode(t){let r=zs.prototype.fetchNodeName.call(t);if(r.charAt(0)===Li.StartTag)return q.EscapeXml(r.substr(1),!1);if(t.isTransient&&!t.isDirty())return q.EmptyString;let n=zs.prototype.enumerateProperties.call(t),i=zs.prototype.enumerateChildren.call(t);if(!(t instanceof ma)){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 $y=v(js=>{"use strict";Object.defineProperty(js,"__esModule",{value:!0});js.completeRecordAsStored=js.completeLabelsAsStored=void 0;var Ry=uo(),YQ="E7A81278-8635-4D9E-8D4D-59480B391C5B",QQ=new Set(["tab","section","cell"]);function Pn(e){let t=[];for(let r=e.firstChild;r;r=r.nextSibling)r.nodeType===1&&t.push(r);return t}function Ao(e,t){return Pn(e).find(r=>r.tagName===t)}function J2(e,t){return e.length===t.length&&e.every((r,n)=>r.tagName===t[n].tagName)}function ky(e){let t=Ao(e,"control");return t?(t.getAttribute("datafieldname")||"")!==""?!0:(t.getAttribute("classid")||"").replace(/[{}]/g,"").toUpperCase()===YQ:!1}function Ly(e,t){var r,n;let i=((r=Ao(e,"control"))===null||r===void 0?void 0:r.getAttribute("id"))||"";return i!==""&&i===(((n=Ao(t,"control"))===null||n===void 0?void 0:n.getAttribute("id"))||"")}function XQ(e,t){if(Ao(e,"labels"))return;let r=Pn(e),n=Pn(t),i=n[0];if(!i||i.tagName!=="labels"||n.length!==r.length+1||!J2(r,n.slice(1)))return;let o=Pn(i);if(!(o.length===0||o.some(s=>s.tagName!=="label"||!s.hasAttribute("description")||!s.hasAttribute("languagecode"))||!(e.tagName==="cell"&&ky(e)&&Ly(e,t))&&o.some(s=>s.getAttribute("description")!=="")))return i}function ZQ(e,t){let r=eX(e.ownerDocument,t),n=Pn(e)[0];n?e.insertBefore(r,n):e.appendChild(r)}function eX(e,t){let r=e.createElement("labels");for(let n of Pn(t))r.appendChild(Y2(e,n));return r}function Y2(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 K2(e,t){let r=Ao(e,"labels");return r?Pn(r).find(n=>n.tagName==="label"&&n.getAttribute("languagecode")===String(t)):void 0}function tX(e,t,r){if(e.tagName!=="cell"||!ky(e)||!Ly(e,t))return!1;let n=K2(e,r),i=K2(t,r),o=i?.getAttribute("description")||"";return!n||!n.hasAttribute("description")||(n.getAttribute("description")||"")!==""||o===""?!1:(n.setAttribute("description",o),!0)}function rX(e,t){if(e.tagName!=="cell"||!ky(e)||!Ly(e,t))return;let r=Ao(e,"labels"),n=Ao(t,"labels");if(!r||!n)return;let i=Pn(r),o=Pn(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 Q2(e,t,r,n){if(e.tagName!==t.tagName)return;if(QQ.has(e.tagName)){let a=XQ(e,t);a&&(ZQ(e,a),n.changed=!0),tX(e,t,r)&&(n.changed=!0);let s=rX(e,t),l=Ao(e,"labels");if(s&&l){for(let{label:u,before:c}of s){let d=Y2(e.ownerDocument,u);c?l.insertBefore(d,c):l.appendChild(d)}n.changed=!0}}let i=Pn(e),o=Pn(t);J2(i,o)&&i.forEach((a,s)=>Q2(a,o[s],r,n))}function X2(e,t,r){if(e===t)return e;let n,i;try{n=(0,Ry.parseXmlRoot)(e,""),i=(0,Ry.parseXmlRoot)(t,"")}catch{return e}let o={changed:!1};return Q2(n,i,r,o),o.changed?(0,Ry.serializeNode)(n):e}js.completeLabelsAsStored=X2;function nX(e,t,r){let n=e?.formxml,i=t?.formxml;if(typeof n!="string"||typeof i!="string")return e;let o=X2(n,i,r);return o===n?e:{...e,formxml:o}}js.completeRecordAsStored=nX});var bk=v(ce=>{"use strict";Object.defineProperty(ce,"__esModule",{value:!0});ce.pcfReadIssues=ce.pcfBindingIssues=ce.commitPcfState=ce.mayCommitPcfState=ce.reconcilePcfDescriptions=ce.customControlNeeds=ce.mintPcfIdentity=ce.planPcfBinding=ce.projectPcfBindings=ce.supportsPcfFormType=ce.storedBindingOf=ce.hasCustomControl=ce.sameAsStored=ce.readPcfDescription=ce.newPcfDescription=ce.editorText=ce.nativeClassFor=ce.pcfEntryLayout=void 0;var iX=(bu(),Br(aT)),oX=Q(),Z2=pt(),V=Dd(),aX=Hh(),Ee=rn(),Ui=["web","phone","tablet"],Wu={web:"2",phone:"0",tablet:"1"},ik=new Map([["2","web"],["0","phone"],["1","tablet"]]),sX=["phone","web","tablet"];function qf(e){let t=new Set(e),r=sX.filter(n=>!t.has(n));return{defaults:r.length===0?[null]:r,named:Ui.filter(n=>t.has(n))}}ce.pcfEntryLayout=qf;function dr(e){return Array.isArray(e)?e:[]}function ut(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function zu(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Fy(e){return{n:`<${e}`,a:[],c:[]}}function ok(e){return typeof e?.n=="string"&&e.n.startsWith("<")}function ek(e){let t=dr(e.c);return t.length===1&&ok(t[0])&&(0,V.rawText)(e)!==""?(0,V.rawText)(e):void 0}function fn(e,t){return JSON.stringify(e)===JSON.stringify(t)}function ak(e){return`{${e.replace(/^\{|\}$/g,"").toUpperCase()}}`}function My(e){try{let t=(0,iX.mapFieldTypeToControl)(e.attributeTypeName,e.format);return t?ak(String(t)):void 0}catch{return}}ce.nativeClassFor=My;var Uy=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}]]),sk=new Set(["TwoOptions","Boolean"]),lk=new Set(["SingleLine.Text","SingleLine.TextArea","SingleLine.Email","SingleLine.Phone","SingleLine.URL","SingleLine.Ticker","Multiple"]),lX=new Map([...[...lk].map(e=>[e,100]),["SingleLine.TextArea",2e3],["Multiple",1048576]]),uX=/^[A-Za-z_][A-Za-z0-9_.-]*$/;function uk(e){return uX.test(e)&&e!=="__proto__"}function By(e){return e!==void 0&&(e==="Enum"||Uy.has(e)||sk.has(e)||lk.has(e))}function ck(e){return typeof e=="number"?e:e!==""&&!Number.isNaN(Number(e))?Number(e):void 0}function ju(e,t){let r=e!==void 0?Uy.get(e):void 0;if(r&&typeof t!="boolean"){let n=ck(t);if(n!==void 0)return n.toFixed(r.digits)}return typeof t=="boolean"?t?"true":"false":String(t)}ce.editorText=ju;function cX(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"&&zu(r,a)?s=ju(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:[Fy(s)]})}return i}function dk(e,t,r,n,i){var o,a;let s=(o=n.formFactors)!==null&&o!==void 0?o:Ui.filter(d=>qy(i).has(d)),l=qf(s),u=cX(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",Wu[d]]],c:[{n:"parameters",a:[],c:[{n:"datafieldname",a:[],c:[Fy(t)]}]}]})),...l.named.map(d=>({n:"customControl",a:[["name",n.name],["formFactor",Wu[d]]],c:[{n:"parameters",a:[],c:c(u)}]}))]}}ce.newPcfDescription=dk;function qy(e){return new Set(Ui.filter(t=>e.availableOn[t]))}function Bf(e){var t;let r=dr(e.c);if(r.length!==1||((t=r[0])===null||t===void 0?void 0:t.n)!=="parameters"||dr(r[0].a).length>0)return;let n=dr(r[0].c);return n.every(i=>ut(i)&&!ok(i))?n:void 0}function ga(e){let t=dr(e?.c);if(t.length===0||!t.every(p=>ut(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=dr(p.a),g=h.length===2?ik.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=qf(o);if(!fn(a.named,o)||i==="")return;let s=Bf(n[0]);if(!s||!n.every(p=>fn(Bf(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",Wu[h]]],b=Bf(l[p]),w=b?.length===1&&b[0].n==="datafieldname"&&dr(b[0].a).length===0?ek(b[0]):void 0;if(!u||!fn(dr(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=dr(p.a),g=ek(p),b=h.map(w=>w[0]);if(g===void 0||!uk(p.n)||zu(d,p.n)||p.n===m)return;if((0,V.rawAttr)(p,"static")===void 0){if(m!==void 0||g!==c||!(b.length===0||fn(b,["type"])))return;m=p.n;continue}if((0,V.rawAttr)(p,"static")!=="true"||!(fn(b,["static"])||fn(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===Ui.length?{}:{formFactors:o}},fieldName:c,nativeClass:u,parameterTypes:f,boundProperty:m}}ce.readPcfDescription=ga;function fk(e,t,r){return e===t?!0:typeof e!="string"&&(t===String(e)||t===ju(r,e))}function pk(e){let t=e.formFactors;return t===void 0?[...Ui]:Array.isArray(t)?Ui.filter(r=>t.includes(r)):[]}function xy(e,t){var r,n,i;if(e.name!==t.binding.name||!fn(pk(e),(r=t.binding.formFactors)!==null&&r!==void 0?r:Ui))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=>zu(a,l)&&fk(o[l],a[l],t.parameterTypes[l]))}ce.sameAsStored=xy;function yt(e){return ut(e)&&e.customControl!==void 0}ce.hasCustomControl=yt;function Mi(e,t){var r;return t?dr((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 Vy(e,t){let r=Mi(e.bag,(0,V.controlUniqueId)(t));return r.length===1?ga(r[0]):void 0}ce.storedBindingOf=Vy;function Gy(e){let t=(0,V.effectiveFormType)(e);return t==="Main"||t==="QuickCreate"}ce.supportsPcfFormType=Gy;function dX(e){if(!Gy(e))return;let t=(0,V.controlUniqueIds)(e);for(let{cell:r}of(0,V.typedCellSites)(e)){let n=r.control;if(!ut(n)||!n.fieldName||!Fi(n.classId)||t.get((0,V.controlUniqueId)(n))!==1)continue;let i=Vy(e,n);i&&i.fieldName===n.fieldName&&(n.customControl=JSON.parse(JSON.stringify(i.binding)))}}ce.projectPcfBindings=dX;function Fi(e){return typeof e=="string"&&e.replace(/^\{|\}$/g,"").toUpperCase()===V.CUSTOM_CONTROL_CLASS_ID}var dn=(e,t)=>({kind:"refused",rule:e,message:t});function fX(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)&&!Fi(e)}function tk(e,t,r){var n,i;let o=ga(r);if(!o)return dn("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 dn("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 dn("pcf-binding-control-swap",`the binding uses "${o.binding.name}": to use another control, remove customControl, push, then add it`);let a=ut(t.parameters)?t.parameters:{},s=(n=o.binding.parameters)!==null&&n!==void 0?n:{},l=Object.keys(a).sort();if(!fn(l,Object.keys(s).sort()))return dn("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=>!fk(a[g],s[g],o.parameterTypes[g])),c=u.find(g=>ju(o.parameterTypes[g],a[g]).trim()==="");if(c!==void 0)return dn("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=pk(t),f=(i=o.binding.formFactors)!==null&&i!==void 0?i:[...Ui],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=>!By(o.parameterTypes[g]));if(h!==void 0){let g=o.parameterTypes[h];return dn("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)&&!fX(o.nativeClass)?dn("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 pX(e,t){return t&&(0,V.typedCellSites)(e).find(({cell:n})=>yt(n.control)&&(0,V.controlUniqueId)(n.control)===t)?{descriptions:Mi(e.bag,t)}:void 0}function mk(e,t){let r=new Map,n=mX(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:yX(u),uid:(0,V.controlUniqueId)(c),bound:yt(c)});for(let{cell:u}of(0,V.typedCellSites)(e)){let c=u.control;ut(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(!ut(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&&rk(D.control)&&r.set(D.control,nk(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)&&rk(D.control)),O=f.filter(D=>m.includes(D));if(S.length===0||O.length===0&&b.length===0)continue;let k=[...O,...b],I=O.length===1&&S.length===1&&m.length===1?nk(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 ${k.map(D=>`{${D.uid}}`).join(", ")} no longer ${k.length===1?"names":"name"} a control: which control held ${k.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 mX(e){let t=(0,V.controlUniqueIds)(e),r=new Map;for(let{cell:i}of(0,V.typedCellSites)(e)){let o=ut(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||yt(a)||o>1)&&n.add(i)}return n}function rk(e){return yt(e)||e.genPage===void 0&&Fi((0,V.effectiveClassId)(e))}function hX(e,t){let r=o=>(0,V.typedCellSites)(o).flatMap(({cell:a,pointer:s})=>{let l=a.control;if(!ut(l)||yt(l)||l.genPage!==void 0||!Fi((0,V.effectiveClassId)(l)))return[];let u=(0,V.controlUniqueId)(l);return u===""||Mi(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 gX="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 nk(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 yX(e){let t=typeof e.id=="string"?e.id.trim():"";return(0,V.normGuid)(t)||t.toLowerCase()}function Hu(e,t,r,n){let i=t.customControl,o=(0,V.controlUniqueId)(t),a=Mi(e.bag,o),s=r?mk(e,r).get(t):void 0;if(s!==void 0)return dn("pcf-binding-unique-id",s);let l=r?pX(r,o):void 0;if(l){let c=l.descriptions,d=c.length===1?ga(c[0]):void 0;if(d&&d.fieldName!==t.fieldName)return dn("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&&fn(c[0],a[0]))return tk(t,i,a[0]);let f=a.length===1?ga(a[0]):void 0;return d&&f&&f.fieldName===t.fieldName&&xy(i,d)&&xy(i,f)?{kind:"unchanged"}:dn("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 dn("pcf-binding-other-control","the control already has a description the SDK cannot read as a binding; adding would replace it");let u=tk(t,i,a[0]);return n&&(u.kind==="edit"||u.kind==="unchanged")?u.kind==="unchanged"?u:dn("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}ce.planPcfBinding=Hu;function hk(e){return e.kind==="edit"&&(e.changed.length>0||e.added.length>0)}function bX(e){let t=n=>yt(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,Z2.newId)()),n.id||(n.id=(0,Z2.newId)()),(0,V.authoredUniqueId)(i)===void 0&&(0,V.setUniqueId)(i)}return r}ce.mintPcfIdentity=bX;function vX(e,t){let r=new Set,n=new Set;for(let{cell:i}of(0,V.typedCellSites)(e)){let o=i.control;if(!yt(o)||!ut(o.customControl))continue;let a=o.customControl.name;if(typeof a!="string"||a===""||typeof o.fieldName!="string"||!o.fieldName)continue;let s=Hu(e,o,t,!0);s.kind==="new"?(r.add(a),n.add(o.fieldName)):hk(s)&&r.add(a)}return{controls:[...r],columns:[...n],...n.size>0&&(0,V.effectiveFormType)(e)==="QuickCreate"?{requireCreateEligibility:!0}:{}}}ce.customControlNeeds=vX;function wX(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(!yt(p)||!ut(p.customControl))continue;let h=(0,V.controlUniqueId)(p);h&&Mi(u,h).length>0&&c.set(p,{plan:Hu(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=ut(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(!yt(g))continue;let b=(0,V.controlUniqueId)(g),w=Mi(t.bag,b),C=Mi(u,b);if(w.length!==1||C.length!==1||!fn(w[0],C[0])||!ga(C[0]))continue;let S=p.get(b);if(S&&!yt(S)){if(((n=f.get(b))!==null&&n!==void 0?n:0)>1)continue;let O=(o=(i=ga(C[0]))===null||i===void 0?void 0:i.nativeClass)!==null&&o!==void 0?o:"";S.classId=O.replace(/^\{|\}$/g,"").toUpperCase(),CX(S,"uniqueid"),m.add(b)}else!S&&!f.has(b)&&m.add(b)}m.size>0&&(d.node.c=dr(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(!yt(m)||!ut(m.customControl))continue;Fi(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 oX.ValidationError("form",e.id,[(0,Ee.issue)(h.pointer,h.plan.rule,h.plan.message)]);h.plan.kind==="edit"&&EX(h.plan,m.customControl);continue}let g=r?.control(m.customControl.name),b=r?.column(e.entityLogicalName,m.fieldName),w=b?.kind==="found"?My(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=dr((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(dk(S,m.fieldName,w,m.customControl,g.value))}}ce.reconcilePcfDescriptions=wX;function CX(e,t){ut(e.bag)&&(e.bag.a=dr(e.bag.a).filter(r=>r[0]!==t))}function EX(e,t){var r,n;let i=dr(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=Bf(g))!==null&&n!==void 0?n:[])e.changed.includes(b.n)&&(b.c=[Fy(ju(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=ik.get(w))!==null&&b!==void 0?b:null},d=(0,V.rawAttr)(a[0],"id"),f=(0,V.rawAttr)(s[0],"name"),m=qf(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",Wu[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",Wu[g]]],w});e.description.c=[...p,...h]}function AX(e){return(0,V.typedCellSites)(e).some(({cell:t})=>yt(t.control))}ce.mayCommitPcfState=AX;function SX(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(!yt(a))continue;let s=Vy(n,a);if(!s||s.fieldName!==a.fieldName)continue;let l=t(V.CUSTOM_CONTROL_CLASS_ID),u=dr((r=a.bag)===null||r===void 0?void 0:r.a).find(c=>c[0]==="classid");(!Fi(a.classId)||a.type!==l||u!==void 0&&!Fi(u[1])||!fn(a.customControl,s.binding))&&(Fi(a.classId)||(a.classId=V.CUSTOM_CONTROL_CLASS_ID),a.type=l,u&&!Fi(u[1])&&(u[1]=ak(V.CUSTOM_CONTROL_CLASS_ID)),a.customControl=JSON.parse(JSON.stringify(s.binding)),i=!0)}return i?n:e}ce.commitPcfState=SX;var NX=new Set(["name","parameters","formFactors"]);function _X(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;yt(s)&&DX(e,s,`${a}/control`,i,n,t,r?.atPush===!0)}return t&&IX(e,t,n),n}ce.pcfBindingIssues=_X;function TX(e,t,r){let n=r.length;if(!ut(e))return r.push((0,Ee.issue)(t,"pcf-binding-shape","customControl must be an object")),!1;for(let i of Object.keys(e))NX.has(i)||r.push((0,Ee.issue)(`${t}/${i}`,"pcf-binding-unknown-key",`customControl has no "${i}"`));if((typeof e.name!="string"||e.name.trim()==="")&&r.push((0,Ee.issue)(`${t}/name`,"pcf-binding-shape","name must be the control's non-empty customcontrols name")),e.parameters!==void 0)if(!ut(e.parameters))r.push((0,Ee.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,Ee.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"&&Ui.includes(a))&&new Set(i).size===i.length||r.push((0,Ee.issue)(`${t}/formFactors`,"pcf-binding-shape","formFactors must be distinct 'web', 'phone' and 'tablet', at least one"))}return r.length===n}function DX(e,t,r,n,i,o,a){var s;let l=`${r}/customControl`,u=TX(t.customControl,l,i);t.fieldName||i.push((0,Ee.issue)(l,"pcf-binding-unbound","a PCF binding needs a control bound to a column (fieldName)")),t.genPage!==void 0&&i.push((0,Ee.issue)(l,"pcf-binding-with-genpage","a control cannot embed a page and bind a PCF control")),Gy(e)||i.push((0,Ee.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,Ee.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,Ee.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,Ee.issue)(`${r}/bag`,"pcf-binding-unique-id","another control carries the same uniqueid")),!u)return;let f=Hu(e,t,o,a);f.kind==="refused"&&i.push((0,Ee.issue)(l,f.rule,f.message))}function IX(e,t,r){var n;let i=new Map,o=mk(e,t);for(let{cell:l,pointer:u}of(0,V.typedCellSites)(e)){let c=ut(l.control)?(0,V.controlUniqueId)(l.control):"";if(c&&!i.has(c)&&i.set(c,{control:l.control,pointer:`${u}/control`}),ut(l.control)&&!yt(l.control)){let d=o.get(l.control);d!==void 0&&r.push((0,Ee.issue)(`${u}/control`,"pcf-binding-unique-id",d))}}let a=(0,V.controlUniqueIds)(e);for(let{cell:l}of(0,V.typedCellSites)(t)){if(!yt(l.control))continue;let u=(0,V.controlUniqueId)(l.control),c=i.get(u);!c||yt(c.control)||(((n=a.get(u))!==null&&n!==void 0?n:0)>1?r.push((0,Ee.issue)(c.pointer,"pcf-binding-unique-id","another control carries this binding\u2019s uniqueid; removing the binding would delete its description too")):fn(Mi(t.bag,u),Mi(e.bag,u))?c.control.fieldName!==l.control.fieldName&&r.push((0,Ee.issue)(c.pointer,"pcf-binding-rebind","remove the binding, push, then bind the new column")):r.push((0,Ee.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 hX(e,t))s.has(l)||r.push((0,Ee.issue)(l,"pcf-binding-unique-id",gX))}var OX=new Set(["Form.Card"]),PX="MscrmControls.ModelForm.ModelFormControl";function gk(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=>!uk(s));if(o!==void 0)return`the property name "${o}" cannot be written as an element`;if(t===PX||n.some(s=>s.defaultType!==void 0&&OX.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"&&!By(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 RX(e){return e.ofType!==null?[e.ofType]:e.ofTypeGroup}function yk(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?Uy.get(r):void 0;if(n){let o=typeof t=="boolean"?void 0:ck(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&&sk.has(r))return t===!0||t===!1||t==="true"||t==="false"?void 0:"must be true or false";let i=r!==void 0?lX.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 kX(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(!yt(d)||!d.fieldName)continue;let f=d.customControl;if(!ut(f)||typeof f.name!="string")continue;let m=`${c}/control/customControl`,p=Hu(e,d,r,!0);if(p.kind==="edit"){hk(p)&&xX(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,Ee.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=gk(h.value,f.name);if(b){l.push((0,Ee.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,aX.manifestTypesForColumn)(C.attributeTypeName,C.format,C.formatName))!==null&&a!==void 0?a:[]:[];C!==void 0&&!C.isPrimaryId&&C.isValidForForm&&My(C)!==void 0&&RX(w).some(x=>S.includes(x))?(0,V.effectiveFormType)(e)==="QuickCreate"&&C?.isValidForCreate!==!0&&l.push((0,Ee.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,Ee.issue)(m,"pcf-binding-incompatible-column",`"${f.name}" cannot be bound to "${d.fieldName}"`));let k=new Map(h.value.properties.filter(x=>x.usage==="input").map(x=>[x.name,x])),I=ut(f.parameters)?f.parameters:{};for(let[x,K]of Object.entries(I)){let Oe=k.get(x);if(!Oe){l.push((0,Ee.issue)(`${m}/parameters/${x}`,"pcf-binding-unknown-parameter",`"${f.name}" has no input "${x}"`));continue}let Vt=yk(Oe,K);Vt&&l.push((0,Ee.issue)(`${m}/parameters/${x}`,"pcf-binding-parameter-value",`"${x}" ${Vt}`))}for(let x of k.values())x.required&&!zu(I,x.name)&&!x.defaultValue&&l.push((0,Ee.issue)(`${m}/parameters`,"pcf-binding-missing-parameter",`"${x.name}" is required`));let D=qy(h.value),P=Array.isArray(f.formFactors)?f.formFactors:void 0;(P?P.some(x=>!D.has(x)):D.size===0)&&l.push((0,Ee.issue)(`${m}/formFactors`,"pcf-binding-form-factor",`"${f.name}" is available on ${D.size===0?"no form factor":[...D].join(", ")}`))}return s}ce.pcfReadIssues=kX;function LX(e,t){return t===void 0||!By(t)?!1:e.ofType!==null?e.ofType===t:e.ofTypeGroup.includes(t)}function $X(e,t,r){var n,i;let o=gk(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&&!zu(s,d.name));return c?`it now requires "${c.name}", which the binding does not store`:void 0}function xX(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,Ee.issue)(`${r}/name`,"PCF_CONTROL_NOT_FOUND",`no single installed control is named "${t.name}" (${u.kind})`));return}let c=$X(u.value,t.name,e.stored);if(c){l.push((0,Ee.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];LX(d.get(h),g)||l.push((0,Ee.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=yk(d.get(h),m[h],e.stored.parameterTypes[h]);g&&l.push((0,Ee.issue)(`${r}/parameters/${h}`,"pcf-binding-parameter-value",`"${h}" ${g}`))}let p=qy(u.value);e.added.some(h=>!p.has(h))&&l.push((0,Ee.issue)(`${r}/formFactors`,"pcf-binding-form-factor",`"${t.name}" is available on ${p.size===0?"no form factor":[...p].join(", ")}`))}});var Lk=v(kr=>{"use strict";Object.defineProperty(kr,"__esModule",{value:!0});kr.classIdForAttributeType=kr.QUICK_VIEW_CLASS_ID=kr.NOTES_CLASS_ID=kr.SUBGRID_CLASS_ID=kr.formRegistration=kr.FormAdapter=void 0;var Bi=(ht(),Br(C_)),vk=(st(),Br(E_)),FX=(It(),Br(S_)),bt=(ue(),Br(A_)),rt=(oa(),Br(N_)),MX=(wy(),Br(z2)),UX=(H2(),Br(j2)),vt=so(),wk=Qr(),Rr=rn(),BX=_g(),Ks=pt(),qX=$y(),er=Dd(),ii=bk(),Hs=Q(),Jy=le(),Wy=lo(),_k=Jo(),VX={[bt.FormType.Main]:"Main",[bt.FormType.QuickCreate]:"QuickCreate",[bt.FormType.QuickViewForm]:"QuickView",[bt.FormType.Card]:"Card"},Vf={Main:bt.FormType.Main,QuickCreate:bt.FormType.QuickCreate,QuickView:bt.FormType.QuickViewForm,Card:bt.FormType.Card},GX=new Map(Object.entries(rt.ControlClassId).map(([e,t])=>[String(t).toUpperCase(),e]));function Yy(e){var t;return e&&(t=GX.get(e.toUpperCase()))!==null&&t!==void 0?t:"Unknown"}function Ku(e){return e.getAllProperties().map(t=>[t.key,t.value])}function ya(e){let t=new Map;for(let r of e.getAllProperties())t.has(r.key)||t.set(r.key,r.value);return t}function Tk(e,t){return e.getAllChildren().find(r=>r.getNodeName()===t)}function Qy(e,t){var r,n;let i=Tk(e,"labels");if(!i)return"";let o=i.getAllChildren().filter(s=>s.getNodeName()==="label"),a=(r=o.find(s=>ya(s).get("languagecode")===String(t)))!==null&&r!==void 0?r:o[0];return a&&(n=ya(a).get("description"))!==null&&n!==void 0?n:""}function WX(e){let t=Tk(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 Dk(e){return/^1+$/.test(e)&&e.length>=1&&e.length<=4?e.length:1}function zy(e){let t=Math.min(Math.max(Math.trunc(e),1),4);return"1".repeat(t)}function Ju(e){return String(e??"").replace(/[{}]/g,"")}function jy(e){return`{${Ju(e)}}`}function Hy(e,t){if(e===void 0||e==="")return t;let r=Number(e);return Number.isNaN(r)?t:r}function Wf(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,vt.rawFromNode)(u)})}),i<0)return{modeled:[],bag:{a:Ku(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,vt.rawFromNode)(u)})}),{modeled:s,bag:{a:Ku(e),c:o,w:{n:a.getNodeName(),a:Ku(a),c:l}}}}function Ik(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,vt.rawFromNode)(o)})}),{modeled:n,bag:{a:Ku(e),c:i}}}function Ck(e,t){let{modeled:r,bag:n}=Wf(e,"tabs","tab");return{tabs:r.map(i=>zX(i,t)),bag:n}}function zX(e,t){var r,n;let i=ya(e),{modeled:o,bag:a}=Wf(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:Qy(e,t),expanded:i.get("expanded")==="true",visible:i.has("visible")?i.get("visible")==="true":!0,columns:o.map(s=>jX(s,t)),bag:a}}function jX(e,t){let r=ya(e),{modeled:n,bag:i}=Wf(e,"sections","section");return{width:r.get("width"),sections:n.map(o=>HX(o,t)),bag:i}}function HX(e,t){var r,n,i;let o=ya(e),{modeled:a,bag:s}=Wf(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:Qy(e,t),visible:o.has("visible")?o.get("visible")==="true":!0,showLabel:o.get("showlabel")==="true",columns:Dk((i=o.get("columns"))!==null&&i!==void 0?i:"1"),rows:a.map(l=>KX(l,t)),bag:s}}function KX(e,t){let{modeled:r,bag:n}=Ik(e,"cell",!1);return{cells:r.map(i=>JX(i,t)),bag:n}}function JX(e,t){var r;let n=ya(e),{modeled:i,bag:o}=Ik(e,"control",!0),a=Qy(e,t),s=n.get("showlabel")==="true",l=i[0]?YX(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:Hy(n.get("colspan"),1),rowspan:Hy(n.get("rowspan"),1),control:l,bag:o}}function YX(e,t,r){var n,i;let o=ya(e),a=Ju((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:Yy(a),isRequired:o.get("isrequired")==="true",isReadOnly:o.get("disabled")==="true",label:t,showLabel:r,parameters:WX(e),bag:{a:Ku(e),c:e.getAllChildren().map((l,u)=>({i:u,node:(0,vt.rawFromNode)(l)}))}}}function _o(e){return e.a.length===0&&e.c.length===0&&!e.w}function Ok(e,t){let r=e.a.find(n=>n[0]===t);return r?r[1]:void 0}function ba(e,t){var r;let n=new Set(e.a.map(a=>a[0])),i=_o(e),o=[];for(let a of t)if(n.has(a.key)){let s=(r=Ok(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,vt.mergeAttrs)(e.a,o)}var So=(e,t)=>({key:e,matches:r=>r===t,render:()=>t,absentDefault:""}),No=(e,t,r=!1)=>({key:e,matches:n=>n==="true"===t,render:()=>String(t),absentDefault:String(r)}),Ek=(e,t,r=1)=>({key:e,matches:n=>Hy(n,r)===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 Ky(e){return{n:"parameters",a:[],c:Object.keys(e).map(t=>{var r;return{n:(0,Jy.assertXmlName)(t,"Form control parameter name"),a:[],c:[{n:`<${(r=e[t])!==null&&r!==void 0?r:""}`,a:[],c:[]}]}})}}function QX(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 XX(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 Zy(e,t,r){let n=e.c.findIndex(o=>o.node.n==="labels");if(n<0){if(!t||_o(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(QX(e.c[n].node,r)===t)return e;let i=XX(e.c[n].node,t,r);return{...e,c:e.c.map((o,a)=>a===n?{...o,node:i}:o)}}function ZX(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 eZ(e,t){let r=Object.keys(e),n=Object.keys(t);return r.length===n.length&&r.every(i=>e[i]===t[i])}function tZ(e,t){return e.a.some(r=>r[0]===t)?{...e,a:e.a.filter(r=>r[0]!==t)}:e}function rZ(e,t){let r=e.c.findIndex(i=>i.node.n==="parameters");if(r<0){if(Object.keys(t).length===0||_o(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:Ky(t)}]}}if(eZ(ZX(e.c[r].node),t))return e;let n=Ky(t);return{...e,c:e.c.map((i,o)=>o===r?{...i,node:n}:i)}}function zf(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,vt.spliceChildren)(e.w.c,r)};return(0,vt.spliceChildren)(e.c,[a])}let i=n(),o={n:t,a:[],c:r};return e.c.length===0?[...i,o]:(0,vt.spliceChildren)(e.c,[...i,o])}function nZ(e,t){let r=e.tabs.map(n=>iZ(n,t));return{n:"form",a:ba(e.bag,[]),c:e.tabs.length===0&&_o(e.bag)?[]:zf(e.bag,"tabs",r,()=>[])}}function Pk(e,t,r){return t&&!e.c.some(n=>n.node.n==="labels")?[Xy(t,r)]:[]}function iZ(e,t){let r=[So("id",e.id),So("name",e.name),No("expanded",e.expanded),No("visible",e.visible,!0)],n=e.columns.map(o=>oZ(o,t)),i=Zy(e.bag,e.label,t);return{n:"tab",a:ba(i,r),c:zf(i,"columns",n,()=>Pk(i,e.label,t))}}function oZ(e,t){let r=e.width!==void 0?[So("width",e.width)]:[],n=e.sections.map(i=>aZ(i,t));return{n:"column",a:ba(e.bag,r),c:zf(e.bag,"sections",n,()=>[])}}function aZ(e,t){let r=[So("id",e.id),So("name",e.name),No("showlabel",e.showLabel),No("visible",e.visible,!0),{key:"columns",matches:o=>Dk(o)===e.columns,render:()=>zy(e.columns),absentDefault:zy(1)}],n=e.rows.map(o=>sZ(o,t)),i=Zy(e.bag,e.label,t);return{n:"section",a:ba(i,r),c:zf(i,"rows",n,()=>Pk(i,e.label,t))}}function sZ(e,t){let r=e.cells.map(n=>lZ(n,t));return{n:"row",a:ba(e.bag,[]),c:_o(e.bag)?r:(0,vt.assembleChildren)(e.bag,r)}}function lZ(e,t){let r=e.control?e.control.showLabel:Ok(e.bag,"showlabel")==="true",n=[So("id",e.id),No("showlabel",r),No("visible",e.visible,!0),Ek("colspan",e.colspan),Ek("rowspan",e.rowspan)],i=e.control?[uZ(e.control)]:[],o;if(_o(e.bag))o=[...e.control&&e.control.label?[Xy(e.control.label,t)]:[],...i];else{let a=e.control?Zy(e.bag,e.control.label,t):e.bag;o=(0,vt.assembleChildren)(a,i)}return{n:"cell",a:ba(e.bag,n),c:o}}function uZ(e){let t=[So("id",e.id),{key:"classid",matches:i=>Ju(i)===e.classId,render:()=>jy(e.classId||String(rt.ControlClassId.TextboxControl)),absentDefault:""}];e.fieldName!==null&&t.push(So("datafieldname",e.fieldName)),t.push(No("disabled",e.isReadOnly)),t.push(No("isrequired",e.isRequired));let r=e.fieldName===null?tZ(e.bag,"datafieldname"):e.bag,n;return _o(r)?n=Object.keys(e.parameters).length>0?[Ky(e.parameters)]:[]:n=(0,vt.assembleChildren)(rZ(r,e.parameters),[]),{n:"control",a:ba(r,t),c:n}}var cZ={make:(e,t)=>new FX.FormElementNode(e,t),setProp:(e,t,r)=>e.setProperty(t,r),addChild:(e,t)=>e.addChild(t)};function Ak(e,t,r,n){(0,Wy.installDomShim)();let i=fZ(e,r);(0,er.reconcileEmbedDescriptions)(i,n),(0,ii.reconcilePcfDescriptions)(i,n,r?.pcf);let o=(0,vt.rebuildRaw)(nZ(i,t),cZ,null);return new UX.SerializationService(t).serializeFormXmlNode(o)}function dZ(e){return JSON.parse(JSON.stringify(e))}function fZ(e,t){let r=dZ(e);r.bag||(r.bag=(0,vt.emptyBag)()),r.tabs||(r.tabs=[]),wZ(r.bag),t&&pZ(r,t);for(let n of r.tabs)mZ(n);return r}function pZ(e,t){var r;let n=(r=e.entityLogicalName)!==null&&r!==void 0?r:"";eb(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=kk(s.attributeType)))})}function Sk(e){let t=[];return eb(e,r=>t.push(r)),t}function eb(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 mZ(e){e.id||(e.id=Bi.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)hZ(t);e.bag||(e.bag=(0,vt.emptyBag)())}function hZ(e){e.sections||(e.sections=[]);for(let t of e.sections)gZ(t);e.bag||(e.bag=(0,vt.emptyBag)()),e.width===void 0&&_o(e.bag)&&(e.width="100%")}function gZ(e){e.id||(e.id=Bi.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)yZ(t);e.bag||(e.bag=(0,vt.emptyBag)())}function yZ(e){e.cells||(e.cells=[]);for(let t of e.cells)bZ(t);e.bag||(e.bag=(0,vt.emptyBag)())}function bZ(e){(0,er.hasGenPage)(e.control)&&(0,er.applyEmbedCellDefaults)(e),e.id||(e.id=Bi.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&&vZ(e.control),e.bag||(e.bag=(0,vt.emptyBag)())}function vZ(e){var t;(0,er.hasGenPage)(e)&&(0,er.applyEmbedControlDefaults)(e),e.id||(e.id=Bi.Guid.NewGuid()),(e.classId===void 0||e.classId===null)&&(e.classId=String(rt.ControlClassId.TextboxControl)),e.fieldName===void 0&&(e.fieldName=null),e.type===void 0&&(e.type=e.fieldName?"Field":Yy(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,Jy.assertXmlName)(r,"Form control parameter name");e.bag||(e.bag=(0,vt.emptyBag)())}function wZ(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"&&!Nk(o,"handlerUniqueId")&&o.a.push(["handlerUniqueId",jy(Bi.Guid.NewGuid())])}}else if(r.n==="formLibraries")for(let n of r.c)n.n==="Library"&&!Nk(n,"libraryUniqueId")&&n.a.push(["libraryUniqueId",jy(Bi.Guid.NewGuid())])}}var Gf=class{constructor(t=_k.DEFAULT_LCID){this.lcid=t}toArtifact(t,r){var n,i,o;let{tabs:a,bag:s}=Ck(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=VX[t.formType])!==null&&o!==void 0?o:"Main",status:this.readActivationStatus(t),...r!==void 0&&r!==""?{description:r}:{},tabs:a,bag:s};return(0,er.projectGenPageEmbeds)(l),(0,ii.projectPcfBindings)(l),l}fromArtifact(t){var r;return this.deserialize({formxml:Ak(t,this.lcid),formid:t.id||(0,Ks.newId)(),objecttypecode:t.entityLogicalName,type:Vf[t.formType],name:t.name,uniquename:t.name,description:(r=t.description)!==null&&r!==void 0?r:"",formpresentation:bt.FormPresentation.AirForm,formactivationstate:t.status==="Active"?bt.FormActivationState.Active:bt.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,Ks.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,Wy.installDomShim)();let f=vk.ScriptUtilities.ParseXml(c),m=CZ(f),p=this.deserializeDocument(d,f);return EZ(this.toArtifact(p,(l=u.description)!==null&&l!==void 0?l:void 0),m)}toApiPayload(t,r,n){let i=(0,er.genPageEmbedIssues)(t);if(i.length>0)throw new Hs.ValidationError("form",t.id,i);let o=(0,ii.pcfBindingIssues)(t,r,{atPush:!0});if(o.length>0)throw new Hs.ValidationError("form",t.id,o);let a=(0,ii.pcfReadIssues)(t,n?.pcf,r);if(a.unavailable)throw(0,Hs.attachCause)(new Hs.SdkError(a.unavailable.code,a.unavailable.message),a.unavailable.cause);if(a.issues.length>0)throw new Hs.ValidationError("form",t.id,a.issues);return{formxml:Ak(t,this.lcid,n,r),name:t.name,type:Vf[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 eb(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,ii.customControlNeeds)(t,r)}}createDefault(t){var r,n,i,o,a,s,l,u,c,d,f,m;let p=[...(0,er.genPageEmbedIssues)(t),...(0,ii.pcfBindingIssues)(t)];if(p.length>0)throw new Hs.ValidationError("form",t.id||"(new)",p);let h=t.tabs&&t.tabs.length>0?void 0:RZ(this.lcid),g=h!==void 0?h:t.tabs.map(C=>AZ(C,this.lcid)).join(""),b=this.deserialize({formxml:`<form><tabs>${g}</tabs></form>`,formid:t.id||(0,Ks.newId)(),objecttypecode:(r=t.entityLogicalName)!==null&&r!==void 0?r:"",type:Vf[(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:bt.FormPresentation.AirForm,formactivationstate:((s=t.status)!==null&&s!==void 0?s:"Active")==="Active"?bt.FormActivationState.Active:bt.FormActivationState.InActive});(l=b.displayCondition)===null||l===void 0||l.removeProperty(bt.ElementProperties.Order);let w=this.toArtifact(b,t.description);if(t.tabs&&t.tabs.length>0){let C=Sk(t);Sk(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,Ks.assignMissingIds)(t)}completeAsStored(t,r){return(0,qX.completeRecordAsStored)(t,r,this.lcid)}normalize(t){return(0,ii.mintPcfIdentity)((0,er.mintEmbedIdentity)(t))}committed(t,r){var n,i,o,a,s,l;let u=r?.formxml;if(typeof u!="string"||!((0,er.mayCommitEmbedState)(t)||(0,ii.mayCommitPcfState)(t)))return{artifact:t,baseline:t};let c=this.deserialize({formxml:u,formid:t.id||(0,Ks.newId)(),objecttypecode:(n=t.entityLogicalName)!==null&&n!==void 0?n:"",type:Vf[(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:bt.FormPresentation.AirForm,formactivationstate:bt.FormActivationState.Active}),{bag:d}=Ck(c,this.lcid),f=(0,ii.commitPcfState)((0,er.commitEmbedState)(t,(l=(0,er.descriptionsRegion)(d))===null||l===void 0?void 0:l.node),Yy);return{artifact:f,baseline:f}}validate(t){return qZ(t)}deserialize(t){return(0,Wy.installDomShim)(),this.deserializeDocument(t,vk.ScriptUtilities.ParseXml(t.formxml))}deserializeDocument(t,r){let n=new MX.DeserializationService(this.lcid).deSerializeFormXml(r,new Bi.Guid(t.formid),t.objecttypecode,bt.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===bt.FormActivationState.InActive?"Inactive":"Active"}};kr.FormAdapter=Gf;var Rk=["header","footer","DisplayConditions"];function CZ(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&&Rk.includes(i.nodeName)&&n.add(i.nodeName);return n}function EZ(e,t){var r;if(!(!((r=e.bag)===null||r===void 0)&&r.c))return e;let n=Rk.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 Rn(e){return String(e??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function tb(e,t){return e?`<labels><label description="${Rn(e)}" languagecode="${t}" /></labels>`:""}function rb(e){return e&&e.length>0?Ju(e):(0,Ks.newId)()}function AZ(e,t){var r,n,i,o;let a=(r=e.columns)!==null&&r!==void 0?r:[],s=(a.length>0?a:[PZ()]).map(l=>SZ(l,t)).join("");return`<tab id="{${Rn(rb(e.id))}}" name="${Rn((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}">${tb(e.label,t)}<columns>${s}</columns></tab>`}function SZ(e,t){var r,n;let i=((r=e.sections)!==null&&r!==void 0?r:[]).map(o=>NZ(o,t)).join("");return`<column width="${Rn((n=e.width)!==null&&n!==void 0?n:"100%")}"><sections>${i}</sections></column>`}function NZ(e,t){var r,n,i,o,a;let s=((r=e.rows)!==null&&r!==void 0?r:[]).map(l=>_Z(l,t)).join("");return`<section id="{${Rn(rb(e.id))}}" name="${Rn((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="${zy((a=e.columns)!==null&&a!==void 0?a:1)}">${tb(e.label,t)}<rows>${s}</rows></section>`}function _Z(e,t){var r;return`<row>${((r=e.cells)!==null&&r!==void 0?r:[]).map(n=>TZ(n,t)).join("")}</row>`}function TZ(e,t){var r,n,i,o,a;let s=DZ(e),l=s.control,u=l?tb((r=l.label)!==null&&r!==void 0?r:"",t):"",c=l?IZ(l):"";return`<cell id="{${Rn(rb(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 DZ(e){if(!(0,er.hasGenPage)(e.control))return e;let t={...e.control};(0,er.applyEmbedControlDefaults)(t);let r={...e,control:t};return(0,er.applyEmbedCellDefaults)(r),r}function IZ(e){var t,r,n;let i=e.fieldName?` datafieldname="${Rn(e.fieldName)}"`:"",o=OZ(e.parameters),a=e.classId?Ju(e.classId):String(rt.ControlClassId.TextboxControl);return`<control id="${Rn((t=e.id)!==null&&t!==void 0?t:"")}" classid="{${Rn(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 OZ(e){let t=Object.keys(e??{});return t.length===0?"":(t.forEach(n=>(0,Jy.assertXmlName)(n,"Form control parameter name")),`<parameters>${t.map(n=>`<${n}>${Rn(e[n])}</${n}>`).join("")}</parameters>`)}function PZ(){return{width:"100%",sections:[],bag:{a:[],c:[]}}}function RZ(e){return`<tab id="{${Bi.Guid.NewGuid()}}" name="tab_general" expanded="true" visible="true"><labels><label description="General" languagecode="${e}" /></labels><columns><column width="100%"><sections><section id="{${Bi.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 kZ(e=_k.DEFAULT_LCID){return{adapter:new Gf(e),api:BX.formApi,languageSensitive:!0,publish:(t,r,n)=>(0,wk.publishBoundEntity)(t,n),publishScope:(t,r)=>(0,wk.boundEntityPublishScope)(r),rebaselineAfterPublish:"bracket"}}kr.formRegistration=kZ;var LZ=new Set(["id","name","label","expanded","visible","columns","bag"]),$Z=new Set(["id","width","sections","bag"]),xZ=new Set(["id","name","label","visible","showLabel","columns","rows","bag"]),FZ=new Set(["id","cells","bag"]),MZ=new Set(["id","visible","colspan","rowspan","control","bag"]),UZ=new Set(["id","classId","fieldName","type","isRequired","isReadOnly","label","showLabel","parameters","genPage","customControl","bag"]),BZ={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 qZ(e){let t=[];return(0,Rr.childObjects)(e,"tabs","","tab",t).forEach(({node:n,index:i})=>{let o=`/tabs/${i}`;(0,Rr.rejectUnknownKeys)(n,LZ,o,"tab",t),(0,Rr.childObjects)(n,"columns",o,"column",t).forEach(({node:s,index:l})=>{let u=`${o}/columns/${l}`;(0,Rr.rejectUnknownKeys)(s,$Z,u,"column",t),(0,Rr.childObjects)(s,"sections",u,"section",t).forEach(({node:d,index:f})=>{let m=`${u}/sections/${f}`;(0,Rr.rejectUnknownKeys)(d,xZ,m,"section",t),(0,Rr.childObjects)(d,"rows",m,"row",t).forEach(({node:h,index:g})=>{let b=`${m}/rows/${g}`;(0,Rr.rejectUnknownKeys)(h,FZ,b,"row",t),(0,Rr.childObjects)(h,"cells",b,"cell",t).forEach(({node:C,index:S})=>{let O=`${b}/cells/${S}`;(0,Rr.rejectUnknownKeys)(C,MZ,O,"cell",t,BZ);let k=C.control;k!=null&&!(0,Rr.isJsonObject)(k)?t.push((0,Rr.issue)(`${O}/control`,"control-must-be-object-or-null",`a cell control must be a JSON object or null, got ${typeof k}`)):(0,Rr.isJsonObject)(k)&&(0,Rr.rejectUnknownKeys)(k,UZ,`${O}/control`,"control",t)})})})})}),t.push(...(0,er.genPageEmbedIssues)(e)),t.push(...(0,ii.pcfBindingIssues)(e)),t}kr.SUBGRID_CLASS_ID=rt.ControlClassId.SubgridControl;kr.NOTES_CLASS_ID=rt.ControlClassId.TimelineControl;kr.QUICK_VIEW_CLASS_ID=rt.ControlClassId.QuickViewControl;var VZ={Lookup:String(rt.ControlClassId.LookupControl),Customer:String(rt.ControlClassId.LookupControl),Owner:String(rt.ControlClassId.LookupControl),PartyList:String(rt.ControlClassId.PartyListControl),Boolean:String(rt.ControlClassId.BooleanControl),DateTime:String(rt.ControlClassId.DateTimeControl),Decimal:String(rt.ControlClassId.DecimalControl),Double:String(rt.ControlClassId.FloatingNumberControl),Money:String(rt.ControlClassId.CurrencyControl),Integer:String(rt.ControlClassId.IntegerControl),BigInt:String(rt.ControlClassId.IntegerControl),Memo:String(rt.ControlClassId.TextAreaControl),String:String(rt.ControlClassId.TextboxControl)},GZ="3EF39988-22BB-4F0B-BBBE-64B5A3748AEE";function kk(e){return e==="Picklist"||e==="State"||e==="Status"?GZ:e&&VZ[e]||String(rt.ControlClassId.TextboxControl)}kr.classIdForAttributeType=kk;function Nk(e,t){let r=e.a.find(n=>n[0]===t);return r?r[1]:void 0}});var nb=v(Js=>{"use strict";Object.defineProperty(Js,"__esModule",{value:!0});Js.viewApi=Js.findDefaultViews=void 0;var Mk=Lt(),fr=ye(),kn=le(),WZ=ns(),$k="savedqueryid,name,description,fetchxml,layoutxml,querytype,returnedtypecode,isdefault",zZ="savedqueryid,name,returnedtypecode,querytype,isdefault",jZ=60*1e3;function jf(e){return(e.localName||e.nodeName).toLowerCase()}function Yu(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 HZ(e){if(!e)return;let t=!0,r=()=>{t=!1},n=new WZ.DOMParser({errorHandler:{warning:r,error:r,fatalError:r}}).parseFromString(e,"text/xml").documentElement;return t&&n&&jf(n)==="fetch"?n:void 0}function KZ(e){for(let t=e.parentNode;t;t=t.parentNode)if(jf(t)==="link-entity")return!0;return!1}function xk(e,t){var r,n,i;if(((r=e.canbedeleted)===null||r===void 0?void 0:r.Value)!==!1)return!1;let o=HZ(e.fetchxml);if(!o)return!1;let a=Array.from(o.getElementsByTagName("*")),s=a.filter(u=>jf(u)==="condition"),l=s.length===1?s[0]:void 0;return l!==void 0&&a.filter(u=>jf(u)==="link-entity").every(u=>{var c;return((c=Yu(u,"link-type"))===null||c===void 0?void 0:c.toLowerCase())==="outer"})&&!KZ(l)&&Yu(l,"entityname")===void 0&&((n=Yu(l,"attribute"))===null||n===void 0?void 0:n.toLowerCase())==="statecode"&&((i=Yu(l,"operator"))===null||i===void 0?void 0:i.toLowerCase())==="eq"&&Yu(l,"value")===String(t)}function JZ(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 YZ(e){var t,r;let n=e.filter(a=>xk(a,0)),i=e.filter(a=>xk(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:"")))<=jZ&&JZ(a.name,s.name)&&o.push({active:a,inactive:s});return o.length===1?o[0]:void 0}async function QZ(e,t,r={}){var n;let i=new Set(((n=r.excludeViewIds)!==null&&n!==void 0?n:[]).filter(Boolean)),o=`returnedtypecode eq '${(0,kn.odataLiteral)(t)}' and querytype eq 0`,a=`/savedqueries${(0,kn.odataQuery)([["$select","savedqueryid,name,canbedeleted,fetchxml,createdon"],["$filter",o]])}`,s=await(0,Mk.collectPages)(e,a,`findDefaultViews('${t}')`),l=YZ(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:"")}})}Js.findDefaultViews=QZ;async function XZ(e,t){var r;let n=`/EntityDefinitions(LogicalName='${(0,kn.odataPathLiteral)(t)}')${(0,kn.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 Fk(e,t,r){if(!r||!/<grid\b/.test(t)||/<grid[^>]*\bobject=/.test(t))return t;let n=await XZ(e,r);return n===void 0?t:t.replace(/<grid\b/,`<grid object="${n}"`)}Js.viewApi={async get(e,t){let r=(0,kn.normalizeGuid)(t,"id"),n=await(0,fr.readRowEtag)(e,"savedqueries","savedqueryid",r),i=`/savedqueries(${r})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,kn.odataQuery)([["$select",$k]]);return{raw:(0,fr.ensureSuccess)(await e.get(i),e.apiUrl(i)).body,etag:n}},async readContentThenToken(e,t){let r=(0,kn.normalizeGuid)(t,"id"),n=`/savedqueries(${r})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,kn.odataQuery)([["$select",$k]]),i=(0,fr.ensureSuccess)(await e.get(n),e.apiUrl(n)),o=await(0,fr.readRowEtag)(e,"savedqueries","savedqueryid",r);return{raw:i.body,etag:o}},async list(e,t){let r=`/savedqueries${(0,kn.odataQuery)([["$select",zZ],["$filter",t?.entityLogicalName?`returnedtypecode eq '${(0,kn.odataLiteral)(t.entityLogicalName)}'`:void 0]])}`;return(await(0,Mk.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,fr.echoWrite)("savedqueryid"),o=`/savedqueries${i.query}`,a=await Fk(e,n.layoutxml,n.returnedtypecode),s=Object.freeze((0,fr.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,fr.ensureSuccess)(await(0,fr.resendDeadlockVictim)(()=>e.post(o,{...s},i.options)),e.apiUrl(o));return{id:(0,fr.resolveCreatedId)(l,"savedqueryid","view",r),etag:(0,fr.readEtag)(l)}},async update(e,t,r,n){let i=r,o=(0,kn.normalizeGuid)(t,"id"),a=(0,fr.echoWrite)("savedqueryid",{"If-Match":(0,fr.requireEtag)(n,"view",o)}),s=`/savedqueries(${o})${a.query}`,l=await Fk(e,i.layoutxml,i.returnedtypecode),u=(0,fr.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,fr.readEtag)(u)}},delete(e,t){return(0,fr.deleteRecord)(e,"savedqueries",t)}}});var eL=v(Ys=>{"use strict";Object.defineProperty(Ys,"__esModule",{value:!0});Ys.viewRegistration=Ys.ViewAdapter=void 0;var zk=Q(),jr=rn(),ib=so(),va=uo(),Uk=Qr(),ZZ=nb(),ob=lo(),eee=pt(),jk=100,Kf=class{toArtifact(t){var r,n,i,o,a,s,l,u;(0,ob.installDomShim)();let c=(r=t.fetchxml)!==null&&r!==void 0?r:"",d=(n=t.layoutxml)!==null&&n!==void 0?n:"",f=(0,va.parseXmlRoot)(c,"<fetch/>"),m=(0,va.parseXmlRoot)(d,"<grid/>"),p=Kk(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:ree(f),queryType:(l=t.querytype)!==null&&l!==void 0?l:0,isDefault:(u=t.isdefault)!==null&&u!==void 0?u:!1,columns:Hk(m,f),filters:Yk(f),sort:Jk(f),...p.length>0?{linkEntities:p}:{},fetchBag:c?(0,va.projectElementBag)(f):void 0,layoutBag:d?(0,va.projectElementBag)(m):void 0}}fromArtifact(t){(0,ob.installDomShim)();let{fetchxml:r,layoutxml:n}=Bk(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,ob.installDomShim)();let{fetchxml:s,layoutxml:l}=Bk(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,eee.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,jr.childObjects)(n,"columns","","column",r),(0,jr.childObjects)(n,"sort","","sort",r),(0,jr.childObjects)(n,"linkEntities","","linkEntity",r),tee(n.linkEntities,r);let i=n.filters;return i!=null&&((0,jr.isJsonObject)(i)?ab(i,"/filters",r):r.push((0,jr.issue)("/filters","filters-must-be-object",`filters must be a JSON object, got ${typeof i}`))),r}};Ys.ViewAdapter=Kf;function tee(e,t){Array.isArray(e)&&e.forEach((r,n)=>{if(!(0,jr.isJsonObject)(r))return;for(let o of["name","from","to"]){let a=r[o];(typeof a!="string"||a.trim()==="")&&t.push((0,jr.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,jr.isJsonObject)(i)?ab(i,`/linkEntities/${n}/filters`,t):t.push((0,jr.issue)(`/linkEntities/${n}/filters`,"filters-must-be-object",`filters must be a JSON object, got ${typeof i}`)))})}function ab(e,t,r){(0,jr.childObjects)(e,"conditions",t,"condition",r),(0,jr.childObjects)(e,"groups",t,"filterGroup",r).forEach(({node:i,index:o})=>ab(i,`${t}/groups/${o}`,r))}function ree(e){var t;let r=e.getElementsByTagName("entity")[0];return(t=r?.getAttribute("name"))!==null&&t!==void 0?t:""}function Hk(e,t){var r;let n=Jf(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)?jk: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 Jf(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 Kk(e){let t=e.getElementsByTagName("entity")[0];if(!t)return[];let r=[];for(let n of Mt(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=Mt(n,"filter").find(c=>!Yf(c));r.push({name:i,from:o,to:a,...s?{alias:s}:{},...l==="inner"||l==="outer"?{linkType:l}:{},...u?{filters:sb(u)}:{}})}return r}function Jk(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=Mt(t,"filter").filter(i=>!Yf(i)).map(sb);return n.length===0?r:n.length===1?n[0]:{type:"and",conditions:[],groups:n}}function Yf(e){if(e.getAttribute("isquickfindfields")==="1"||Qk(e))return!0;if(Mt(e,"filter").length>0)return!1;let t=Mt(e,"condition");return t.length===0?!1:t.some(r=>r.getAttribute("isquickfindfields")==="1"||Mt(r,"value").length>0||iee(r))}function Qk(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"?Qk(n):n.tagName!=="condition"))return!0}return!1}var nee=new Set(["attribute","operator","value","entityname","uiname","uitype"]);function iee(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&&!nee.has(i))return!0}return!1}function sb(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(sb(l))}return{type:n,conditions:i,groups:o}}function Mt(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 lb=e=>{var t,r;return`${(t=e.relatedEntity)!==null&&t!==void 0?t:""}::${(r=e.sourceAttribute)!==null&&r!==void 0?r:e.name}`};function oee(e,t){let r=Jf(e),n=new Map;for(let i of t){if(!i.relatedEntity)continue;let o=r.get(i.name);if(o){let a=lb(i),s=n.get(a);s?s.push(o.link):n.set(a,[o.link])}}return n}function aee(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(lb(s));return!!l&&l.some(u=>!i.has(u))});if(a.length!==0)throw new zk.ValidationError("view",e.id,a.map(s=>(0,jr.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 Bk(e){var t,r;let n=see(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(!qk(e.fetchBag)||!qk(e.layoutBag))return{fetchxml:wee({...e,columns:n,sort:i,filters:o}),layoutxml:Cee({...e,columns:n},`${e.entityLogicalName}id`)};let a=new DOMParser().parseFromString("<root/>","text/xml"),s=Vk(e.fetchBag,"fetch",a),l=Vk(e.layoutBag,"grid",a),u=Hk(l,s),c=!Hf(n,u),d=!Hf(i,Jk(s)),f=!Hf(o,Yk(s)),m=e.linkEntities,p=m!==void 0&&!Hf(m,Kk(s)),h=p?oee(s,u):void 0;return p&&yee(a,s,m),p&&(vee(e,s,n,h),aee(e,s,n,h)),c?(Gk(a,s,n,u),fee(a,l,n)):p&&Gk(a,s,n,u),d&&hee(a,s,i),f&&gee(a,s,o),{fetchxml:(0,va.serializeNode)(s),layoutxml:(0,va.serializeNode)(l)}}function see(e){return(e??[]).map((t,r)=>{var n,i;return{name:String(t.name).toLowerCase(),width:(n=t.width)!==null&&n!==void 0?n:jk,order:(i=t.order)!==null&&i!==void 0?i:r,...t.relatedEntity?{relatedEntity:t.relatedEntity}:{},...t.sourceAttribute?{sourceAttribute:String(t.sourceAttribute).toLowerCase()}:{}}})}function qk(e){return!!e&&(e.c.length>0||e.a.length>0)}function Vk(e,t,r){let n={n:t,a:(0,ib.mergeAttrs)(e.a,[]),c:(0,ib.spliceChildren)(e.c,[])};return(0,ib.rebuildRaw)(n,(0,va.domEngine)(r),null)}function Gk(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=Jf(t);for(let p of n)u.has(l(p))||(uee(s,p),p.relatedEntity&&c.has(p.name)&&lee((i=d.get(p.name))===null||i===void 0?void 0:i.link,p.name));let f=Jf(t),m=new Set(Mt(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||!Zk(s,p.relatedEntity)))continue;let g=cee(e,s,p.relatedEntity),b=e.createElement("attribute");Xk(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),dee(s,h),m.add(p.name)}}function Xk(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 lee(e,t){if(e){for(let r of Mt(e,"attribute"))if((r.getAttribute("alias")||r.getAttribute("name"))===t){e.removeChild(r);return}}}function uee(e,t){if(t.relatedEntity){for(let r of Mt(e,"link-entity"))if(!(r.getAttribute("alias")!==t.relatedEntity&&r.getAttribute("name")!==t.relatedEntity)){for(let n of Mt(r,"attribute"))if((n.getAttribute("alias")||n.getAttribute("name"))===t.name){r.removeChild(n);return}}return}for(let r of Mt(e,"attribute"))if(r.getAttribute("name")===t.name){e.removeChild(r);return}}function Zk(e,t,r=!1){let n=o=>o.getAttribute("alias")===t||o.getAttribute("name")===t;for(let o of Mt(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 cee(e,t,r){let n=Zk(t,r);if(n)return n;let i=e.createElement("link-entity");return i.setAttribute("name",r),t.appendChild(i),i}function dee(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 fee(e,t,r){let n=t.getElementsByTagName("row")[0];if(!n)return;let i=[...r].sort((s,l)=>s.order-l.order),o=pee(n);if(mee(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 pee(e){return Mt(e,"cell").filter(t=>!!t.getAttribute("name")&&t.getAttribute("ishidden")!=="1")}function mee(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 hee(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 Mt(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 gee(e,t,r){let n=t.getElementsByTagName("entity")[0];if(n){for(let i of Mt(n,"filter"))Yf(i)||n.removeChild(i);(r.conditions.length>0||r.groups.length>0)&&n.appendChild(Qu(e,r))}}function Hf(e,t){return JSON.stringify(e)===JSON.stringify(t)}function yee(e,t,r){var n;let i=t.getElementsByTagName("entity")[0];if(!i)return;let o=Mt(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){Wk(e,g,p);return}let b=e.createElement("link-entity");Wk(e,b,p),i.appendChild(b)});for(let p of o)l.has(p)||i.removeChild(p)}var bee=new Set(["inner","outer"]);function vee(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(lb(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 zk.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,jr.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 Wk(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):bee.has(t.getAttribute("link-type")||"")&&t.removeAttribute("link-type");let n=Mt(t,"filter").find(o=>!Yf(o)),i=r.filters&&(r.filters.conditions.length>0||r.filters.groups.length>0)?Qu(e,r.filters):null;n&&i?t.replaceChild(i,n):n?t.removeChild(n):i&&t.appendChild(i)}function wee(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(Qu(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){Xk(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(Qu(r,e.filters)),new XMLSerializer().serializeToString(r)}function Qu(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(Qu(e,n));return r}function Cee(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 Eee(){return{adapter:new Kf,api:ZZ.viewApi,publish:(e,t,r)=>(0,Uk.publishBoundEntity)(e,r),publishScope:(e,t)=>(0,Uk.boundEntityPublishScope)(t),rebaselineAfterPublish:"bracket"}}Ys.viewRegistration=Eee});function Qf(e,t){return e==="SetFieldValue"&&t!==void 0&&Aee.has(t.attributeType)&&(t.requiredLevel==="None"||t.requiredLevel==="Recommended")}var Aee,ub=L(()=>{"use strict";Aee=new Set(["Integer","Double","Decimal","Money","String","Memo","DateTime","Picklist","Lookup"])});function tL(e){return e!=="Entity"&&e!=="AllForms"&&typeof e=="string"&&e.trim()!==""}function cb(e){return e==="AllForms"||tL(e)?1:2}function db(e){return tL(e)?e:null}function rL(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:Qs.WorkflowCategory.BusinessRule,type:Qs.WorkflowTypeCode.Definition,mode:1,scope:Qs.WorkflowScope.Organization,primaryentity:e.entityLogicalName,iscrmuiworkflow:!0,processtriggerscope:cb(e.scope),processtriggerformid:db(e.scope)}}var Qs,nL=L(()=>{"use strict";Qs=Ae(Qi());});function iL(e,t=0){return(Ut[e[t+0]]+Ut[e[t+1]]+Ut[e[t+2]]+Ut[e[t+3]]+"-"+Ut[e[t+4]]+Ut[e[t+5]]+"-"+Ut[e[t+6]]+Ut[e[t+7]]+"-"+Ut[e[t+8]]+Ut[e[t+9]]+"-"+Ut[e[t+10]]+Ut[e[t+11]]+Ut[e[t+12]]+Ut[e[t+13]]+Ut[e[t+14]]+Ut[e[t+15]]).toLowerCase()}var Ut,oL=L(()=>{Ut=[];for(let e=0;e<256;++e)Ut.push((e+256).toString(16).slice(1))});function fb(){return Xf>Zf.length-16&&((0,aL.randomFillSync)(Zf),Xf=0),Zf.slice(Xf,Xf+=16)}var aL,Zf,Xf,sL=L(()=>{aL=require("crypto"),Zf=new Uint8Array(256),Xf=Zf.length});var lL,pb,uL=L(()=>{lL=require("crypto"),pb={randomUUID:lL.randomUUID}});function See(e,t,r){if(pb.randomUUID&&!t&&!e)return pb.randomUUID();e=e||{};let n=e.random??e.rng?.()??fb();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 iL(n)}var pr,cL=L(()=>{uL();sL();oL();pr=See});var mb=L(()=>{cL()});var dL=L(()=>{"use strict";});function fL(e){return e!=null&&Nee.has(e)}function ep(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 Nee,hb=L(()=>{"use strict";Nee=new Set(["Picklist","State","Status"])});var tp=v(pn=>{"use strict";Object.defineProperty(pn,"__esModule",{value:!0});pn.WorkflowConditionOperator=pn.WorkflowAttributeType=pn.SystemStep=pn.FieldRequiredLevelTypes=pn.AttributeDateTimeBehavior=void 0;pn.AttributeDateTimeBehavior={None:0,Dynamic:1,DateOnly:2,StaticTimeZoneInvariant:3,UserLocal:4};pn.FieldRequiredLevelTypes={None:"0",Required:"1",Recommended:"2"};pn.SystemStep={IdentifyContact:"IdentifyContact",IdentifyAccount:"IdentifyAccount",IdentifyCustomer:"IdentifyCustomer",IdentifyCase:"IdentifyCase",Solution:"Solution",Resolve:"Resolve"};pn.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"};pn.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 rp(e){return e!=null&&mL.includes(e)}function gb(e){return e===oe.WorkflowAttributeType.Integer}function yb(e,t){return t===oe.WorkflowConditionOperator.Equal||t===oe.WorkflowConditionOperator.NotEqual?e:_ee.includes(t)?mL.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 hL(e){let t=e.leftWorkflowType??e.valueWorkflowType??oe.WorkflowAttributeType.String,r=Xu[e.operator]??oe.WorkflowConditionOperator.Equal;return yb(t,r)}function gL(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||!pL.test(o)||!pL.test(a)||o.length>1&&o.startsWith("0")||o.length>Tee?!1:t!==oe.WorkflowAttributeType.Integer||i.length===1}var oe,Xu,mL,_ee,pL,Tee,bb=L(()=>{"use strict";oe=Ae(tp());Xu={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},mL=[oe.WorkflowAttributeType.Decimal,oe.WorkflowAttributeType.Float,oe.WorkflowAttributeType.Integer,oe.WorkflowAttributeType.Money],_ee=[oe.WorkflowConditionOperator.GreaterThan,oe.WorkflowConditionOperator.GreaterThanOrEqual,oe.WorkflowConditionOperator.LessThan,oe.WorkflowConditionOperator.LessThanOrEqual];pL=/^\d*$/,Tee=28});var yL=L(()=>{"use strict";});function Ln(e){return!Dee.has(e)}function vb(e){return e==="Equals"||e==="DoesNotEqual"}function np(e){return vL.has(e)?Iee:Lee.has(e)?Oee:wL.has(e)?Pee:xee.has(e)?kee:Ree}function CL(e){return np(e)[0]}function EL(e,t){return np(t).includes(e)}function bL(e){return vL.has(e)?"string":e==="Money"?"money":e==="Integer"||e==="BigInt"?"integer":e==="Decimal"||e==="Double"?"decimal":wL.has(e)?"date":$ee.has(e)?"boolean":"other"}function ip(e,t){let r=bL(e),n=bL(t);return r==="other"||n==="other"?e===t:r===n}var Dee,Iee,Oee,Pee,Ree,kee,vL,Lee,wL,$ee,xee,op=L(()=>{"use strict";yL();Dee=new Set(["ContainsData","DoesNotContainData"]);Iee=["Equals","DoesNotEqual","Contains","DoesNotContain","BeginsWith","DoesNotBeginWith","EndsWith","DoesNotEndWith","ContainsData","DoesNotContainData"],Oee=["Equals","DoesNotEqual","IsGreaterThan","IsGreaterThanEqualTo","IsLessThan","IsLessThanEqualTo","ContainsData","DoesNotContainData"],Pee=["On","NotOn","Equals","DoesNotEqual","IsGreaterThan","IsGreaterThanEqualTo","IsLessThan","IsLessThanEqualTo","ContainsData","DoesNotContainData"],Ree=["Equals","DoesNotEqual","ContainsData","DoesNotContainData"],kee=["Equals","DoesNotEqual","Contains","DoesNotContain","BeginsWith","DoesNotBeginWith","EndsWith","DoesNotEndWith","ContainsData","DoesNotContainData"],vL=new Set(["String","Memo","EntityName"]),Lee=new Set(["Integer","BigInt","Money","Decimal","Double"]),wL=new Set(["DateTime"]),$ee=new Set(["Boolean"]),xee=new Set(["Lookup","Owner","Customer"])});function _L(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 kL(e){return e&&e!==Fe.WorkflowAttributeType.String?e:void 0}function Uee(e){return{__class:RL,parameterName:"primaryEntity",entityName:e}}function AL(e){return{__class:Cb,type:wb,typeSet:!1,behavior:Fe.AttributeDateTimeBehavior.None,method:TL,parameters:[e]}}function SL(e,t,r=Fe.WorkflowAttributeType.String){return{__class:IL,type:r,behavior:Fe.AttributeDateTimeBehavior.None,typeSet:!1,entity:Uee(t),attributeName:e}}function Bee(e,t=Fe.WorkflowAttributeType.String){return{__class:OL,type:t,behavior:Fe.AttributeDateTimeBehavior.None,typeSet:!1,primitiveValue:e}}function qee(e){return{__class:PL,type:wb,typeSet:!1,behavior:Fe.AttributeDateTimeBehavior.None,days:e,hours:"0",minutes:"0",months:"0",years:"0"}}function LL(e,t){let r=Fee[e.operator],n=AL(SL(e.leftField,t,e.leftWorkflowType)),i;e.dateArithmetic?i=qee(e.right.value??"0"):e.right.kind==="field"?i=SL(e.right.field??"",t,e.right.workflowType):i=Bee(e.right.value??"",e.right.workflowType??e.leftWorkflowType);let o=AL(i);return{__class:Cb,type:wb,typeSet:!1,behavior:Fe.AttributeDateTimeBehavior.None,method:DL,parameters:[r,n,o]}}function $L(e){return typeof e=="object"&&e.__class===Cb}function Vee(e){return typeof e=="object"&&e.__class===PL}function ap(e){return $L(e)&&e.method===TL&&e.parameters.length>0?ap(e.parameters[0]):e}function NL(e){if(typeof e!="object"||e.__class!==IL)return null;let t=e.entity;if(t&&t.__class&&t.__class!==RL)return null;let r=e.attributeName;return r?{field:r,workflowType:kL(e.type)}:null}function xL(e){if(!e)return null;let t=ap(e);if(!$L(t)||t.method!==DL||t.parameters.length!==3)return null;let r=t.parameters[0],n=Mee[String(r)];if(!n)return null;let i=NL(ap(t.parameters[1]));if(!i)return null;let o=ap(t.parameters[2]);if(Vee(o))return n!=="+"&&n!=="-"?null:{leftField:i.field,leftWorkflowType:i.workflowType,operator:n,right:{kind:"value",value:String(o.days??"")},dateArithmetic:!0};let a=NL(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===OL){let s=o.primitiveValue;return{leftField:i.field,leftWorkflowType:i.workflowType,operator:n,right:{kind:"value",value:s!=null?String(s):"",workflowType:kL(o.type)}}}return null}function Ab(e){let t=(e??"").trim();if(!/^\d+$/.test(t))return!1;let r=Number(t);return Number.isSafeInteger(r)&&r>=Eb&&r<=Xs}function wa(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&&!Ab(t)?"invalidDayCount":null}function Zs(e){return wa(e)===null}var Fe,TL,DL,wb,IL,OL,Cb,PL,RL,Fee,Mee,Eb,Xs,Zu=L(()=>{"use strict";Fe=Ae(tp());op();TL="0",DL="3",wb="0",IL="EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions",OL="PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions",Cb="MethodCallExpression:#Microsoft.Crm.Workflow.Expressions",PL="TimeSpanExpression:#Microsoft.Crm.Workflow.Expressions",RL="PrimaryEntity:#Microsoft.Crm.Workflow.Expressions";Fee={"+":0,"-":1,"*":2,"/":3},Mee={0:"+",1:"-",2:"*",3:"/"};Eb=0,Xs=2147483647});function Wee(e){return e.startsWith("__")&&!Gee.has(e)}function zee(e){let t=Object.create(null);return Object.keys(e).forEach(r=>{Wee(r)&&(t[r]=e[r])}),Object.keys(t).length>0?t:void 0}function YL(e){return e.__class==="BinaryExpression:#Microsoft.Crm.Workflow.Expressions"}function Ea(e){return e.__class==="UnaryExpression:#Microsoft.Crm.Workflow.Expressions"}function sp(e){return YL(e)||Ea(e)}function jee(e){return e.__class==="ConditionBranchStep:#Microsoft.Crm.Workflow.ObjectModel"}function ec(){return{list:[]}}function Sb(e,t,r){return e&&e.list.length>0?{list:[{...e.list[0],description:t},...e.list.slice(1)]}:{list:[{labelId:pr(),languageCode:r,description:t}]}}function _b(e){return{__class:"PrimaryEntity:#Microsoft.Crm.Workflow.Expressions",parameterName:"primaryEntity",entityName:e}}function dp(e,t,r,n=j.AttributeDateTimeBehavior.None){return{__class:"EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions",type:r,behavior:n,typeSet:!1,entity:_b(t),attributeName:e}}function Ca(e,t,r=j.AttributeDateTimeBehavior.None){return{__class:"PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions",type:t,behavior:r,typeSet:!1,primitiveValue:e}}function Jee(e){return e.bpfField==="StageCategory"?e.stageType==="SelectedStage"?ZL:XL:QL}function e1(e){return e.bpfField==="StageCategory"?j.WorkflowAttributeType.BpfStageCategory:j.WorkflowAttributeType.BpfProcess}function Yee(e,t){let r=e1(e),n=e.bpfField==="StageCategory"?{__class:"EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions",type:r,behavior:j.AttributeDateTimeBehavior.None,typeSet:!1,entity:{__class:"RelatedEntity:#Microsoft.Crm.Workflow.Expressions",parameterName:`related_${ML}_${FL}`,entityName:FL,relatedAttributeName:ML},attributeName:Kee}:dp(Hee,t,r);return{__class:"MethodCallExpression:#Microsoft.Crm.Workflow.Expressions",type:r,behavior:j.AttributeDateTimeBehavior.None,typeSet:!1,method:Ib,parameters:[Jee(e),n]}}function t1(e){let t=e;if(t.__class!=="MethodCallExpression:#Microsoft.Crm.Workflow.Expressions"||String(t.method)!==Ib)return null;let r=(t.parameters??[])[0];if(typeof r!="string")return null;let n=r.replace(/^"+|"+$/g,"");return n===XL?{bpfField:"StageCategory",stageType:"ActiveStage"}:n===ZL?{bpfField:"StageCategory",stageType:"SelectedStage"}:n===QL?{bpfField:"ProcessName"}:null}function lp(e){if(!e)return!1;let t=e;if(t.__class==="MethodCallExpression:#Microsoft.Crm.Workflow.Expressions"&&String(t.method)===Ib){let r=(t.parameters??[])[0];if(typeof r=="string"&&Qee.has(r.replace(/^"+|"+$/g,"")))return!0}return Ea(e)?lp(e.operand):YL(e)?lp(e.left)||(e.right??[]).some(lp):!1}function r1(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 Xee(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 UL(e){if(!e)return!1;switch(e.__class){case"EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions":return r1(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 Zee(e){let t=Db[e.conditionOperatoroperator];if(!t)return!1;let r=t==="ContainsData"||t==="DoesNotContainData";if(Ea(e))return r&&BL(e.operand,!0);let n=e.right??[];return n.length!==(r?0:1)?!1:BL(e.left,r,n[0])}function BL(e,t,r){return t1(e)||r1(e)?t||UL(r):!1}function Tb(e){if(!e||!sp(e))return!1;let t=e.conditionOperatoroperator;if(!Ea(e)&&(t===j.WorkflowConditionOperator.LogicalAnd||t===j.WorkflowConditionOperator.LogicalOr)){let r=e.right??[];return r.length>0&&Tb(e.left)&&r.every(Tb)}return Zee(e)}function qL(e){return!e||Xee(e)?!1:lp(e)||!Tb(e)}function n1(e){return{__class:"LookupExpression:#Microsoft.Crm.Workflow.Expressions",type:e.workflowType??j.WorkflowAttributeType.Lookup,behavior:j.AttributeDateTimeBehavior.None,typeSet:!1,entityType:e.entityType,label:e.label??"",staticValue:Ca(e.id.replace(/[{}]/g,""),j.WorkflowAttributeType.UniqueIdentifier)}}function tte(e){return e===j.WorkflowAttributeType.DateTime?j.AttributeDateTimeBehavior.DateOnly:j.AttributeDateTimeBehavior.None}function rte(e,t){if(t!==j.WorkflowAttributeType.DateTime)return j.AttributeDateTimeBehavior.None;let r=e.leftDateTimeBehavior;return r!==void 0&&r!==j.AttributeDateTimeBehavior.None?r:tte(t)}function nte(e,t,r){if(t!==j.WorkflowAttributeType.DateTime)return j.AttributeDateTimeBehavior.None;let n=e.valueFieldDateTimeBehavior;return n!==void 0&&n!==j.AttributeDateTimeBehavior.None?n:r}function ote(e){let t=e.trim().toLowerCase();if(t==="true"||t==="1")return"1";if(t==="false"||t==="0")return"0"}function pte(e){let t=fte.exec(e);if(t)return`${t[1]}T${t[2]}`;let r=dte.exec(e);if(!r)return;let[,n,i,o,a,s,l]=r,u=cte.indexOf(i.toLowerCase());if(u<0)return;let c=String(u+1).padStart(2,"0");return`${o}-${c}-${n}T${a}:${s}:${l}`}function mte(e){let t=pte(e.trim());return t!==void 0&&i1(t)?t:e}function i1(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(!ate.test(i)||o.length>0&&!ste.test(o)&&!lte.test(o)&&!ute.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 hte(e,t){let r={value:e,type:j.WorkflowAttributeType.String};if(t===j.WorkflowAttributeType.String||ite.includes(t)||e.trim().length===0)return r;if(t===j.WorkflowAttributeType.Boolean){let n=ote(e);return n==null?r:{value:n,type:t}}return ete.includes(t)?ep(e)?{value:e.trim(),type:t}:r:rp(t)?{value:e.trim(),type:t}:t===j.WorkflowAttributeType.DateTime&&i1(e)?{value:e.trim(),type:t}:r}function VL(e){return e==="ContainsData"||e==="DoesNotContainData"}function GL(e){return gte.has(e)}function WL(e,t){return{__class:"UnaryExpression:#Microsoft.Crm.Workflow.Expressions",type:j.WorkflowAttributeType.Boolean,behavior:j.AttributeDateTimeBehavior.None,typeSet:!1,conditionOperatoroperator:t,operand:e}}function zL(e,t){let r=e.leftWorkflowType??e.valueWorkflowType??j.WorkflowAttributeType.String,n=Xu[e.operator]??j.WorkflowConditionOperator.Equal,i=rte(e,r),o=yb(r,n);if(e.source==="BusinessProcess"){let l=Yee(e,t);if(VL(e.operator))return WL(l,n);let u=e1(e);return{__class:"BinaryExpression:#Microsoft.Crm.Workflow.Expressions",type:j.WorkflowAttributeType.Boolean,behavior:j.AttributeDateTimeBehavior.None,typeSet:!1,conditionOperatoroperator:n,left:l,right:[Ca(e.value??"",u)]}}let a=dp(e.field,t,r,i);if(VL(e.operator))return WL(a,n);let s;if(e.valueType==="Field"&&e.valueField){let l=GL(o)&&GL(e.valueFieldWorkflowType??"")?e.valueFieldWorkflowType:o;s=[dp(e.valueField,t,l,nte(e,l,i))]}else if(e.valueType==="Lookup"){if(!e.lookupValue)throw new Error("Lookup condition is missing its record value.");s=[n1(e.lookupValue)]}else if(e.valueType==="Clear")s=[Ca(null,j.WorkflowAttributeType.String,i)];else if(e.valueType==="Expression")s=[cp(e.valueType,e.value,e.valueField,t,e.expression,e.rawExpression)];else{let l=hte(e.value??"",o);s=[Ca(l.value,l.type,i)]}return{__class:"BinaryExpression:#Microsoft.Crm.Workflow.Expressions",type:j.WorkflowAttributeType.Boolean,behavior:j.AttributeDateTimeBehavior.None,typeSet:!1,conditionOperatoroperator:n,left:a,right:s}}function yte(){return Ca(!0,j.WorkflowAttributeType.Boolean)}function bte(e,t,r){if(e.length===0)return null;let n=zL(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:j.WorkflowAttributeType.Boolean,behavior:j.AttributeDateTimeBehavior.None,typeSet:!1,conditionOperatoroperator:o==="AND"?j.WorkflowConditionOperator.LogicalAnd:j.WorkflowConditionOperator.LogicalOr,left:n,right:[zL(e[i],r)]}}return n}function up(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===j.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===j.WorkflowAttributeType.DateTime?{valueType:"Value",value:mte(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!==j.WorkflowAttributeType.Lookup?{workflowType:e.type}:{}}}}if(e.__class==="MethodCallExpression:#Microsoft.Crm.Workflow.Expressions"){let t=xL(e);return t?{valueType:"Expression",expression:t}:{valueType:"Expression",rawExpression:e}}return{valueType:"Value",value:""}}function vte(e){let t=Db[e.conditionOperatoroperator]??"Equals",r=t==="ContainsData"||t==="DoesNotContainData",n=Ea(e)?e.operand:e.left,i=Ea(e)?[]:e.right??[],o=t1(n);if(o){let g=i[0];return{id:pr(),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"}:up(i[0]),c=l,d=a&&n.type===j.WorkflowAttributeType.DateTime&&n.behavior!==j.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===j.WorkflowAttributeType.DateTime&&m.behavior!==j.AttributeDateTimeBehavior.None?m.behavior:void 0;return{id:pr(),field:s,fieldDisplayName:s,operator:t,...u,...f?{valueWorkflowType:f}:{},...c?{leftWorkflowType:c}:{},...d!==void 0?{leftDateTimeBehavior:d}:{},...h!==void 0?{valueFieldDateTimeBehavior:h}:{}}}function jL(e){if(!e||!sp(e))return{clauses:[],logic:"AND"};let t=[],r=(o,a)=>{let s=o.conditionOperatoroperator;if(Ea(o)||s!==j.WorkflowConditionOperator.LogicalAnd&&s!==j.WorkflowConditionOperator.LogicalOr){t.push({...vte(o),...a?{connector:a}:{}});return}let l=s===j.WorkflowConditionOperator.LogicalAnd?"AND":"OR";sp(o.left)&&r(o.left,a),(o.right??[]).filter(sp).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 cp(e,t,r,n,i,o,a,s){if(e==="Field"&&r)return dp(r,n,j.WorkflowAttributeType.String);if(e==="Expression"){if(i)return LL(i,n);if(o!=null)return o}return e==="Lookup"&&a?n1(a):e==="Clear"?Ca(null,s??j.WorkflowAttributeType.String):Ca(t??"",j.WorkflowAttributeType.String)}function Nb(e,t){return{propertyName:e,propertyValueExpr:t}}function el(e){return`Step_${e.value++}`}function mn(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 HL(e,t,r){return e&&!r.used.has(e)?(r.used.add(e),e):mn(t,r)}function wte(e){return e===JL.StateCode.Activated?"Active":"Draft"}function Cte(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 Ete(e,t){let r=e.processtriggerscope,n=e.processtriggerformid;return r===1?n&&n.trim()!==""?n:"AllForms":r===2?"Entity":t??"Entity"}function o1(e,t=1033){return new tl({languageCode:t}).serialize(e)}function a1(e){return new tl().deserialize(e)}var JL,j,Gee,Db,Ib,QL,XL,ZL,Hee,Kee,FL,ML,Qee,ete,ite,ate,ste,lte,ute,cte,dte,fte,gte,Ob,tl,Pb=L(()=>{"use strict";mb();JL=Ae(Qi());dL();hb();bb();Zu();j=Ae(tp());Gee=new Set(["__class"]);Db={};for(let e of Object.keys(Xu))Db[Xu[e]]=e;Ib="23",QL="BpfProcess",XL="ActiveStageCategory",ZL="SelectedStageCategory",Hee="processid",Kee="stagecategory",FL="processstage",ML="stageid";Qee=new Set(["ActiveStage","SelectedStage","Stage"]);ete=[j.WorkflowAttributeType.Picklist,j.WorkflowAttributeType.State,j.WorkflowAttributeType.Status];ite=[j.WorkflowAttributeType.Lookup,j.WorkflowAttributeType.Customer,j.WorkflowAttributeType.Owner];ate=/^\d{4}-\d{2}-\d{2}$/,ste=/^\d{2}:\d{2}$/,lte=/^\d{2}:\d{2}:\d{2}$/,ute=/^\d{2}:\d{2}:\d{2}\.\d{1,7}$/,cte=["jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"],dte=/^[A-Za-z]{3}, (\d{2}) ([A-Za-z]{3}) (\d{4}) (\d{2}):(\d{2}):(\d{2}) GMT$/,fte=/^(\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$/;gte=new Set([j.WorkflowAttributeType.Lookup,j.WorkflowAttributeType.Owner,j.WorkflowAttributeType.Customer]);Ob={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"};tl=class{resolveLabel;languageCode;entityName="";stepCounter={value:0};idCounter={counts:{},used:new Set};constructor(t={}){this.resolveLabel=t.resolveLabel??(r=>Ob[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??pr(),name:r?.name??"Step_0",description:r!==void 0?r.description:t.description||null,stepLabels:ec(),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:mn("SetAttributeValueStep",this.idCounter),description:t.displayName||"New Action",name:t.stepName??el(this.stepCounter),stepLabels:{list:[]},specification:Nb(t.field,cp(t.valueType,t.value,t.valueField,this.entityName,t.expression,t.rawExpression,t.lookupValue,t.valueWorkflowType)),entity:_b(this.entityName)}}makeRecommendationActionStep(t,r,n){let i=r.map(l=>this.makeApplyActionStep(l)),o=t??"",a=n?.stepLabels,s=Sb(a,o,this.languageCode);return{__class:"ActionStep:#Microsoft.Crm.Workflow.ObjectModel",id:HL(n?.id,"ActionStep",this.idCounter),name:n?.name??el(this.stepCounter),description:n?.description??"Action step",stepLabels:s,steps:{list:i},actionId:null,actionType:n?.actionType??"4",processId:n?.processId??pr(),uniqueName:n?.uniqueName??`id_${pr().replace(/-/g,"")}ActionStep`}}serializeAction(t){let r=_b(this.entityName),n=t.stepName??el(this.stepCounter),i=t.stepLabels??ec(),o={name:n,stepLabels:i,description:t.displayName},a=t.type;switch(a){case"SetFieldValue":return{...o,id:mn("SetAttributeValueStep",this.idCounter),__class:"SetAttributeValueStep:#Microsoft.Crm.Workflow.ObjectModel",entity:r,specification:Nb(t.field,cp(t.valueType,t.value,t.valueField,this.entityName,t.expression,t.rawExpression,t.lookupValue,t.valueWorkflowType))};case"SetDefaultValue":return{...o,id:mn("SetDefaultValueStep",this.idCounter),__class:"SetDefaultValueStep:#Microsoft.Crm.Workflow.ObjectModel",entity:r,specification:Nb(t.field,cp(t.valueType,t.value,t.valueField,this.entityName,t.expression,t.rawExpression,t.lookupValue,t.valueWorkflowType))};case"LockUnlock":return{...o,id:mn("SetDisplayModeStep",this.idCounter),__class:"SetDisplayModeStep:#Microsoft.Crm.Workflow.ObjectModel",controlId:t.field,controlType:"standard",isReadOnly:t.lock,entity:r};case"SetBusinessRequired":return{...o,id:mn("SetFieldRequiredLevelStep",this.idCounter),__class:"SetFieldRequiredLevelStep:#Microsoft.Crm.Workflow.ObjectModel",controlId:t.field,controlType:"standard",requiredLevel:t.required?j.FieldRequiredLevelTypes.Required:j.FieldRequiredLevelTypes.None,entity:r};case"SetVisibility":return{...o,id:mn("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=Sb(t.stepLabels,s,this.languageCode);return{...o,id:mn("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=Sb(t.stepLabels,s,this.languageCode),u={list:[this.makeRecommendationActionStep(t.acceptanceText,t.applyActions??[],t.recommendationActionStepMeta)]};return{...o,id:mn("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??el(this.stepCounter),n=mn("ConditionStep",this.idCounter),i=[],o=t,a=!0;for(;o;){let s=o.rawConditionExpression??bte(o.clauses,o.logic,this.entityName),l=a?o.branchName??el(this.stepCounter):el(this.stepCounter),c={__class:"ConditionBranchStep:#Microsoft.Crm.Workflow.ObjectModel",id:a?HL(o.branchId,"ConditionBranchStep",this.idCounter):mn("ConditionBranchStep",this.idCounter),name:l,description:o.displayName,stepLabels:ec(),conditionExpression:s??(a?yte():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:ec(),containsElsebranch:i.length>1,steps:{list:i}}}makeTerminalElseBranch(t){return{__class:"ConditionBranchStep:#Microsoft.Crm.Workflow.ObjectModel",id:mn("ConditionBranchStep",this.idCounter),name:"Else",description:null,stepLabels:ec(),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??pr():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:zee(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:Ete(r,i?.formId),status:wte(t.statecode),rootCondition:n,wfomRoot:i,...Cte(t)}}deserializeConditionStep(t){let r=(t.steps?.list??[]).filter(jee);return this.buildConditionNodeFromBranches(r,t,!0)}buildConditionNodeFromBranches(t,r,n){let[i,...o]=t,{clauses:a,logic:s}=jL(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)??pr(),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,...qL(i?.conditionExpression)?{rawConditionExpression:i?.conditionExpression}:{}}}deserializeElseChain(t,r){if(t.length===0)return[];let[n]=t,{clauses:i}=jL(n.conditionExpression);return i.length===0&&!qL(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||pr(),field:u?.propertyName??"",stepName:l.name??void 0,displayName:l.description??void 0,...up(u?.propertyValueExpr)}}),meta:i,acceptanceText:a}}deserializeAction(t){switch(t.__class){case"SetAttributeValueStep:#Microsoft.Crm.Workflow.ObjectModel":{let r=up(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=up(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!==j.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 s1=L(()=>{"use strict";});function Tte(e){return typeof e=="object"&&e!==null?e:null}function rl(e){let t=Tte(e);if(!t)return!1;if(t.__class===Nte){let r=t;return String(r.method)===_te?!0:Array.isArray(r.parameters)&&r.parameters.some(rl)}if(t.__class===Ste)return rl(t.operand);if(t.__class===Ate){let r=t;return rl(r.left)||Array.isArray(r.right)&&r.right.some(rl)}return!1}var Ate,Ste,Nte,_te,l1=L(()=>{"use strict";s1();Ate="BinaryExpression:#Microsoft.Crm.Workflow.Expressions",Ste="UnaryExpression:#Microsoft.Crm.Workflow.Expressions",Nte="MethodCallExpression:#Microsoft.Crm.Workflow.Expressions",_te="23"});function $b(e){return Dte.has(e.type)}function Rb(e,t,r,n,i,o,a){let s=i.get(r);!s||!d1.has(s.attributeType)||n!=="Value"||a?.operator&&!vb(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 Ite(e,t){let r=t.get(e.field);return!!r&&d1.has(r.attributeType)&&vb(e.operator)}function kb(e){return!!(e?.entityType?.trim()&&e.id?.trim())}function Lb(e,t,r){return{nodeId:e,kind:"INVALID_DAY_COUNT",message:`Please enter a whole number of days between 0 and ${Xs}.`,target:t,itemId:r,messageKey:"Validation.InvalidDayCount",messageParams:{max:Xs}}}function u1(e,t,r,n,i,o,a,s){if(i!=="Clear")return;let l=o.get(n);Qf(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 pp(e){if(!e)return!1;for(let t of[...e.trueBranch,...e.falseBranch])if(t.kind==="action"){if($b(t))return!0}else if(pp(t))return!0;return!1}function xb(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=xb(r,t);if(n)return n}}return null}function Ote(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 Pte(e){return e.clauses.length===0&&(e.rawConditionExpression===void 0||Ote(e.rawConditionExpression))}function kte(e){return!!e.clauses?.some(t=>t.source==="BusinessProcess")||rl(e.rawConditionExpression)}function nl(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=nl(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=nl(n,t);if(i)return i}}return null}function Fb(e,t){return{...e,trueBranch:c1(e.trueBranch,t),falseBranch:c1(e.falseBranch,t)}}function c1(e,t){return e.filter(r=>r.id!==t).map(r=>r.kind==="condition"?Fb(r,t):r)}function To(e,t,r){return e.id===t?r(e):{...e,trueBranch:e.trueBranch.map(n=>n.kind==="condition"?To(n,t,r):n),falseBranch:e.falseBranch.map(n=>n.kind==="condition"?To(n,t,r):n)}}function fp(e,t,r){return{...e,trueBranch:e.trueBranch.map(n=>n.kind==="action"&&n.id===t?r(n):n.kind==="condition"?fp(n,t,r):n),falseBranch:e.falseBranch.map(n=>n.kind==="action"&&n.id===t?r(n):n.kind==="condition"?fp(n,t,r):n)}}function f1(e,t,r,n){return To(e,t,i=>({...i,trueBranch:r==="true"?[...i.trueBranch,n]:i.trueBranch,falseBranch:r==="false"?[...i.falseBranch,n]:i.falseBranch}))}function Mb(e){return e.length===1&&e[0].kind==="condition"}function $te(e){let t=0,r=e??void 0;for(;r;){t+=1;let{falseBranch:n}=r;if(Mb(n)){r=n[0];continue}n.length>0&&(t+=1),r=void 0}return t}function xte(e){return!!e&&$te(e)<Lte}function Fte(e,t){if(!e)return;let r=(n,i)=>{if(n.id===t)return i;let o=[];if(Mb(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 p1(e,t,r){let n=Fte(e,t);return!n||!xte(n)?e:To(e,t,i=>m1(i,r))}function m1(e,t){if(Mb(e.falseBranch))return{...e,falseBranch:[m1(e.falseBranch[0],t)]};let r=Ub(t);return r.falseBranch=e.falseBranch,{...e,falseBranch:[r]}}function h1(e,t){let r=nl(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 To(e,r.node.id,o=>({...o,falseBranch:i}))}function g1(e,t,r){let n=nl(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 To(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 Ub(e){return{kind:"condition",id:pr(),displayName:e??"New Condition",clauses:[],logic:"AND",trueBranch:[],falseBranch:[],isCollapsed:!1}}function y1(e,t){let r={kind:"action",id:pr(),type:e,displayName:t??`New ${e}`};switch(e){case"Recommendation":return{...r,type:"Recommendation",field:"",recommendationTitle:"",messageText:"",applyActions:[{id:pr(),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 b1(e){if(!e)return[];let t=[];return v1(e,t),[...new Set(t)]}function v1(e,t){e.clauses.forEach(r=>{r.field&&t.push(r.field)}),[...e.trueBranch,...e.falseBranch].forEach(r=>{r.kind==="condition"?v1(r,t):"field"in r&&r.field&&t.push(r.field)})}function w1(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 E1(e,n,i,!0),r==="Entity"&&C1(e,n),pp(e)||n.push({nodeId:"root",kind:"NO_ACTION",message:"A business rule must include at least one action step.",target:"node"}),n}function C1(e,t){kte(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"&&C1(r,t)})}function E1(e,t,r,n=!1){let i=n&&Pte(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?wa(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(Ln(a.operator)&&a.valueType==="Value"&&!a.value&&!Ite(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(Ln(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 Ln(a.operator)&&a.valueType==="Expression"&&!a.rawExpression&&!Zs(a.expression)?t.push(s==="invalidDayCount"?Lb(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"}):Ln(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"});Ln(a.operator)&&a.valueType==="Value"&&a.value&&fL(r.get(a.field)?.attributeType)&&!ep(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=hL(a);Ln(a.operator)&&a.valueType==="Value"&&a.value&&rp(l)&&!gL(a.value,l)&&t.push({nodeId:e.id,kind:"INVALID_CLAUSE_NUMERIC_VALUE",message:gb(l)?"Please enter a whole number for this clause.":"Please enter a valid number for this clause.",target:"clauseValue",itemId:a.id,messageKey:gb(l)?"Validation.InvalidClauseWholeNumberValue":"Validation.InvalidClauseNumericValue"}),Ln(a.operator)&&a.valueType==="Lookup"&&(kb(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"})),Ln(a.operator)&&Rb(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"&&Rte.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")E1(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&&!ip(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:wa(a.expression);!a.rawExpression&&!Zs(a.expression)&&t.push(s==="invalidDayCount"?Lb(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"&&!kb(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&&(Rb(a.id,a.type,a.field,a.valueType,r,t,{target:"actionValue"}),u1(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:wa(l.expression);!l.rawExpression&&!Zs(l.expression)&&t.push(u==="invalidDayCount"?Lb(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"?kb(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&&(Rb(a.id,"Recommendation",l.field,l.valueType,r,t,{target:"applyActionValue",itemId:l.id}),u1(a.id,"Recommendation","SetFieldValue",l.field,l.valueType,r,t,{target:"applyActionValue",itemId:l.id}))})}}})}var Dte,d1,Rte,Lte,Bb=L(()=>{"use strict";mb();ub();op();Zu();l1();bb();hb();Dte=new Set(["LockUnlock","ShowErrorMessage","Recommendation","SetFieldValue","SetDefaultValue","SetBusinessRequired","SetVisibility"]);d1=new Set(["Lookup","Customer","Owner"]);Rte=new Set(["SetFieldValue","ShowErrorMessage","Recommendation"]);Lte=10});var A1={};Jr(A1,{DAY_COUNT_MAX:()=>Xs,DAY_COUNT_MIN:()=>Eb,DEFAULT_DESERIALIZE_LABELS:()=>Ob,WorkflowJsonMapper:()=>tl,addElseIfInTree:()=>p1,appendToBranch:()=>f1,areFieldKindsCompatible:()=>ip,attributeTypeToWorkflowType:()=>_L,buildWorkflowEntity:()=>rL,collectUsedFields:()=>b1,createEmptyAction:()=>y1,createEmptyCondition:()=>Ub,deserializeWorkflowJson:()=>a1,findNode:()=>xb,findParent:()=>nl,getDefaultOperatorForFieldType:()=>CL,getExpressionModelIssue:()=>wa,getOperatorsForFieldType:()=>np,hasAnyTriggerGeneratingAction:()=>pp,isDayCountValid:()=>Ab,isExpressionModelComplete:()=>Zs,isOperatorCompatible:()=>EL,isTriggerGeneratingAction:()=>$b,moveBranchItemInTree:()=>g1,operatorNeedsValue:()=>Ln,processTriggerFormIdFromScope:()=>db,processTriggerScopeFromScope:()=>cb,removeElseIfInTree:()=>h1,removeNodeFromTree:()=>Fb,serializeToWorkflowJson:()=>o1,supportsClearForActionType:()=>Qf,updateActionInTree:()=>fp,updateConditionInTree:()=>To,validateBusinessRule:()=>w1});var S1=L(()=>{"use strict";ub();nL();Pb();Pb();Bb();Bb();op();Zu();Zu();});var qb=v(mp=>{"use strict";Object.defineProperty(mp,"__esModule",{value:!0});mp.cloneJson=void 0;function Mte(e){return JSON.parse(JSON.stringify(e))}mp.cloneJson=Mte});var x1=v(Do=>{"use strict";Object.defineProperty(Do,"__esModule",{value:!0});Do.BUSINESS_RULE_NULL_GUID=Do.businessRuleRegistration=Do.BusinessRuleAdapter=void 0;var N1=pt(),tc=(S1(),Br(A1)),_1=Qr(),T1=Q(),Ute=qb(),oi=rn(),Bte=Fm(),qte=pt(),Vte=Jo(),Gte=new Set(["ShowErrorMessage","Recommendation"]);function P1(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)?P1(n):Gte.has(String(n.type))):!1}function Wte(e){return R1((0,Ute.cloneJson)(e))}function R1(e){var t,r;let n=i=>(i??[]).map(o=>zte(o)?R1(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 zte(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 jte(e){var t;if(e===null||typeof e!="object"||Array.isArray(e))throw new T1.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 T1.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 Hte="00000000-0000-0000-0000-000000000000";Do.BUSINESS_RULE_NULL_GUID=Hte;var Kte=new Set(["Recommendation","LockUnlock","ShowErrorMessage","SetFieldValue","SetDefaultValue","SetBusinessRequired","SetVisibility"]),Jte=["ruleId","name","description","entityLogicalName","scope","status","rootCondition"],Yte=["kind","id","displayName","logic","clauses","trueBranch","falseBranch"],Qte=["id","field","fieldDisplayName","operator","valueType","value","valueField","lookupValue","expression","rawExpression","valueWorkflowType"];function $n(e,t){return e===void 0?t:{...e,...t}}var Aa=["kind","id","type","displayName","field","stepName","stepLabels"],D1=["valueType","valueWorkflowType","value","valueField","lookupValue","expression","rawExpression"],Xte={Recommendation:[...Aa,"recommendationTitle","messageText","acceptanceText","applyActions","recommendationActionStepMeta"],LockUnlock:[...Aa,"lock"],ShowErrorMessage:[...Aa,"errorMessage","messageLevel","messageActionSteps"],SetFieldValue:[...Aa,...D1],SetDefaultValue:[...Aa,...D1],SetBusinessRequired:[...Aa,"required"],SetVisibility:[...Aa,"visible"]};function ne(e,t){return t===void 0?{}:{[e]:t}}function k1(e){var t;return e==null?void 0:{...e,label:(t=e.label)!==null&&t!==void 0?t:""}}function Vb(e){return{valueType:e.valueType,...ne("valueWorkflowType",e.valueWorkflowType),...ne("value",e.value),...ne("valueField",e.valueField),...ne("lookupValue",k1(e.lookupValue)),...ne("expression",e.expression),...ne("rawExpression",e.rawExpression)}}function L1(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 Zte=["id","field","valueType","valueWorkflowType","value","valueField","lookupValue","expression","rawExpression","stepName","displayName"];function ere(e){return $n(e.bag,{id:e.id,field:e.field,...Vb(e),...ne("stepName",e.stepName),...ne("displayName",e.displayName)})}function tre(e){let t=L1(e,Zte);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 I1(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 O1(e){throw new Error(`Unsupported business-rule action type: ${e.type}`)}var rre=new Set(["INVALID_CLEAR_FOR_FIELD","INVALID_VALUE_TYPE_FOR_FIELD","CLAUSE_VALUE_TOO_LONG","ACTION_VALUE_TOO_LONG"]),nre=new Set,ire="INVALID_CLEAR_FOR_FIELD";function ore(e){let t=n=>{var i;return(0,oi.isJsonObject)(n)&&(n.label===""||n.label===void 0)?{...n,label:String((i=n.id)!==null&&i!==void 0?i:"")}:n},r=n=>{if(!(0,oi.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 hp=class{toArtifact(t){let r=this.residualBag(t,Jte),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 $n(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,tc.deserializeWorkflowJson)(i);return this.toArtifact(o)}needsBaseLanguage(t){return P1(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,tc.serializeToWorkflowJson)(a,(i=n?.baseLanguageCode)!==null&&i!==void 0?i:Vte.DEFAULT_LCID),l=(o=a.ruleId)!==null&&o!==void 0?o:(0,N1.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,tc.createEmptyCondition)():t.rootCondition===null?null:this.conditionFromJson(Wte(jte(t.rootCondition)))},u=this.toArtifact(l);return u.id||(u.id=(0,N1.newId)()),u}assignMissingIds(t){return(0,qte.assignMissingIds)(t)}validate(t){let r=[],n=t.rootCondition;return n==null?r:(0,oi.isJsonObject)(n)?($1(n,"/rootCondition",r),r):(r.push((0,oi.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,oi.issue)("/rootCondition","rule-not-representable",a instanceof Error?a.message:String(a))]}let i=n.rootCondition===null?null:ore(n.rootCondition),o;return r.length===0?o=rre:r.some(a=>a.requiredLevel!==void 0)?o=nre:o=new Set([ire]),(0,tc.validateBusinessRule)(i,r).filter(a=>!o.has(a.kind)).map(a=>(0,oi.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 L1(t,r)}buildWorkflowEntity(t,r){return(0,tc.buildWorkflowEntity)(t,r)}conditionToJson(t){let r=this.residualBag(t,Yte),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,Qte),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,Xte[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(tre),...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",...I1(t)};case"SetDefaultValue":return{...n,type:"SetDefaultValue",...I1(t)};case"SetBusinessRequired":return{...n,type:"SetBusinessRequired",required:t.required};case"SetVisibility":return{...n,type:"SetVisibility",visible:t.visible};default:return O1(t)}}conditionFromJson(t){var r;let n=(r=t.bag)!==null&&r!==void 0?r:{};return $n(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 $n(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",k1(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(!Kte.has(t.type))throw new Error(`Unsupported business-rule action type: ${t.type}`);sre(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 $n(t.bag,{...r,type:"Recommendation",recommendationTitle:t.recommendationTitle,messageText:t.messageText,...ne("acceptanceText",t.acceptanceText),applyActions:t.applyActions.map(ere),...ne("recommendationActionStepMeta",t.recommendationActionStepMeta)});case"LockUnlock":return $n(t.bag,{...r,type:"LockUnlock",lock:t.lock});case"ShowErrorMessage":return $n(t.bag,{...r,type:"ShowErrorMessage",errorMessage:t.errorMessage,...ne("messageLevel",t.messageLevel),...ne("messageActionSteps",t.messageActionSteps)});case"SetFieldValue":return $n(t.bag,{...r,type:"SetFieldValue",...Vb(t)});case"SetDefaultValue":return $n(t.bag,{...r,type:"SetDefaultValue",...Vb(t)});case"SetBusinessRequired":return $n(t.bag,{...r,type:"SetBusinessRequired",required:t.required});case"SetVisibility":return $n(t.bag,{...r,type:"SetVisibility",visible:t.visible});default:return O1(t)}}isConditionJson(t){return Object.prototype.hasOwnProperty.call(t,"clauses")&&Object.prototype.hasOwnProperty.call(t,"logic")&&!Object.prototype.hasOwnProperty.call(t,"type")}};Do.BusinessRuleAdapter=hp;function $1(e,t,r){(0,oi.optionalEnum)(e,"logic",["AND","OR"],t,"condition-logic-invalid",r),(0,oi.childObjects)(e,"clauses",t,"clause",r);for(let n of["trueBranch","falseBranch"])(0,oi.childObjects)(e,n,t,"branchItem",r).forEach(({node:o,index:a})=>{"clauses"in o||"trueBranch"in o||"falseBranch"in o?$1(o,`${t}/${n}/${a}`,r):are(o,`${t}/${n}/${a}`,r)})}function are(e,t,r){e.type==="SetDefaultValue"&&e.valueType==="Clear"&&r.push((0,oi.issue)(`${t}/valueType`,"clear-only-set-field-value","Clear is only supported for SetFieldValue actions."))}function sre(e){if(e.type==="SetDefaultValue"&&e.valueType==="Clear")throw new Error("Clear is only supported for SetFieldValue actions.")}function lre(){return{adapter:new hp,api:Bte.businessRuleApi,publish:(e,t,r)=>(0,_1.publishBoundEntity)(e,r),publishScope:(e,t)=>(0,_1.boundEntityPublishScope)(t)}}Do.businessRuleRegistration=lre});var e$=v(Io=>{"use strict";Object.defineProperty(Io,"__esModule",{value:!0});Io.appRegistration=Io.AppAdapter=Io.HEADER_NAV_BOOLEAN_RULE=void 0;var qi=rn(),Ot=so(),ic=uo(),ure=Qr(),j1=zd(),Gb=Fd(),Wb=lo(),cre=pt(),dre=le(),H1=Jo(),K1=Q(),J1=Ud();Object.defineProperty(Io,"HEADER_NAV_BOOLEAN_RULE",{enumerable:!0,get:function(){return J1.HEADER_NAV_BOOLEAN_RULE}});var vp="7.0.0.0",F1=`<SiteMap IntroducedVersion="${vp}"></SiteMap>`,M1="/_imgs/imagestrips/transparent_spacer.gif",U1="/_imgs/TableIconsFluentV9/document_one_page_sparkle.svg",Y1=["Entity","Url","DefaultDashboard","Page","GenPageId"],rc="sitemapId",B1="sitemapName",zb="sitemapNameUnique",q1="aiDescription",V1="[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}",fre=new RegExp(`^(?:\\{${V1}\\}|${V1})$`);function G1(e,t){if(!fre.test(e.trim()))throw new K1.ValidationError("app",t,[{pointer:"/sitemapId",rule:"app-sitemapid-guid",message:`sitemapId must be a GUID; received '${e}'.`}]);return e.trim()}function W1(e,t,r){if(e===void 0)return r;if(typeof e!="boolean")throw new K1.ValidationError("app",t,[Q1(e)]);return e}function Q1(e){return(0,qi.issue)("/headerAndNavigationRefresh",J1.HEADER_NAV_BOOLEAN_RULE,`headerAndNavigationRefresh must be a boolean, got ${typeof e}`)}function pre(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,dre.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 mre(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 wp=class{constructor(t=H1.DEFAULT_LCID){this.lcid=t}toArtifact(t){let{bag:r,modeledEls:n}=gp(t,"Area");return{id:"",name:"",uniqueName:"",description:"",siteMap:{areas:n.map(i=>this.areaToJson(i)),bag:r},bag:(0,Ot.emptyBag)()}}fromArtifact(t){(0,Wb.installDomShim)();let r=this.assignMissingIds(JSON.parse(JSON.stringify(t))),n=new DOMParser().parseFromString("<root/>","text/xml"),i=this.rootToRaw(r);return(0,Ot.rebuildRaw)(i,(0,ic.domEngine)(n),null)}fromApiResponse(t){var r,n,i,o,a,s,l,u,c,d,f;(0,Wb.installDomShim)();let m=t??{},p=(r=m.$sitemap)!==null&&r!==void 0?r:m,h=(0,ic.parseXmlRoot)((n=p.sitemapxml)!==null&&n!==void 0?n:F1,F1),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:[[rc,(u=(l=p.sitemapid)!==null&&l!==void 0?l:m._sitemapid_value)!==null&&u!==void 0?u:""],[B1,(c=p.sitemapname)!==null&&c!==void 0?c:""],[zb,(d=p.sitemapnameunique)!==null&&d!==void 0?d:""],[q1,(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,Wb.installDomShim)();let w=(0,ic.serializeNode)(this.fromArtifact(t)),C=[],S=[];for(let k of(i=(n=t.siteMap)===null||n===void 0?void 0:n.areas)!==null&&i!==void 0?i:[])for(let I of(o=k.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,Ot.emptyBag)();return{sitemapId:nc(O,rc)||(t.sitemapId?G1(t.sitemapId,t.id):""),sitemapxml:w,sitemapname:nc(O,B1)||t.name,...nc(O,zb)?{sitemapNameUnique:nc(O,zb)}:{},appModuleId:t.id,appModuleName:t.name,appModuleDescription:t.description,...t.aiDescription!==void 0&&t.aiDescription!==(r?r.aiDescription:nc(O,q1))?{appModuleAiDescription:t.aiDescription}:{},appModuleUniqueName:t.uniqueName,...t.iconWebResourceId?{iconWebResourceId:t.iconWebResourceId}:{},...t.headerAndNavigationRefresh===void 0?{}:{appSettings:{[Gb.HEADER_AND_NAVIGATION_REFRESH]:W1(t.headerAndNavigationRefresh,(l=t.id)!==null&&l!==void 0?l:"(unknown)",!0)?Gb.APP_SETTING_ON:Gb.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,cre.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:G1(t.sitemapId,u)}:{},...t.iconWebResourceId?{iconWebResourceId:t.iconWebResourceId}:{},headerAndNavigationRefresh:W1(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(Kb):Array.isArray(r.areas)?r.areas.forEach(Kb):Array.isArray(r.groups)?Kb(r):Array.isArray(r.subAreas)?Z1(r):"type"in r&&Cp(r,"subarea"),t}validate(t){let r=[],n=t.published;n!==void 0&&typeof n!="boolean"&&r.push((0,qi.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(Q1(o)),i==null)return r;if(!(0,qi.isJsonObject)(i))return r.push((0,qi.issue)("/siteMap","sitemap-must-be-object",`siteMap must be a JSON object, got ${typeof i}`)),r;let a=(0,qi.childObjects)(i,"areas","/siteMap","area",r),s=new Map;return a.forEach(({node:l,index:u})=>{let c=`/siteMap/areas/${u}`;(0,qi.childObjects)(l,"groups",c,"group",r).forEach(({node:f,index:m})=>{let p=`${c}/groups/${m}`;(0,qi.childObjects)(f,"subAreas",p,"subArea",r).forEach(({node:g,index:b})=>{let w=`${p}/subAreas/${b}`;(0,qi.optionalEnum)(g,"type",["Entity","URL","DashBoard","CustomPage","GenPage"],w,"subarea-type-invalid",r);let C=pre(g);if(!C)return;let S=s.get(C);if(S===void 0){s.set(C,w);return}r.push((0,qi.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,j1.mainFormSetShapeIssues)((r=t.components)===null||r===void 0?void 0:r.mainFormsByTable,mre(t))}applyServerIdentity(t,r){let n=r[rc];if(!n)return;t.bag||(t.bag=(0,Ot.emptyBag)());let i=t.bag.a.find(o=>o[0]===rc);i?i[1]=n:t.bag.a.push([rc,n])}areaToJson(t){var r;let{bag:n,modeledEls:i}=gp(t,"Group"),o={id:(r=t.getAttribute("Id"))!==null&&r!==void 0?r:"",title:jb(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}=gp(t,"SubArea");return{id:(r=t.getAttribute("Id"))!==null&&r!==void 0?r:"",title:jb(t,this.lcid),subAreas:i.map(o=>this.subAreaToJson(o)),bag:n}}subAreaToJson(t){var r;let{bag:n}=gp(t,null),i=hre(t),o={id:(r=t.getAttribute("Id"))!==null&&r!==void 0?r:"",type:i,title:jb(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!==M1&&(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,Ot.emptyBag)(),l=yp(a)?[["IntroducedVersion",vp]]:[],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,Ot.mergeAttrs)(a.a,l),c:(0,Ot.spliceChildren)(a.c,u)}}areaToRaw(t){var r,n;let i=(r=t.bag)!==null&&r!==void 0?r:(0,Ot.emptyBag)(),o=yp(i),a=[],s=[];t.id&&a.push(["Id",t.id]),o&&a.push(["ShowGroups","true"],["ResourceId","SitemapDesigner.NewTitle"],["DescriptionResourceId","SitemapDesigner.NewTitle"],["IntroducedVersion",vp]),t.icon!==void 0?a.push(["Icon",t.icon]):bp(i.a,"Icon")&&s.push("Icon"),t.vectorIcon!==void 0?a.push(["VectorIcon",t.vectorIcon]):bp(i.a,"VectorIcon")&&s.push("VectorIcon");let l=((n=t.groups)!==null&&n!==void 0?n:[]).map(c=>this.groupToRaw(c)),u=Hb((0,Ot.spliceChildren)(i.c,l),t.title,o,this.lcid);return{n:"Area",a:(0,Ot.mergeAttrs)(i.a,a,s),c:u}}groupToRaw(t){var r,n;let i=(r=t.bag)!==null&&r!==void 0?r:(0,Ot.emptyBag)(),o=yp(i),a=[];t.id&&a.push(["Id",t.id]),o&&a.push(["ResourceId","SitemapDesigner.NewGroup"],["DescriptionResourceId","SitemapDesigner.NewGroup"],["ToolTipResourseId","SitemapDesigner.Unknown"],["IntroducedVersion",vp],["IsProfile","false"]);let s=((n=t.subAreas)!==null&&n!==void 0?n:[]).map(u=>this.subAreaToRaw(u)),l=Hb((0,Ot.spliceChildren)(i.c,s),t.title,o,this.lcid);return{n:"Group",a:(0,Ot.mergeAttrs)(i.a,a),c:l}}subAreaToRaw(t){var r;let n=(r=t.bag)!==null&&r!==void 0?r:(0,Ot.emptyBag)(),i=yp(n),o=yre(n.a,t.type),a=[],s=[];t.id&&a.push(["Id",t.id]);let l=!i&&!n.a.some(([c])=>Y1.includes(c));vre(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]):bp(o,"Icon",M1)&&s.push("Icon"),t.vectorIcon!==void 0?a.push(["VectorIcon",t.vectorIcon]):bp(o,"VectorIcon")?t.type==="GenPage"?a.push(["VectorIcon",U1]):s.push("VectorIcon"):t.type==="GenPage"&&!gre(o,"VectorIcon")&&a.push(["VectorIcon",U1]);let u=Hb((0,Ot.spliceChildren)(n.c,[]),t.title,i,this.lcid);return{n:"SubArea",a:(0,Ot.mergeAttrs)(o,a,s),c:u}}};Io.AppAdapter=wp;function gp(e,t){let r=(0,ic.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,Ot.rawFromNode)((0,ic.nodeLikeFromDom)(l))}),a+=1)}return{bag:{a:r,c:n},modeledEls:i}}function z1(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 jb(e,t){var r;let n=z1(e,"Titles")[0];if(!n)return"";let o=z1(n,"Title").find(a=>a.getAttribute("LCID")===String(t));return o&&(r=o.getAttribute("Title"))!==null&&r!==void 0?r:""}function hre(e){return e.getAttribute("GenPageId")?"GenPage":e.getAttribute("Entity")?"Entity":e.getAttribute("Page")?"CustomPage":e.getAttribute("DefaultDashboard")?"DashBoard":"URL"}function yp(e){return e.a.length===0&&e.c.length===0}function gre(e,t){return e.some(([r])=>r===t)}function bp(e,t,r){let n=e.find(([o])=>o===t),i=n?.[1];return!!i&&i!==r}function nc(e,t){let r=e.a.find(([n])=>n===t);return r?r[1]:void 0}function yre(e,t){let r=bre(t);return e.filter(([n])=>!Y1.includes(n)||r.has(n)).map(n=>[n[0],n[1]])}function bre(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 vre(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 Hb(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]=wre(e[i],t,n),o}return r?[Cre(t,n),...e]:e}function wre(e,t,r){let n=!1,i=e.c.map(o=>!n&&o.n==="Title"&&Ere(o,"LCID")===String(r)?(n=!0,{n:o.n,a:(0,Ot.mergeAttrs)(o.a,[["Title",t]]),c:o.c}):o);return n||i.unshift(X1(t,r)),{n:e.n,a:e.a.map(o=>[o[0],o[1]]),c:i}}function Cre(e,t){return{n:"Titles",a:[],c:[X1(e,t)]}}function X1(e,t){return{n:"Title",a:[["LCID",String(t)],["Title",e]],c:[]}}function Ere(e,t){let r=e.a.find(([n])=>n===t);return r?r[1]:void 0}function Are(e){let t="0123456789abcdef",r="";for(let n=0;n<e;n+=1)r+=t[Math.floor(Math.random()*t.length)];return r}function Cp(e,t){e&&(typeof e.id!="string"||e.id.length===0)&&(e.id=`${t}_${Are(8)}`)}function Kb(e){var t;Cp(e,"area");for(let r of(t=e.groups)!==null&&t!==void 0?t:[])Z1(r)}function Z1(e){var t;Cp(e,"group");for(let r of(t=e.subAreas)!==null&&t!==void 0?t:[])Cp(r,"subarea")}function Sre(e=H1.DEFAULT_LCID){return{adapter:new wp(e),api:j1.appApi,languageSensitive:!0,publish:(t,r)=>(0,ure.publishAppModule)(t,r),publishScope:t=>({envelope:"appmodule",targetIds:[t]}),rebaselineAfterPublish:"bracket"}}Io.appRegistration=Sre});var t$={};Jr(t$,{ActionType:()=>Yb,AppActionOrigin:()=>iv,AppActionVisibilityType:()=>nv,ButtonType:()=>Xb,CannotUpdateAppActionColumns:()=>Nre,Context:()=>ev,IconType:()=>Qb,Location:()=>Zb,OnClickEventType:()=>rv,Scope:()=>tv,VisibilityType:()=>Jb});var Jb,Yb,Qb,Xb,Zb,ev,tv,rv,nv,iv,Nre,r$=L(()=>{"use strict";(function(e){e[e.NotSupported=0]="NotSupported",e[e.Show=1]="Show",e[e.ClassicRules=2]="ClassicRules",e[e.Expression=3]="Expression"})(Jb||(Jb={}));(function(e){e[e.NotSupported=0]="NotSupported",e[e.None=1]="None",e[e.JavaScript=2]="JavaScript",e[e.Expression=3]="Expression"})(Yb||(Yb={}));(function(e){e[e.NoIcon=0]="NoIcon",e[e.UseIcon=1]="UseIcon",e[e.UseWebResource=2]="UseWebResource"})(Qb||(Qb={}));(function(e){e[e.Standard=0]="Standard",e[e.Dropdown=1]="Dropdown",e[e.Split=2]="Split",e[e.Group=3]="Group"})(Xb||(Xb={}));(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"})(Zb||(Zb={}));(function(e){e[e.All=0]="All",e[e.Entity=1]="Entity"})(ev||(ev={}));(function(e){e[e.App=0]="App",e[e.Entity=1]="Entity",e[e.Global=2]="Global"})(tv||(tv={}));(function(e){e[e.None=0]="None",e[e.Formula=1]="Formula",e[e.JavaScript=2]="JavaScript"})(rv||(rv={}));(function(e){e[e.None=0]="None",e[e.Formula=1]="Formula",e[e.ClassicRules=2]="ClassicRules"})(nv||(nv={}));(function(e){e[e.Default=0]="Default",e[e.Migrated=1]="Migrated",e[e.MigratedClone=2]="MigratedClone"})(iv||(iv={}));Nre=["appactionid","appmoduleid","context","contextvalue","location","name","type","uniquename","isdisabled","origin"]});var u$=v(Pt=>{"use strict";Object.defineProperty(Pt,"__esModule",{value:!0});Pt.assertOneWritePerRow=Pt.commandApi=Pt.COMMAND_DUPLICATE_ROW_CODE=Pt.COMMAND_ROW_NOT_IN_BAR_CODE=Pt.COMMAND_TABLE_MISMATCH_CODE=void 0;var ov=Lt(),Lr=ye(),Vi=Q(),$r=le();Pt.COMMAND_TABLE_MISMATCH_CODE="COMMAND_TABLE_MISMATCH";Pt.COMMAND_ROW_NOT_IN_BAR_CODE="COMMAND_ROW_NOT_IN_BAR";Pt.COMMAND_DUPLICATE_ROW_CODE="COMMAND_DUPLICATE_ROW";var _re="OnClickEventJavaScriptWebResourceId($select=name,webresourceid),IconWebResourceId($select=name,webresourceid)";async function av(e,t){let r=`/EntityDefinitions(LogicalName='${(0,$r.odataPathLiteral)(t)}')${(0,$r.odataQuery)([["$select","MetadataId"]])}`,i=(0,Lr.ensureSuccess)(await e.get(r),e.apiUrl(r)).body,o=i?.MetadataId;return o?(0,$r.normalizeGuid)(o,"entityMetadataId"):""}function sv(e,t){return t?`_contextentity_value eq ${t}`:`contextvalue eq '${(0,$r.odataLiteral)(e)}'`}function oc(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 n$(e,t){let r=e.entityLogicalName;if(t===void 0)return r;if(typeof r!="string"||r.toLowerCase()!==t.toLowerCase())throw new Vi.SdkError(Pt.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 i$(e,t,r){let n=await av(e,t);if(r){let i=(0,$r.normalizeGuid)(r,"entityMetadataId");if(i!==n)throw new Vi.SdkError(Pt.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. `+oc(t))}return n}Pt.commandApi={async get(e,t){let r=t,n=await av(e,r),i=sv(r,n),o=`/appactions${(0,$r.odataQuery)([["$expand",_re],["$filter",i]])}`,a,s=await(0,ov.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,$r.normalizeGuid)(d,"appactionid")]=typeof f=="string"?f:null}}return{raw:l,etag:a?(0,Lr.readEtag)(a):null,memberEtags:u}},async list(e,t){let r=t?.entityLogicalName;return r?[{type:"command",id:r,name:`${r} commands`,entityLogicalName:r,isDirty:!1}]:[]},async create(e,t,r){let n=t,i=n$(n,r),o=await i$(e,i,n.entityMetadataId);return o$(e,i,{...n,entityMetadataId:o},!1)},async update(e,t,r,n,i){let o=r,a=n$(o,t),s=await i$(e,a,o.entityMetadataId);return o$(e,a,{...o,entityMetadataId:s},!0,i)},async delete(e,t){let r=await av(e,t),n=`/appactions${(0,$r.odataQuery)([["$select","appactionid"],["$filter",sv(t,r)]])}`,i=await(0,ov.collectPages)(e,n,"deleteArtifact('command')");for(let o of i)o.appactionid&&await(0,Lr.deleteRecord)(e,"appactions",o.appactionid)}};async function o$(e,t,r,n,i){let o=r.entityMetadataId?(0,$r.normalizeGuid)(r.entityMetadataId,"entityMetadataId"):"",a=await Dre(e,t,r,o,n,i),s={};try{await Ore(e,a,o,s)}catch(l){throw(0,Vi.withPartialTokens)(l,{memberEtags:s})}return{id:r.entityLogicalName,etag:null,memberEtags:s}}function lv(e){return e.replace(/[{}]/g,"").toLowerCase()}function l$(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=lv(o),l=n.get(s);if(l===void 0){n.set(s,a);continue}throw new Vi.SdkError(Pt.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.`)}}Pt.assertOneWritePerRow=l$;var Tre={entities:/^\/entities\(([^()]+)\)$/,appactions:/^\/appactions\(([^()]+)\)$/};function a$(e,t){let r=Tre[t].exec(e);return r?lv(r[1]):void 0}async function Dre(e,t,r,n,i,o){var a,s;l$(t,r);let l=Pre(r.rows),u=new Set(l.map(f=>lv(f.appactionid))),c={writes:[],deletes:[]};for(let f of l){let m=f.body["[email protected]"];if(m!==void 0&&!(typeof m=="string"&&n!==""&&a$(m,"entities")===n))throw new Vi.SdkError(Pt.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"}). `+oc(t));let p=f.body["[email protected]"];if(typeof p=="string"){let h=a$(p,"appactions");if(h===void 0||!u.has(h))throw new Vi.SdkError(Pt.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. `+oc(t))}if(i&&f.exists){let h=(0,$r.normalizeGuid)(f.appactionid,"id"),g=(a=o?.[h])!==null&&a!==void 0?a:f.etag;if(!(0,Lr.isVersionToken)(g))throw s$(t,h,"update",g);c.writes.push({kind:"patch",row:f,id:h,token:g})}else{if(m===void 0&&!n)throw new Vi.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,$r.normalizeGuid)(f,"id"),p=o?.[m];if(!(0,Lr.isVersionToken)(p))throw s$(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 Ire(e,t,n),m=d.find(p=>!f.has(p.id));if(m)throw new Vi.SdkError(Pt.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. `+oc(t))}return c}function s$(e,t,r,n){return new Vi.SdkError(Lr.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. `+oc(e))}async function Ire(e,t,r){let n=`/appactions${(0,$r.odataQuery)([["$select","appactionid"],["$filter",sv(t,r)]])}`,i=await(0,ov.collectPages)(e,n,"pushArtifact('command') bar membership"),o=new Set;for(let a of i)typeof a.appactionid=="string"&&o.add((0,$r.normalizeGuid)(a.appactionid,"appactionid"));return o}async function Ore(e,t,r,n){for(let i of t.writes)if(i.kind==="patch"){let o=(0,Lr.echoWrite)("appactionid",{"If-Match":i.token}),a=`/appactions(${i.id})${o.query}`,s=(0,Lr.ensureSuccess)(await e.patch(a,i.row.body,o.options),e.apiUrl(a));n[i.id]=(0,Lr.readEtag)(s)}else{let o=(0,Lr.echoWrite)("appactionid"),a=`/appactions${o.query}`,s={...i.row.body};s["[email protected]"]===void 0&&(s["[email protected]"]=`/entities(${r})`);let l=(0,Lr.ensureSuccess)(await e.post(a,s,o.options),e.apiUrl(a)),u=(0,Lr.readCreatedId)(l,"appactionid");u&&(n[(0,$r.normalizeGuid)(u,"appactionid")]=(0,Lr.readEtag)(l))}for(let{id:i,token:o}of[...t.deletes].reverse())await(0,Lr.deleteRecord)(e,"appactions",i,o),delete n[i]}function Pre(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 N$=v(il=>{"use strict";Object.defineProperty(il,"__esModule",{value:!0});il.commandRegistration=il.CommandAdapter=void 0;var ct=(r$(),Br(t$)),c$=Qr(),wt=rn(),p$=u$(),m$=pt(),ol=le(),h$=Q(),dv="$ClientSvg:",fv=".svg",Rre=2,kre=1,Lre=1,g$="entityMetadataId",$re=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"]),Ep=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 h$.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=Bre(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:Fre(g,f,w$(h),c)});return{id:c,entityLogicalName:c,commandBars:Ure(p),bag:{a:[[g$,(l=t.entityMetadataId)!==null&&l!==void 0?l:""]]}}}fromArtifact(t){return{entityLogicalName:t.entityLogicalName,entityMetadataId:mv(t),appActions:uv(t).map(r=>r.row)}}fromApiResponse(t){return this.toArtifact(t??{})}toApiPayload(t,r){let n=new Set(r?uv(r).map(l=>l.appactionid):[]),i=uv(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?Zre(l.row):S$(l.row)}}),s=[...n].filter(l=>!o.has(l));return(0,p$.assertOneWritePerRow)(t.entityLogicalName,{rows:a,deletedRowIds:s}),{entityLogicalName:t.entityLogicalName,entityMetadataId:mv(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,m$.assignMissingIds)(t)}normalize(t){let r=Wre(t),n=!1,i=(Array.isArray(t.commandBars)?t.commandBars:[]).map(o=>{let a=(0,wt.isJsonObject)(o)&&Array.isArray(o.groups)?o.groups:void 0;if(!a)return o;let s=!1,l=a.map(u=>{let c=(0,wt.isJsonObject)(u)&&Array.isArray(u.controls)?u.controls:void 0;if(!c)return u;let d=c.map(f=>E$(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,wt.childObjects)(t,"commandBars","","commandBar",r).forEach(({node:i,index:o})=>{let a=`/commandBars/${o}`;(0,wt.optionalEnum)(i,"location",["MainTab","ContextualTab","HomeTab"],a,"bar-location-invalid",r),(0,wt.childObjects)(i,"groups",a,"group",r).forEach(({node:l,index:u})=>{let c=`${a}/groups/${u}`;Np(l.bag)||((0,wt.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."})),y$((0,wt.childObjects)(l,"controls",c,"control",r),`${c}/controls`,r)})}),r}};il.CommandAdapter=Ep;function Np(e){let t=e?.a;return Array.isArray(t)&&t.length>0}function y$(e,t,r){e.forEach(({node:n,index:i})=>{let o=`${t}/${i}`;Np(n.bag)||(0,wt.optionalGuidId)(n,"id",o,"control-id-invalid",r),(0,wt.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,wt.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,wt.isJsonObject)(n.action)?(0,wt.optionalEnum)(n.action,"type",["javascript"],`${o}/action`,"action-type-invalid",r):r.push((0,wt.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,wt.childObjects)(n,"children",o,"control",r);s.length>0&&y$(s,`${o}/children`,r)})}function pv(e){return{a:Object.entries(e)}}function xre(e){return Object.fromEntries(e.a)}function ac(e,t){if(e){for(let[r,n]of e.a)if(r===t)return n}}function mv(e){let t=ac(e.bag,g$);return typeof t=="string"?t:""}function Fre(e,t,r,n){var i,o;let a=[],s=[];for(let l of Sp(e))l.type===ct.ButtonType.Group?a.push({id:v$(l.name,n),title:typeof l.grouptitle=="string"?l.grouptitle:"",controls:Sp((o=t.get((i=l.appactionid)!==null&&i!==void 0?i:""))!==null&&o!==void 0?o:[]).map(u=>Ap(u,t,r,n)),bag:pv(l)}):s.push(Ap(l,t,r,n));return s.length>0&&a.unshift({id:Xre(n,r),title:"",controls:s}),a}function hv(e){let t=e.bag?ac(e.bag,"appactionid"):void 0;return typeof t=="string"&&t.trim()!==""?t:e.id}function Ap(e,t,r,n){var i,o,a,s,l;let u=v$(e.name,n),c={id:u,type:qre(e.type),label:typeof e.buttonlabeltext=="string"?e.buttonlabeltext:"",command:typeof e.appactionid=="string"?e.appactionid:u,bag:pv(e)},d=b$(e);d&&(c.icon=d);let f=Mre(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 Sp(m))if(g.type===ct.ButtonType.Group){let b=(o=g.appactionid)!==null&&o!==void 0?o:"",w=pv(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 Sp((l=t.get((s=g.appactionid)!==null&&s!==void 0?s:""))!==null&&l!==void 0?l:[])){let O=Ap(S,t,r,n);p.push(O),C.push(hv(O))}h.push({id:b,bag:w,childIds:C})}else p.push(Ap(g,t,r,n));c.children=p,h.length>1&&(c.flyoutGroups=h)}return c}function b$(e){var t;if(!((t=e.IconWebResourceId)===null||t===void 0)&&t.name)return e.IconWebResourceId.name;if(e.fonticon)return e.fonticon.startsWith(dv)?e.fonticon.slice(dv.length)+fv:e.fonticon}function Mre(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 d$(e){return typeof e.sequence=="number"?e.sequence:typeof e.buttonsequencepriority=="number"?e.buttonsequencepriority:0}function Sp(e){return[...e].sort((t,r)=>d$(t)-d$(r))}function Ure(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 v$(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 Bre(e){switch(e){case ct.Location.Form:case ct.Location.QuickForm:return"MainTab";case ct.Location.HomePageGrid:case ct.Location.Dashboard:return"HomeTab";default:return"ContextualTab"}}function w$(e){switch(e){case"MainTab":return ct.Location.Form;case"HomeTab":return ct.Location.HomePageGrid;default:return ct.Location.SubGridStandard}}function qre(e){switch(e){case ct.ButtonType.Dropdown:return"FlyoutAnchor";case ct.ButtonType.Split:return"SplitButton";default:return"Button"}}function Vre(e){switch(e){case"FlyoutAnchor":return ct.ButtonType.Dropdown;case"SplitButton":return ct.ButtonType.Split;default:return ct.ButtonType.Standard}}function Gre(e){var t;return e.bag&&e.bag.a.length>0?!0:((t=e.title)!==null&&t!==void 0?t:"").length>0}function C$(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 uv(e,t=new Set){var r,n,i,o;let a=[],s=mv(e);for(let l of(r=e.commandBars)!==null&&r!==void 0?r:[]){let u=w$(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=>!C$(m,t)),f=0;for(let m of(i=l.groups)!==null&&i!==void 0?i:[]){let p;if(Gre(m)){let h=jre(m,u,void 0,e,s);a.push(h),p=h.appactionid}for(let h of(o=m.controls)!==null&&o!==void 0?o:[])A$(h,u,p,e,s,a,d?f:void 0,t),f+=1}}return a}function E$(e,t){if(!(0,wt.isJsonObject)(e))return e;let r=e.children,n=r,i=!1;Array.isArray(r)&&(n=r.map(s=>E$(s,t)),i=n.some((s,l)=>s!==r[l]));let o=!Np(e.bag)&&(typeof e.id!="string"||e.id.trim()==="");if(!o&&!i)return e;let a;if(o){do a=(0,m$.newId)();while(t.has(a));t.add(a)}return{...e,...a!==void 0?{id:a}:{},...i?{children:n}:{}}}function Wre(e){let t=new Set,r=(o,...a)=>{if((0,wt.isJsonObject)(o))for(let s of[...a.map(l=>o[l]),Np(o.bag)?ac(o.bag,"appactionid"):void 0])typeof s=="string"&&s.trim()!==""&&t.add(s.toLowerCase())},n=o=>{(0,wt.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,wt.isJsonObject)(o)?o.groups:void 0;(Array.isArray(a)?a:[]).forEach(s=>{r(s,"id");let l=(0,wt.isJsonObject)(s)?s.controls:void 0;(Array.isArray(l)?l:[]).forEach(n)})}),t}function A$(e,t,r,n,i,o,a,s=new Set){var l;let u=zre(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=>!C$(h,s)),f=(h,g,b)=>{A$(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=>[hv(S),S])),g=new Set,b=0,w;for(let[S,O]of m.entries()){let k=O.id||(S===0?cv(u.appactionid):yv("flyout-group",`${u.appactionid}#${S}`)),I=f$(k,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??cv(u.appactionid);for(let S of c){let O=hv(S);g.has(O)||(g.add(O),f(S,C,b),b+=1)}return}let p=e.flyoutGroupId||cv(u.appactionid);o.push(f$(p,t,u.appactionid,n,i,e.flyoutGroupBag));for(let[h,g]of c.entries())f(g,p,h)}function zre(e,t,r,n,i,o){let a=gv(e,t,r,n,i),s=a.row;o!==void 0&&typeof s.sequence!="number"&&(s.sequence=o);let l=b$(s);return e.location!==void 0&&(s.location=e.location),s.type=Vre(e.type),s.buttonlabeltext=e.label,Kre(s,e.icon,l),Yre(s,e.action),Jre(s),e.hidden!==void 0&&(s.hidden=e.hidden),e.disabled!==void 0&&(s.isdisabled=e.disabled),{...a,row:s}}function jre(e,t,r,n,i){let o=gv(e,t,r,n,i);return o.row.type=ct.ButtonType.Group,o.row.grouptitle=e.title,o}function f$(e,t,r,n,i,o){let a=gv({id:e,bag:o},t,r,n,i),s=a.row;return s["[email protected]"]=`/appactions(${(0,ol.normalizeGuid)(r,"Command flyout group id")})`,s.type=ct.ButtonType.Group,s.grouptitle===void 0&&(s.grouptitle=""),s.isgrouptitlehidden===void 0&&(s.isgrouptitlehidden=!0),a}function gv(e,t,r,n,i){let o,a,s,l;if(e.bag&&e.bag.a.length>0){o=xre(e.bag),a=!0;let u=ac(e.bag,"@odata.etag");s=typeof u=="string"?u:null;let c=ac(e.bag,"appactionid");l=typeof c=="string"&&c?c:e.id}else{if(typeof e.id!="string"||e.id.trim()==="")throw new h$.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=Hre(l,t,n,i),a=!1,s=null}return r?o["[email protected]"]=`/appactions(${(0,ol.normalizeGuid)(r,"Command parent appaction id")})`:a&&typeof o._parentappactionid_value=="string"&&o._parentappactionid_value&&o.type!==ct.ButtonType.Group&&(o["[email protected]"]=null),delete o._parentappactionid_value,{appactionid:l,exists:a,etag:s,row:o}}function Hre(e,t,r,n){let i={appactionid:e,name:`${e}!${e.replace(/-/g,"").slice(0,32)}`,uniquename:"",location:t,context:ct.Context.Entity,contextvalue:r.entityLogicalName,scope:ct.Scope.Entity};return n&&(i["[email protected]"]=`/entities(${(0,ol.normalizeGuid)(n,"Command context entity metadata id")})`),i}function Kre(e,t,r){if(t===r){let n=e._iconwebresourceid_value;typeof n=="string"&&n&&!e.fonticon&&(e["[email protected]"]=`/webresourceset(${(0,ol.normalizeGuid)(n,"Command icon web resource id")})`);return}if(t===void 0){e.fonticon="",e.IconWebResourceId=null;return}e.fonticon=t.toLowerCase().endsWith(fv)?dv+t.slice(0,t.length-fv.length):t,e.IconWebResourceId=null}function Jre(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,ol.normalizeGuid)(o,`Command ${i}`);e[`${i}@odata.bind`]=`/canvasapps(${a})`};e.onclickeventtype===kre&&t("_onclickeventformulacomponentlibraryid_value","OnClickEventFormulaComponentLibraryId");let r=e.visibilitytype;(!r||r===Lre)&&t("_visibilityformulacomponentlibraryid_value","VisibilityFormulaComponentLibraryId")}function Yre(e,t){if(!(!t||t.type!=="javascript")){if(e.onclickeventtype=Rre,t.webResourceId){let r=(0,ol.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 Qre(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 yv(e,t){let r="";for(let n=0;n<4;n+=1)r+=Qre(`${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 cv(e){return yv("flyout-group",e)}function Xre(e,t){return yv("loose-group",`${e}|${t}`)}function S$(e){let t={...e};for(let r of $re)delete t[r];return t}function Zre(e){let t=S$(e);for(let r of ct.CannotUpdateAppActionColumns)delete t[r];return t}function ene(){return{adapter:new Ep,api:p$.commandApi,publish:(e,t,r)=>(0,c$.publishBoundEntity)(e,r),publishScope:(e,t)=>(0,c$.boundEntityPublishScope)(t)}}il.commandRegistration=ene});var T$=v(_p=>{"use strict";Object.defineProperty(_p,"__esModule",{value:!0});_p.chartApi=void 0;var tne=Lt(),xr=ye(),Sa=le(),_$="savedqueryvisualizationid,name,description,primaryentitytypecode,datadescription,presentationdescription,charttype,type,isdefault",rne="savedqueryvisualizationid,name,primaryentitytypecode,charttype,isdefault";_p.chartApi={async get(e,t){let r=(0,Sa.normalizeGuid)(t,"id"),n=await(0,xr.readRowEtag)(e,"savedqueryvisualizations","savedqueryvisualizationid",r),i=`/savedqueryvisualizations(${r})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,Sa.odataQuery)([["$select",_$]]);return{raw:(0,xr.ensureSuccess)(await e.get(i),e.apiUrl(i)).body,etag:n}},async readContentThenToken(e,t){let r=(0,Sa.normalizeGuid)(t,"id"),n=`/savedqueryvisualizations(${r})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,Sa.odataQuery)([["$select",_$]]),i=(0,xr.ensureSuccess)(await e.get(n),e.apiUrl(n)),o=await(0,xr.readRowEtag)(e,"savedqueryvisualizations","savedqueryvisualizationid",r);return{raw:i.body,etag:o}},async list(e,t){let r=`/savedqueryvisualizations${(0,Sa.odataQuery)([["$select",rne],["$filter",t?.entityLogicalName?`primaryentitytypecode eq '${(0,Sa.odataLiteral)(t.entityLogicalName)}'`:void 0]])}`;return(await(0,tne.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,xr.echoWrite)("savedqueryvisualizationid"),o=`/savedqueryvisualizations${i.query}`,a=(0,xr.ensureSuccess)(await e.post(o,(0,xr.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,xr.resolveCreatedId)(a,"savedqueryvisualizationid","chart",r),etag:(0,xr.readEtag)(a)}},async update(e,t,r,n){let i=r,o=(0,Sa.normalizeGuid)(t,"id"),a=(0,xr.echoWrite)("savedqueryvisualizationid",{"If-Match":(0,xr.requireEtag)(n,"chart",o)}),s=`/savedqueryvisualizations(${o})${a.query}`,l=(0,xr.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,xr.readEtag)(l)}},delete(e,t){return(0,xr.deleteRecord)(e,"savedqueryvisualizations",t)}}});var W$=v(sl=>{"use strict";Object.defineProperty(sl,"__esModule",{value:!0});sl.chartRegistration=sl.ChartAdapter=void 0;var bv=so(),D$=rn(),ai=uo(),I$=Qr(),nne=T$(),vv=lo(),ine=pt(),one=["Column","StackedColumn","StackedColumn100","Bar","StackedBar","StackedBar100","Area","StackedArea","StackedArea100","Line","Pie","Doughnut","Funnel","Tag"],ane=new Map(one.map(e=>[e.toLowerCase(),e]));function L$(e){var t;return e&&(t=ane.get(e.toLowerCase()))!==null&&t!==void 0?t:"Column"}function sne(){return'<Chart Palette="BrightPastel"><Series><Series ChartType="Column" ChartArea="Default" /></Series><ChartAreas><ChartArea Name="Default" /></ChartAreas><Legends><Legend Name="Default" /></Legends></Chart>'}function lne(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 Tp=class{toArtifact(t){var r,n,i,o,a,s,l;(0,vv.installDomShim)();let u=(r=t.datadescription)!==null&&r!==void 0?r:"",c=(n=t.presentationdescription)!==null&&n!==void 0?n:"",d=(0,ai.parseXmlRoot)(u,"<datadefinition/>"),f=(0,ai.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:Dp(f),isDefault:(l=t.isdefault)!==null&&l!==void 0?l:!1,series:F$(d),categories:M$(d),presentation:$$(f),dataBag:u?(0,ai.projectElementBag)(d):void 0,presentationBag:c?(0,ai.projectElementBag)(f):void 0,rowBag:une(t.charttype,t.type)}}fromArtifact(t){(0,vv.installDomShim)();let{datadescription:r,presentationdescription:n}=cne(t);return{savedqueryvisualizationid:t.id,name:t.name,description:t.description,primaryentitytypecode:t.entityLogicalName,datadescription:r,presentationdescription:n,charttype:O$(t.rowBag,"charttype"),type:O$(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,vv.installDomShim)();let u=(r=t.entityLogicalName)!==null&&r!==void 0?r:"";return{id:(n=t.id)!==null&&n!==void 0?n:(0,ine.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,D$.childObjects)(n,"series","","series",r),(0,D$.childObjects)(n,"categories","","category",r),r}};sl.ChartAdapter=Tp;function une(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 O$(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 Dp(e){let t=e.getElementsByTagName("Series");for(let r=0;r<t.length;r+=1)if(t[r].getAttribute("ChartType"))return L$(t[r].getAttribute("ChartType"));return"Column"}function $$(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 Ip(e){return e.getElementsByTagName("fetch")[0]}function x$(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 F$(e){let t=Ip(e);if(!t)return[];let r=x$(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=L$(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 M$(e){var t;let r=Ip(e);if(!r)return[];let n=x$(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 cne(e){var t,r;let n=(t=e.series)!==null&&t!==void 0?t:[],i=(r=e.categories)!==null&&r!==void 0?r:[];if(!P$(e.dataBag)||!P$(e.presentationBag)){let c=lne({...e,series:n,categories:i});return{datadescription:c,presentationdescription:Ine(e,c)}}let o=new DOMParser().parseFromString("<root/>","text/xml"),a=R$(e.dataBag,"datadefinition",o),s=R$(e.presentationBag,"Chart",o),l=e.chartType||Dp(s),u=F$(a);if(!wv(n,u)){let c=Cv(a);dne(o,a,n);let d=Cv(a),f=d.length>0?d:n.map(()=>"");U$(o,s,f,c,l)}return wv(i,M$(a))||fne(o,a,i),e.chartType&&e.chartType!==Dp(s)&&V$(s,e.chartType),e.presentation&&!wv(e.presentation,$$(s))&&G$(s,e.presentation),{datadescription:(0,ai.serializeNode)(a),presentationdescription:(0,ai.serializeNode)(s)}}function P$(e){return!!e&&(e.c.length>0||e.a.length>0)}function U$(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 Cv(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 R$(e,t,r){let n={n:t,a:(0,bv.mergeAttrs)(e.a,[]),c:(0,bv.spliceChildren)(e.c,[])};return(0,bv.rebuildRaw)(n,(0,ai.domEngine)(r),null)}function dne(e,t,r){let n=Ip(t),i=n?.getElementsByTagName("entity")[0];!n||!i||B$(e,t,i,vne(n),r,Cne,{aliasPrefix:"aggregate_column",addRef:hne,removeRef:bne})}function fne(e,t,r){let n=Ip(t),i=n?.getElementsByTagName("entity")[0];!n||!i||B$(e,t,i,wne(n),r,Ene,{aliasPrefix:"groupby_column",addRef:gne,removeRef:yne})}function B$(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=Ane(r,m),b=p.relatedEntity;(g??void 0)!==(b??void 0)&&((h=m.parentNode)===null||h===void 0||h.removeChild(m),k$(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||mne(t,a.aliasPrefix);p.setAttribute("alias",h),o(p,m),k$(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),Nne(m)}}function pne(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 mne(e,t){let r=pne(e);if(!r.has(t))return t;for(let n=2;;n+=1){let i=`${t}_${n}`;if(!r.has(i))return i}}function q$(e,t){let r=t.getElementsByTagName("categorycollection")[0];if(r)return r;let n=e.createElement("categorycollection");return t.appendChild(n),n}function hne(e,t,r){let n=q$(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 gne(e,t,r){let n=q$(e,t),i=e.createElement("category");i.setAttribute("alias",r),n.appendChild(i)}function yne(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 bne(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"&&!Tne(a)&&((r=a.parentNode)===null||r===void 0||r.removeChild(a))}}function vne(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 wne(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 Cne(e,t){e.setAttribute("name",t.attribute),e.setAttribute("aggregate",t.aggregate),t.seriesType&&e.setAttribute("charttype",t.seriesType)}function Ene(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 Ane(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 k$(e,t,r,n){n?Sne(e,t,n).appendChild(r):t.appendChild(r)}function Sne(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 Nne(e){let t=e.parentNode;if(t&&(t.removeChild(e),t.tagName==="link-entity"&&!_ne(t))){let r=t.parentNode;r&&r.removeChild(t)}}function _ne(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 Tne(e){let t=e.childNodes;for(let r=0;r<t.length;r+=1)if(t[r].nodeType===1)return!0;return!1}function V$(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(!Dne(r[i])){r[i].setAttribute("ChartType",t);return}}}function Dne(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 G$(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 Ine(e,t){let r=(0,ai.parseXmlRoot)(sne(),"<Chart/>"),n=e.chartType||Dp(r);V$(r,n),e.presentation&&G$(r,e.presentation);let i=Cv((0,ai.parseXmlRoot)(t,"<datadefinition/>"));return i.length>0&&U$(r.ownerDocument,r,i,i.slice(0,1),n),(0,ai.serializeNode)(r)}function wv(e,t){return JSON.stringify(e)===JSON.stringify(t)}function al(e){return String(e??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function One(){return{adapter:new Tp,api:nne.chartApi,publish:(e,t,r)=>(0,I$.publishBoundEntity)(e,r),publishScope:(e,t)=>(0,I$.boundEntityPublishScope)(t),rebaselineAfterPublish:"bracket"}}sl.chartRegistration=One});var K$=v(Na=>{"use strict";Object.defineProperty(Na,"__esModule",{value:!0});Na.dashboardApi=Na.dashboardEntity=void 0;var Pne=Lt(),Oo=ye(),ll=le(),Rne=Cg(),z$=ru();function j$(e){return e&&e.toLowerCase()!=="none"?e:void 0}Na.dashboardEntity=j$;var H$="formid,name,description,formxml,type,objecttypecode,istabletenabled,iscustomizable,componentstate,versionnumber",kne={select:H$,required:["name","type","objecttypecode","istabletenabled"]},Lne="formid,name,type,objecttypecode",$ne=0,xne=10;Na.dashboardApi={async get(e,t){let r=(0,ll.normalizeGuid)(t,"id"),n=`/systemforms(${r})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,ll.odataQuery)([["$select",H$]]),i=(0,Oo.ensureSuccess)(await e.get(n),e.apiUrl(n));return(0,z$.assertSystemFormRecordKind)(i.body,r,"dashboard","fetch"),{raw:i.body,etag:(0,Oo.readEtag)(i)}},async list(e,t){let r=[`(type eq ${$ne} or type eq ${xne})`];t?.entityLogicalName&&r.push(`objecttypecode eq '${(0,ll.odataLiteral)(t.entityLogicalName)}'`);let n=`/systemforms${(0,ll.odataQuery)([["$select",Lne],["$filter",r.join(" and ")]])}`;return(await(0,Pne.collectPages)(e,n,"listArtifacts('dashboard')")).map(o=>{var a,s;let l=j$(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,Oo.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,Oo.ensureSuccess)(await e.post(o,(0,Oo.withClientMintedId)(a,"formid",r),i.options),e.apiUrl(o));return{id:(0,Oo.resolveCreatedId)(s,"formid","dashboard",r),etag:(0,Oo.readEtag)(s)}},async update(e,t,r,n){let i=r;return(0,Rne.patchSystemForm)(e,(0,ll.normalizeGuid)(t,"id"),"dashboard",{name:i.name,description:i.description,formxml:i.formxml,istabletenabled:i.istabletenabled},n,kne)},readContentThenToken(e,t){return Na.dashboardApi.get(e,t)},async delete(e,t){let r=(0,ll.normalizeGuid)(t,"id");return await(0,z$.assertSystemFormKind)(e,r,"dashboard"),(0,Oo.deleteRecord)(e,"systemforms",r)}}});var sx=v(si=>{"use strict";Object.defineProperty(si,"__esModule",{value:!0});si.dashboardRegistration=si.TILE_CLASS_ID=si.DashboardAdapter=void 0;var lc=so(),hn=uo(),Ev=Qr(),sc=rn(),ex=K$(),Av=lo(),_a=pt(),tx=le(),rx=Jo(),Fne=$y(),J$="0",Sv="10",Mne=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"]]),Une="{3FF9A528-DD50-4ACA-8F10-2E5ED73513AD}",Pp=class{constructor(t=rx.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,hn.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:Bne(t.type),entityLogicalName:(a=(0,ex.dashboardEntity)(t.objecttypecode))!==null&&a!==void 0?a:null,enabledForMobile:!!t.istabletenabled,layoutType:qne(l),components:Y$(l,this.lcid),bag:(0,hn.projectElementBag)(l)}}fromArtifact(t){var r;return(0,Av.installDomShim)(),{formid:t.id,name:t.name,description:t.description,type:t.dashboardType==="Interactive"?Sv:J$,objecttypecode:(r=t.entityLogicalName)!==null&&r!==void 0?r:"",istabletenabled:t.enabledForMobile,formxml:Q$(t,this.lcid)}}fromApiResponse(t){return this.toArtifact(t??{})}completeAsStored(t,r){return(0,Fne.completeRecordAsStored)(t,r,this.lcid)}toApiPayload(t){return{name:t.name,description:t.description,formxml:Q$(t,this.lcid),istabletenabled:t.enabledForMobile,type:t.dashboardType==="Interactive"?Sv:J$,objecttypecode:t.entityLogicalName}}createDefault(t){var r,n,i,o,a,s,l,u;(0,Av.installDomShim)();let c=(0,hn.parseXmlRoot)(eie(),"<form/>");return{id:(r=t.id)!==null&&r!==void 0?r:(0,_a.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:Y$(c,this.lcid),bag:(0,hn.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,_a.newId)())}return t}validate(t){let r=[],n=(0,sc.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,sc.isJsonObject)(u)&&r.push((0,sc.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,sc.isJsonObject)(o.position)){let l=uc(o.position);i.has(l)?r.push((0,sc.issue)(`${s}/position`,"component-position-collision",`two components occupy the same dashboard position (${l}); move one to a free cell`)):i.add(l)}}),r}};si.DashboardAdapter=Pp;function Bne(e){return String(e??"")===Sv?"Interactive":"Standard"}function qne(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 Y$(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)=>{Vne(c,{tabIndex:o,columnIndex:l,sectionIndex:d},r,t)})})}),r}function Vne(e,t,r,n){ae(e,"rows").flatMap(o=>ae(o,"row")).forEach((o,a)=>{ae(o,"cell").forEach((s,l)=>{let u=Gne(s,{...t,rowIndex:a,cellIndex:l},n);u&&r.push(u)})})}function Gne(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=jne(a),u=Hne(s,l,a),c=Wne(a);return{id:a.getAttribute("id")||o,type:u,name:ix(e,r),classId:s,position:t,colspan:Rp(e,"colspan",1),rowspan:Rp(e,"rowspan",1),parameters:l,bag:(0,hn.projectElementBag)(e),...c?{icProperties:c}:{}}}function nx(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 Wne(e){let t=nx(e);return t?(0,hn.serializeNode)(t):void 0}function zne(e,t,r){let n=nx(t);if(!r){n&&t.removeChild(n);return}let i=new DOMParser().parseFromString(r,"text/xml").documentElement,o=(0,lc.rebuildRaw)((0,lc.rawFromNode)((0,hn.nodeLikeFromDom)(i)),(0,hn.domEngine)(e),null);n&&(0,hn.serializeNode)(n)===(0,hn.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 jne(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 Hne(e,t,r){var n;let i=Mne.get(e.toUpperCase());return i?i==="chart"?t.ChartGridMode==="Chart"?"chart":"list":i==="assistant"?((n=r.getAttribute("uniqueid"))!==null&&n!==void 0?n:"").toUpperCase()===Une?"assistant":t.ChartGridMode!==void 0||r.getAttribute("indicationOfSubgrid")==="true"?t.ChartGridMode==="Chart"?"chart":"list":"unknown":i:"unknown"}function Rp(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 Kne(e,t){let r={n:"form",a:(0,lc.mergeAttrs)(e.bag.a,[]),c:(0,lc.spliceChildren)(e.bag.c,[])};return(0,lc.rebuildRaw)(r,(0,hn.domEngine)(t),null)}function Q$(e,t){let r=new DOMParser().parseFromString("<root/>","text/xml"),n=Kne(e,r);return Qne(r,n,e.components,t),Jne(r,n,e.components,t),(0,hn.serializeNode)(n)}function Jne(e,t,r,n){let i=ax(t);for(let o of r)i.has(uc(o.position))||Yne(e,t,o,n)}function Yne(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=tie(t,e,l);for(let x of ae(u,"row"))ae(x,"cell").some(K=>ae(K,"control").length>0)||u.removeChild(x);let c=r.classId||si.TILE_CLASS_ID[r.type]||si.TILE_CLASS_ID.iframe,d=r.rowspan&&r.rowspan>0?r.rowspan:4,f=r.bag&&X$(r.bag,"id")?String(X$(r.bag,"id")):Op((0,_a.newId)()),m=r.id?Op(r.id):Op((0,_a.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=ae(u,"row"),w=b[b.length-1],C=w?ae(w,"cell").reduce((x,K)=>x+Rp(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"),k=e.createElement("label");k.setAttribute("description",(a=r.name)!==null&&a!==void 0?a:""),k.setAttribute("languagecode",String(n)),O.appendChild(k),S.appendChild(O);let I=e.createElement("control");I.setAttribute("id",m),I.setAttribute("classid",Op(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,tx.createSafeXmlElement)(e,x,"dashboard tile parameter");K.textContent=P[x],D.appendChild(K)}I.appendChild(D),S.appendChild(I),w.appendChild(S)}function X$(e,t){if(!e)return;let r=e.a.find(n=>n[0]===t);return r?r[1]:void 0}function Qne(e,t,r,n){var i;let o=ax(t),a=new Set(r.map(s=>uc(s.position)));for(let s of r){let l=o.get(uc(s.position));if(!l)continue;let u=ae(l,"control")[0];u&&(Xne(e,l,s.name,n),Zne(e,u,s.parameters),Z$(l,"colspan",s.colspan),Z$(l,"rowspan",s.rowspan),s.icProperties!==void 0&&zne(e,u,s.icProperties))}for(let[s,l]of o)a.has(s)||(i=l.parentNode)===null||i===void 0||i.removeChild(l)}function ax(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,m)=>{ae(f,"cell").forEach((p,h)=>{var g;ox((g=p.getAttribute("id"))!==null&&g!==void 0?g:"").toLowerCase().startsWith("spacer")||ae(p,"control")[0]&&t.set(uc({tabIndex:i,columnIndex:s,sectionIndex:c,rowIndex:m,cellIndex:h}),p)})})})})}),t}function uc(e){let t=e??{};return`${t.tabIndex}.${t.columnIndex}.${t.sectionIndex}.${t.rowIndex}.${t.cellIndex}`}function Xne(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 Zne(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,tx.createSafeXmlElement)(e,l,"dashboard component parameter");d.textContent=u,o.appendChild(d)}}}function Z$(e,t,r){Rp(e,t,1)!==r&&e.setAttribute(t,String(r))}function eie(e=2){let t=`{${(0,_a.newId)()}}`,r=`{${(0,_a.newId)()}}`,n=`{${(0,_a.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>`}si.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 Op(e){return`{${e.replace(/[{}]/g,"")}}`}function tie(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 rie(e=rx.DEFAULT_LCID){return{adapter:new Pp(e),api:ex.dashboardApi,languageSensitive:!0,publish:(t,r,n)=>n?.entityLogicalName?(0,Ev.publishBoundEntity)(t,n):(0,Ev.publishDashboardById)(t,r),publishScope:(t,r)=>r?.entityLogicalName?(0,Ev.boundEntityPublishScope)(r):{envelope:"dashboard",targetIds:[t]},rebaselineAfterPublish:"bracket"}}si.dashboardRegistration=rie});var _v=v(Fr=>{"use strict";Object.defineProperty(Fr,"__esModule",{value:!0});Fr.readEveryInOrder=Fr.readInOrder=Fr.plainRead=Fr.resolveReadConcurrency=Fr.MAX_READ_CONCURRENCY=void 0;var lx=Q();Fr.MAX_READ_CONCURRENCY=8;function nie(e){if(e===void 0)return 1;if(typeof e!="number"||!Number.isInteger(e)||e<1||e>Fr.MAX_READ_CONCURRENCY)throw new lx.InvalidArgumentError(`readConcurrency must be a whole number from 1 to ${Fr.MAX_READ_CONCURRENCY} (got ${typeof e=="string"?`'${e}'`:String(e)})`);return e}Fr.resolveReadConcurrency=nie;var iie=e=>({ok:!0,value:e}),Nv=e=>({ok:!1,error:e});function oie(e){let t=(async()=>e())().then(iie,Nv);return{outcome:t,finish:async r=>{await r()},discard:async()=>{await t}}}Fr.plainRead=oie;async function ux(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 m=await r(e[f],f),p=m.outcome.catch(Nv);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:Nv(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 aie(e,t,r,n){return ux(e,t,r,(i,o,a)=>n(i.value,o,a),"stop")}Fr.readInOrder=aie;function sie(e,t,r,n){return ux(e,t,r,n,"continue")}Fr.readEveryInOrder=sie});var _x=v(Lp=>{"use strict";Object.defineProperty(Lp,"__esModule",{value:!0});Lp.genPageApi=void 0;var kp=Lt(),Cx=Kl(),Be=ye(),ve=le(),xn=xd(),Je=Q(),Ex=pt(),cx=_v();function lie(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 li="uxagentprojects",Da="uxagentprojectfiles",fc="agentconversationmessages",pc="uxagentprojectid",Bt="uxagentprojectfileid",Ia="agentconversationmessageid",cc=`${pc},name`,uie=`${Bt},filename,filetype`,Ax=2e8,Sx=200000001,Oa={"MSCRM.IncludeUnpublished":"true"},Tv={};function Ta(e,t){return{"MSCRM.VersioningChangeset":e,...Oa,...t}}async function Ov(e,t,r,n){var i;let o=`/${t}(${r})`+(0,ve.odataQuery)([["$select",n]]),a=(0,Be.ensureSuccess)(await e.get(o,{headers:{...Oa}}),e.apiUrl(o));return{row:(i=a.body)!==null&&i!==void 0?i:{},etag:(0,Be.readEtag)(a)}}async function mc(e,t,r=Oa){let n=`/${Da}(${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=lie(o);if(a)return{status:"available",data:(0,xn.bytesToBase64)(a)};if(typeof o=="string")return{status:"available",data:(0,xn.utf8ToBase64)(o)};throw new Je.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 Nx(e){let t=e.lastIndexOf("/");return t>=0?e.slice(t+1):e}async function cie(e,t,r,n,i,o){if(!e.supportsBinaryPatch)throw new Je.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=`/${Da}(${t})/filecontent`,s=(0,xn.base64ToBytes)(n);(0,ve.assertNoControlChars)(r,"generative-page file name"),(0,Be.ensureSuccess)(await e.patchRaw(a,s,{headers:Ta(i,{"Content-Type":"application/octet-stream","Content-Length":String(s.byteLength),"x-ms-file-name":Nx(r),...o?{"If-Match":"*"}:{}})}),e.apiUrl(a))}async function dc(e,t,r=Oa){let n=`/${Da}`+(0,ve.odataQuery)([["$select",uie],["$filter",`_${pc}_value eq ${t}`]]);return(await(0,kp.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 Dv(e,t){let r=`/${fc}`+(0,ve.odataQuery)([["$select",`${Ia},message,messagesender,createdon`],["$filter",`_regardingobjectid_value eq ${t}`],["$orderby","createdon asc,versionnumber asc"]]);return(0,kp.collectPages)(e,r,"fetchArtifact('genPage')",void 0,{headers:{...Oa}})}async function dx(e,t){var r,n,i;let{row:o,etag:a}=await Ov(e,li,t,cc),s=new Map;for(let{row:l,etag:u}of await dc(e,t))s.set((0,ve.normalizeGuid)(String((r=l[Bt])!==null&&r!==void 0?r:""),Bt),{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,ve.normalizeGuid)(c.id,"file id");u.add(d);let f=r?.rows.get(d);if(c.content.status==="retain"){if(!r)throw new Je.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 Je.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 Pv(e){let t=(0,xn.base64ToUtf8)(e);return(0,xn.utf8ToBase64)(t)===(0,xn.bytesToBase64)((0,xn.base64ToBytes)(e))?t:void 0}function die(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?{[Ia]:(0,ve.normalizeGuid)(t.id,"message id")}:{},"[email protected]":`/${li}(${e})`,message:t.message,messagecontext:JSON.stringify(f),messagesender:t.sender==="user"?Ax:Sx}}async function fie(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,ve.normalizeGuid)(f,"message id"));if(s.length===0)return r;let l=`/${fc}`+(0,ve.odataQuery)([["$select",`${Ia},message,messagesender,_regardingobjectid_value`],["$filter",s.map(f=>`${Ia} eq ${f}`).join(" or ")]]),u=await(0,kp.collectPages)(e,l,"pushArtifact('genPage')",void 0,{headers:{...Oa}});if(u.length===0)return r;let c=new Map(u.map(f=>{var m;return[String((m=f[Ia])!==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,ve.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"?Ax:Sx)&&String((a=m._regardingobjectid_value)!==null&&a!==void 0?a:"").toLowerCase()===t))throw new Je.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 Iv(e,t,r,n){switch(t.kind){case"createProject":return{method:"POST",path:`/${li}`,body:(0,Be.withClientMintedId)({name:t.name},pc,e),headers:Ta(n)};case"createRow":return{method:"POST",path:`/${Da}`,body:(0,Be.withClientMintedId)({filename:t.file.name,filetype:t.file.fileType,[`${pc}@odata.bind`]:`/${li}(${e})`},Bt,(0,ve.normalizeGuid)(t.file.id,"file id")),headers:Ta(n)};case"renameRow":return{method:"PATCH",path:`/${Da}(${(0,ve.normalizeGuid)(t.file.id,"file id")})`,body:{filename:t.file.name,filetype:t.file.fileType},headers:Ta(n,{"If-Match":"*"})};case"content":{let i=Pv(t.data);if(i===void 0)throw new Je.SdkError("GENPAGE_CONTENT_NOT_TEXT",`File '${t.file.name}' is not UTF-8 text and cannot ride in a change set.`);return(0,ve.assertNoControlChars)(t.file.name,"generative-page file name"),{method:"PATCH",path:`/${Da}(${(0,ve.normalizeGuid)(t.file.id,"file id")})/filecontent`,rawBody:i,contentType:"application/octet-stream; charset=utf-8",headers:Ta(n,{"x-ms-file-name":Nx(t.file.name),...t.existing?{"If-Match":"*"}:{}})}}case"deleteRow":return{method:"DELETE",path:`/${Da}(${t.fileId})`,headers:Ta(n,{"If-Match":"*"})};case"patchProject":return{method:"PATCH",path:`/${li}(${e})`,body:{name:t.name},headers:Ta(n,{"If-Match":"*"})};case"message":return{method:"POST",path:`/${fc}`,body:die(e,t.turn,r,n)};default:{let i=t;throw new Je.SdkError("GENPAGE_WRITE_UNKNOWN",`Unknown generative-page write: ${JSON.stringify(i)}`)}}}function px(e,t){return e.supportsAtomicBatch&&t.every(r=>r.kind!=="content"||Pv(r.data)!==void 0)}async function mx(e,t,r,n,i){await(0,Cx.postChangeSet)(e,r.map(o=>Iv(t,o,n,i)),`generative page '${t}' (${r.length} operation(s))`)}async function hx(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 cie(e,(0,ve.normalizeGuid)(s.file.id,"file id"),s.file.name,s.data,i,s.existing);continue}let l=Iv(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=>Iv(t,l,n,i));if(e.supportsAtomicBatch)await(0,Cx.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 gx(e,t,r,n,i,o,a){var s;let l=u=>({id:t,etag:null,memberEtags:{},warnings:[...a,u]});try{let u=await dx(e,t),c=new Map;for(let C of r)(C.kind==="createRow"||C.kind==="renameRow"||C.kind==="content")&&c.set((0,ve.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 mc(e,(0,ve.normalizeGuid)(C.file.id,"file id")),O=(0,xn.bytesToBase64)((0,xn.base64ToBytes)(C.data));(S.status!=="available"||S.data!==O)&&d.push(S.status==="available"?`file '${C.file.name}' holds ${(0,xn.base64ToBytes)(S.data).byteLength} byte(s) that differ from the ${(0,xn.base64ToBytes)(O).byteLength} written`:`file '${C.file.name}' holds no content`)}let f=new Set(r.filter(C=>C.kind==="content").map(C=>(0,ve.normalizeGuid)(C.file.id,"file id")));for(let[C,S]of c)!f.has(C)&&(await mc(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 dx(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.`):pie({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 yx(e,t,r,n=e.readConcurrency){var i;let o=(0,ve.normalizeGuid)(t,"id"),{row:a,etag:s}=await Ov(e,li,o,cc),l=await dc(e,o),u={},c=[];if(n>1)await(0,cx.readInOrder)(l,n,({row:f})=>{var m;let p=(0,ve.normalizeGuid)(String((m=f[Bt])!==null&&m!==void 0?m:""),Bt);return(0,cx.plainRead)(async()=>({fileId:p,content:await mc(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,ve.normalizeGuid)(String((i=f[Bt])!==null&&i!==void 0?i:""),Bt);u[p]=m;let h=await mc(e,p);c.push({...f,content:h})}return{raw:r?{project:a,files:c,conversation:await Dv(e,o)}:{project:a,files:c},etag:s,memberEtags:u}}Lp.genPageApi={get(e,t,r){return yx(e,t,!0,r?.fileConcurrency)},getForRebaseline(e,t){return yx(e,t,!1)},async getPublished(e,t){var r,n;let i=(0,ve.normalizeGuid)(t,"id"),o=`/${li}(${i})`+(0,ve.odataQuery)([["$select",cc]]),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 dc(e,i,Tv);for(let{row:g,etag:b}of c){let w=(0,ve.normalizeGuid)(String((n=g[Bt])!==null&&n!==void 0?n:""),Bt);l[w]=b,u.push({...g,content:await mc(e,w,Tv)})}let d=g=>g.map(({row:b,etag:w})=>`${String(b[Bt])}@${String(w)}`).sort().join("|"),f=()=>new Je.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,Be.ensureSuccess)(m,e.apiUrl(o));let p=await dc(e,i,Tv);if([(0,Be.readEtag)(a),(0,Be.readEtag)(m),...[...c,...p].map(g=>g.etag)].some(g=>!g))throw new Je.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)(m)!==(0,Be.readEtag)(a)||d(p)!==d(c))throw f();return{raw:{project:s,files:u,conversation:[]},etag:(0,Be.readEtag)(a),memberEtags:l}},async list(e,t){let r=`/${li}`+(0,ve.odataQuery)([["$select",cc]]);return(await(0,kp.collectPages)(e,r,"listArtifacts('genPage')",void 0,{headers:{...Oa}})).map(i=>{var o,a;return{type:"genPage",id:String((o=i[pc])!==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,ve.normalizeGuid)(r,"id"):(0,Ex.newId)(),a=fx(o,i,void 0);wx(e,a),vx(e,o,i);let s=bx(),l=[],u=!0;px(e,a)?await mx(e,o,a,i,s):{warnings:l,turnRecorded:u}=await hx(e,o,a,i,s);let c=new Set(((n=i.files)!==null&&n!==void 0?n:[]).map(f=>(0,ve.normalizeGuid)(f.id,"file id"))),d=await gx(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,ve.normalizeGuid)(t,"id");if(!Array.isArray(s.files))throw new Je.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 fie(e,l,s);vx(e,l,u);let c=await dc(e,l),{row:d,etag:f}=await Ov(e,li,l,cc);if(n&&f&&n!==f)throw new Je.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 Je.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 m=new Map(c.map(({row:I})=>{var D,P;return[(0,ve.normalizeGuid)(String((D=I[Bt])!==null&&D!==void 0?D:""),Bt),{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,ve.normalizeGuid)(I.id,"file id")));if(!i)throw new Je.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(!p.has(I)&&g.has(I))throw new Je.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 p)if(!g.has(I))throw new Je.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 P;return[(0,ve.normalizeGuid)(String((P=I[Bt])!==null&&P!==void 0?P:""),Bt),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 Je.SdkError(Be.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 Je.SdkError(Be.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=fx(l,u,{rows:m,name:String((a=d.name)!==null&&a!==void 0?a:"")});if(wx(e,w),w.length===0)return{id:l,etag:f,memberEtags:Object.fromEntries(c.map(({row:I,etag:D})=>{var P;return[(0,ve.normalizeGuid)(String((P=I[Bt])!==null&&P!==void 0?P:""),Bt),D]}))};let C=bx(),S=[],O=!0;px(e,w)?await mx(e,l,w,u,C):{warnings:S,turnRecorded:O}=await hx(e,l,w,u,C);let k=await gx(e,l,w,u,h,b,S);return O?k:{...k,intentPending:!0}},async delete(e,t){var r;let n=(0,ve.normalizeGuid)(t,"id"),i=await Dv(e,n);await(0,Be.deleteRecord)(e,li,n);let o=new Set(i.map(l=>{var u;return String((u=l[Ia])!==null&&u!==void 0?u:"")}).filter(l=>l!=="")),a=!1;try{for(let l of await Dv(e,n)){let u=String((r=l[Ia])!==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,fc,l)}catch(u){u instanceof Je.ConnectionError&&u.statusCode===404||s.push(l)}if(s.length>0||a)throw new Je.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 ${fc} rows regarding '${n}'.`)}};function bx(){return`uxagentproject_${(0,Ex.newId)()}`}function pie(e,t){var r;return t.length===0?e:{...e,warnings:[...(r=e.warnings)!==null&&r!==void 0?r:[],...t]}}function vx(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 Je.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 wx(e,t){let r=t.filter(i=>i.kind==="content");if(r.length>0&&!e.supportsBinaryPatch&&!e.supportsAtomicBatch)throw new Je.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=>Pv(i.data)===void 0)&&!e.supportsBinaryPatch)throw new Je.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 Gx=v(cl=>{"use strict";Object.defineProperty(cl,"__esModule",{value:!0});cl.genPageRegistration=cl.GenPageAdapter=void 0;var mie=_x(),hie=Qr(),Ie=rn(),Up=pt(),Bp=xd(),gie=le(),Pa=Q(),Fx=$g(),Rv=rh(),Po=2e8,Mx=200000001,Wi={source:{name:"src/pages/page.tsx",fileType:Po},output:{name:"src/pages/page.compiled",fileType:Mx},config:{name:"config.json",fileType:Po},prompt:{name:"firstPrompt.json",fileType:Po}},Ux=Object.keys(Wi),yie=["dataSources","model","connectorBindings","actionBindings"],bie=["userMessage","agentMessage"],Tx=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,vie={source:"6f1c2a4e9b3d47a1b85c0e2f7d914a63",output:"a8e53d17c2f64b09a1d7e4b8c3f2069d",config:"3b97f0c64e2a4d8f95b1c7a0e6d3f814",prompt:"d24e8b51f7a34c6e8b09d5f1a2c7e3b6"},wie="9c3e7a15d2b84f6e8a01c5d7b3f9e240";function Bx(e,t,r){let n=(0,gie.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 $p(e,t){return Bx(e,vie[t],"id")}function Cie(e,t){let r=Bx(e,wie,"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 Dx(e){return typeof e=="string"&&e.trim()!==""?e:(0,Up.newId)()}function Gi(e){return(0,Ie.isJsonObject)(e)?e:{}}function ul(e,t){return JSON.stringify(e??null)===JSON.stringify(t??null)}function xp(e){return JSON.parse(JSON.stringify(e))}function Eie(e){let t=Gi(e);return t.status==="available"&&typeof t.data=="string"?{status:"available",data:t.data}:{status:"unavailable",reason:t.reason==="unpublished"?"unpublished":"missing"}}function gc(e){if(!e||e.status!=="available")return;let t=(0,Bp.base64ToUtf8)(e.data);return(0,Bp.utf8ToBase64)(t)===e.data?t:void 0}function qx(e,t,r){var n,i,o,a;return e.source!==void 0&&t!==void 0&&t?.source===e.source&&ul((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,Fx.isLoadableGenPageOutput)(r)}function Aie(e,t){var r;try{return qx(e,t,gc((r=e.bag)===null||r===void 0?void 0:r.output))}catch{return!1}}function Fp(e){if(e!==void 0)try{let t=JSON.parse(e.replace(/^\uFEFF/,""));return(0,Ie.isJsonObject)(t)?t:void 0}catch{return}}function Ix(e,t){if(t===Po&&e.includes("page.tsx"))return"source";if(t===Mx&&e.includes(".compiled"))return"output";if(t===Po&&e===Wi.config.name)return"config";if(t===Po&&e===Wi.prompt.name)return"prompt"}function Ox(e){let t=e.toLowerCase();return Ux.some(r=>Wi[r].name.toLowerCase()===t)}function kv(e){return Object.fromEntries(e)}function Vx(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),kv(i)}function Px(e){var t,r,n;return Vx({dataSources:(t=e.dataSources)!==null&&t!==void 0?t:[],model:e.model,connectorBindings:e.connectorBindings,actionBindings:e.actionBindings},yie,(r=e.bag)===null||r===void 0?void 0:r.config,(n=e.bag)===null||n===void 0?void 0:n.configKeys)}function Rx(e){var t,r;return Vx({userMessage:e.firstPrompt,agentMessage:e.firstAgentMessage},bie,(t=e.bag)===null||t===void 0?void 0:t.prompt,(r=e.bag)===null||r===void 0?void 0:r.promptKeys)}function kx(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=kv(n)),!0}function Lx(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=kv(n)),!0}function yc(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 Sie=["dataSources","model","connectorBindings","actionBindings","firstPrompt","firstAgentMessage"];function $x(e){return yc(e)?[]:Sie.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 xx(){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 Mp(e){return{status:"available",data:(0,Bp.utf8ToBase64)(e)}}function hc(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 qp=class{toArtifact(t){return t}fromArtifact(t){return t}fromApiResponse(t){let r=t,n=Gi(r?.project),i=(Array.isArray(r?.files)?r.files:[]).map(g=>{var b,w,C;let S=Gi(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:Po),content:Eie(S.content)}}),o=Array.isArray(r?.conversation)?r.conversation.map(g=>{var b,w;let C=Gi(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=Ix(g.name,g.fileType);b?((s.has(b)||g.name!==Wi[b].name)&&(u=!1),s.set(b,g)):(Ox(g.name)&&(u=!1),l.push(g))}if(!u||s.size===0)return a(hc(n,i));let c=hc(n,l),d={rows:{}};for(let[g,b]of s)d.rows[g]=b.id;let f=s.get("source");if(f){let g=gc(f.content);if(g===void 0)return a(hc(n,i));c.source=g}let m=s.get("output");m&&(d.output=m.content);let p=s.get("config");if(p){let g=Fp(gc(p.content));if(!g||!kx(c,d,g))return a(hc(n,i))}let h=s.get("prompt");if(h){let g=Fp(gc(h.content));if(!g||!Lx(c,d,g))return a(hc(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&&!ul((i=t.conversation)!==null&&i!==void 0?i:[],(o=r.conversation)!==null&&o!==void 0?o:[]))throw new Pa.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=$x(t);if(b.length>0)throw new Pa.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(yc(S)){let I=(s=(a=S.bag)===null||a===void 0?void 0:a.rows)!==null&&s!==void 0?s:{},D=Xe=>{var Ne;return(Ne=I[Xe])!==null&&Ne!==void 0?Ne:$p(S.id,Xe)},P=(Xe,Ne,se)=>{w.push({id:D(Xe),name:Wi[Xe].name,fileType:Wi[Xe].fileType,content:Ne,unchanged:se})};if(S.source!==void 0){P("source",Mp(S.source),!C&&r?.source===S.source&&I.source!==void 0);let Xe=gc((l=S.bag)===null||l===void 0?void 0:l.output);qx(S,r,Xe)?P("output",{status:"retain"},!0):P("output",Mp(await this.compile(S,S.source,n)),!1)}else{if(I.source!==void 0)throw new Pa.ValidationError("genPage",S.id,[xx()]);if(I.output!==void 0){if(!C&&!ul((u=r?.dataSources)!==null&&u!==void 0?u:[],(c=S.dataSources)!==null&&c!==void 0?c:[]))throw new Pa.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=Px(S),K=!C&&r!==void 0&&ul(Px(r),x);(C||I.config!==void 0||!K)&&P("config",Mp(JSON.stringify(x)),K&&I.config!==void 0);let Oe=Rx(S),Vt=!C&&r!==void 0&&ul(Rx(r),Oe);(I.prompt!==void 0||Object.keys(Oe).length>0&&!Vt)&&P("prompt",Mp(JSON.stringify(Oe)),Vt&&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&&ul(D,I)})}let O=[];if(S.newTurn){let I=S.newTurn.id,D=P=>I?{id:Cie(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 k=(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(k.enabledTools)?k.enabledTools:[],configurableTools:Array.isArray(k.configurableTools)?k.configurableTools:[]}}:{}}}committed(t,r,n={intentPending:!1}){let i=this.serverState(t,r);return n.intentPending&&t.newTurn!==void 0?{artifact:{...i,newTurn:xp(t.newTurn)},baseline:i}:{artifact:i,baseline:i}}serverState(t,r){var n,i,o,a,s,l;if(!yc(t)&&!t.newTurn)return t;let u=xp(t);if(delete u.newTurn,!yc(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=Ux.find(p=>Wi[p].name===d.name&&Wi[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,Bp.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,kx(u,c,(s=Fp(m))!==null&&s!==void 0?s:{})):f==="prompt"&&(delete c.prompt,delete u.firstPrompt,delete u.firstAgentMessage,Lx(u,c,(l=Fp(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"&&Tx.test(r.id)?t:{...t,newTurn:{...r,id:(0,Up.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 Pa.ValidationError("genPage",t.id,s);if(!n?.loadTypeScript)throw new Pa.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,Rv.buildGenPageRuntimeTypes)(a):void 0,c=a.length>0?(0,Rv.buildGenPageLegacyEnums)(a):void 0,d=(0,Fx.compileGenPage)(l,r,u,c);if(d.diagnostics.length>0)throw new Pa.ValidationError("genPage",t.id,d.diagnostics.map(Nie));return d.code}metadataNeeds(t,r){if(t.source===void 0||!Array.isArray(t.dataSources))return[];let n=Aie(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=Dx(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:Dx(a.id),name:(s=a.name)!==null&&s!==void 0?s:"index.tsx",fileType:(l=a.fileType)!==null&&l!==void 0?l:Po,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=xp(t.connectorBindings)),t.actionBindings!==void 0&&(o.actionBindings=xp(t.actionBindings)),o.source!==void 0&&(o.bag={rows:{source:$p(i,"source"),output:$p(i,"output"),config:$p(i,"config")}}),o}assignMissingIds(t){if(t==null)return{id:(0,Up.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,Up.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&&Gi(Gi(n.bag).rows).source!==void 0&&r.push(xx()),r.push(...$x(t)),n.newTurn!==void 0){let s=Gi(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"||!Tx.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"||!Rv.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=yc(t),a=new Map;return(Array.isArray(i)?i:[]).forEach((s,l)=>{let u=`/files/${l}`,c=Gi(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&&(Ox(f)||Ix(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=Gi(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}};cl.GenPageAdapter=qp;function Nie(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 _ie(){return{adapter:new qp,api:mie.genPageApi,publish:(e,t)=>(0,hie.publishGenPageById)(e,t),publishScope:e=>({envelope:"uxagentproject",targetIds:[e]}),rebaselineAfterPublish:"snapshot"}}cl.genPageRegistration=_ie});var zx=v(Gp=>{"use strict";Object.defineProperty(Gp,"__esModule",{value:!0});Gp.reconcileBpfSecurityRoles=void 0;var Wx=Lt(),$v=Q(),Vp=ye(),bc=le(),Tie="Global",Lv={create:"Create",read:"Read",write:"Write",delete:"Delete"};async function Die(e,t){var r;let n=`/EntityDefinitions(LogicalName='${(0,bc.odataPathLiteral)(t)}')?$select=LogicalName,Privileges`,i=(0,Vp.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 $v.ConnectionError(e.apiUrl(n),i.status,`reading the privileges of business process flow table '${t}' returned no 'Privileges' array (got ${(0,Wx.describeMalformedValue)(o)}), so which access it can grant is unknown.`);let a=o,s={},l=new Set;return Object.keys(Lv).forEach(u=>{let c=a.find(d=>d.PrivilegeType===Lv[u]);if(c){let d=(0,bc.normalizeGuid)(c.PrivilegeId,"PrivilegeId");s[u]=d,l.add(d)}}),{byAccess:s,all:l}}async function Iie(e,t){var r;let n=`/RetrieveRolePrivilegesRole(RoleId=${t})`,i=(0,Vp.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 $v.ConnectionError(e.apiUrl(n),i.status,`reading the privileges of role '${t}' returned no 'RolePrivileges' array (got ${(0,Wx.describeMalformedValue)(o)}), so what it holds is unknown.`);return new Set(o.map(a=>(0,bc.normalizeGuid)(a.PrivilegeId,"PrivilegeId")))}async function Oie(e,t,r){if(r.length===0)return;let n={Privileges:r.map(o=>({Depth:Tie,PrivilegeId:o}))},i=`/roles(${t})/Microsoft.Dynamics.CRM.AddPrivilegesRole`;(0,Vp.ensureSuccess)(await e.post(i,n),e.apiUrl(i))}async function Pie(e,t,r){let n={Privilege:{"@odata.type":"Microsoft.Dynamics.CRM.privilege",privilegeid:r}},i=`/roles(${t})/Microsoft.Dynamics.CRM.RemovePrivilegeRole`;(0,Vp.ensureSuccess)(await e.post(i,n),e.apiUrl(i))}async function Rie(e,t,r){var n,i,o;if(!r||r.length===0)return;let a=await Die(e,t.toLowerCase());for(let s of r){let l=(0,bc.normalizeGuid)(s.roleId,"roleId"),u=((n=s.access)!==null&&n!==void 0?n:[]).find(c=>!a.byAccess[c]);if(u!==void 0)throw new $v.InvalidArgumentError(`Cannot grant '${u}' access to role '${l}' on business process flow table '${t.toLowerCase()}': its metadata lists no '${(i=Lv[u])!==null&&i!==void 0?i:u}' privilege. No security role was changed.`)}for(let s of r){let l=(0,bc.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 Iie(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 Oie(e,l,f);for(let p of m)await Pie(e,l,p)}}Gp.reconcileBpfSecurityRoles=Rie});var iF=v(jp=>{"use strict";Object.defineProperty(jp,"__esModule",{value:!0});jp.bpfApi=void 0;var mr=Qi(),jx=Kl(),kie=Lt(),Qe=Q(),Ye=ye(),gn=le(),Lie=zx(),$ie=Lm(),vc=xm(),xie={"Content-Type":"application/json",Accept:"application/json"},xv={...xie,Prefer:"return=representation"},Fie=`category eq ${mr.WorkflowCategory.BusinessProcessFlow} and type eq ${mr.WorkflowTypeCode.Definition} and businessprocesstype eq ${mr.BusinessProcessType.BusinessFlow}`,Mie="workflowid,name,description,primaryentity,statecode,category,type,businessprocesstype,processorder",Uie="workflowid,name,uniquename,description,primaryentity,statecode,statuscode,category,type,businessprocesstype,processorder,xaml,clientdata",Bie=["xaml","name","description","processorder"];async function Wp(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,Lie.reconcileBpfSecurityRoles)(e,n,t.securityRoles)}async function Mv(e,t,r){let n={statecode:mr.StateCode.Activated,statuscode:mr.StatusCode.Activated},i=`/workflows(${t})`,{response:o,resent:a}=await nF(e,i,n,r,null);try{return(0,Ye.ensureSuccess)(o,e.apiUrl(i))}catch(s){throw a?tF(s):s}}var eF=new WeakSet;function tF(e){return typeof e=="object"&&e!==null&&eF.add(e),e}function rF(e){return typeof e=="object"&&e!==null&&eF.has(e)}function Hx(e){return e instanceof Qe.ConnectionError&&(e.statusCode===0||Ye.AMBIGUOUS_WRITE_STATUSES.has(e.statusCode))}async function nF(e,t,r,n,i){let o=n??i,a=0;try{return{response:await(0,Ye.resendWhile)(Ye.isConcurrencyLockRefusal,()=>{a+=1;let l=a===1?n:o,u={...xv};return l&&(u["If-Match"]=l),e.patch(t,r,{headers:u})},o?Ye.LOCK_BACKOFF_MS:[]),resent:a>1}}catch(s){throw a>1?tF(s):s}}async function Kx(e,t,r){return(0,Ye.readEtag)(await Mv(e,t,r))}function Jx(e,t){return new Qe.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. `+zp(e))}async function wc(e,t){var r;let n=`/workflows(${t})${(0,gn.odataQuery)([["$select","statecode"]])}`,i=(0,Ye.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 Qe.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 Fv(e,t,r,n,i=null){if((n??await wc(e,t))!==mr.StateCode.Activated)return{deactivated:!1,etag:null};let o={statecode:mr.StateCode.Draft,statuscode:mr.StatusCode.Draft},a=`/workflows(${t})`,s,l;try{({response:s,resent:l}=await nF(e,a,o,r,i))}catch(c){return await Yx(e,t,c,rF(c))}if(Ye.AMBIGUOUS_WRITE_STATUSES.has(s.status))return await Yx(e,t,new Qe.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,Ye.ensureSuccess)(s,e.apiUrl(a));return{deactivated:!0,etag:(0,Ye.readEtag)(u)}}async function Yx(e,t,r,n){let i;try{i=await wc(e,t)}catch{i=void 0}if(i===mr.StateCode.Draft&&!n)return{deactivated:!0,etag:null,uncertainCause:r};if(i===mr.StateCode.Activated)throw r;let o=new Qe.SdkError("BPF_DEACTIVATE_OUTCOME_UNKNOWN",i===mr.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,Qe.attachCause)(o,r),o}async function qie(e,t){let r=(0,gn.normalizeGuid)(t,"workflowid");try{return await Mv(e,r,null),"restored"}catch{return Uv(e,r)}}async function Vie(e,t,r){let n=(0,gn.normalizeGuid)(t,"workflowid");try{let i=await Mv(e,n,r);return{outcome:"restored",acknowledged:!0,echo:(0,Ye.readEtag)(i)}}catch(i){return i instanceof Qe.SdkError&&i.code===Ye.VERSION_CONFLICT_CODE?{outcome:"changed",acknowledged:!1,echo:null}:{outcome:await Uv(e,n),acknowledged:!1,echo:null}}}async function Uv(e,t){try{let r=await wc(e,t);return r===mr.StateCode.Activated?"restored":r===mr.StateCode.Draft?"disabled":"unknown"}catch{return"unknown"}}async function Qx(e,t,r,n){return r?{...await Vie(e,t,r),attempted:!0}:n?{outcome:await Uv(e,(0,gn.normalizeGuid)(t,"workflowid")),attempted:!1,acknowledged:!1,echo:null}:{outcome:await qie(e,t),attempted:!0,acknowledged:!1,echo:null}}function Gie(e,t){let r=new Qe.SdkError(vc.WORKFLOW_DELETE_UNSETTLED_CODE,`Deleting business process flow '${e}' failed${(0,vc.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,Qe.attachCause)(r,t),r}function Xx(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 Qe.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 Qe.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 Qe.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,Qe.attachCause)(s,n),s}async function Wie(e,t){try{return await wc(e,t),"survived"}catch(r){return r instanceof Qe.ConnectionError&&r.statusCode===404?"removed":"unknown"}}async function zie(e,t,r){if(r)try{let{deactivated:n,etag:i}=await Fv(e,t,r),o=n?i:r;if(o)return await(0,vc.deleteWorkflowResending)(e,t,{bindingToken:o,kindName:"business process flow",resendDeadlockVictim:!0,ifMatchOnFirst:!0}),"removed"}catch{}return Wie(e,t)}function zp(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 Zx(e,t){return new Qe.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. ${zp(e)}`)}function jie(e,t){let r=new Qe.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.) ${zp(e)} Or delete it. Original failure: ${t instanceof Error?t.message:String(t)}`);return(0,Qe.attachCause)(r,t),r}function Hie(e,t){let r=new Qe.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. ${zp(e)} Or delete it. Original failure: ${t instanceof Error?t.message:String(t)}`);return(0,Qe.attachCause)(r,t),r}function Kie(e,t){let r=new Qe.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,Qe.attachCause)(r,t),r}function Bv(e){let t={};for(let r of Bie)e[r]!==void 0&&(t[r]=e[r]);return t}var Jie=["name,processorder","description,name,processorder"];function Yie(e){let{xaml:t,...r}=Bv(e);return typeof t=="string"&&Jie.includes(Object.keys(r).sort().join(","))}async function Qie(e,t,r,n){let{xaml:i,...o}=Bv(r),[,a]=await(0,jx.sendChangeSet)(e,[{method:"PATCH",path:`/workflows(${t})`,body:o,etag:n},{method:"PATCH",path:`/workflows(${t})${(0,gn.odataQuery)([["$select","workflowid"]])}`,body:{xaml:i},headers:{Prefer:"return=representation"}}],`business process flow '${t}'`,{resendWhileLockRefused:!0});return(0,Ye.readEtag)((0,jx.partResponse)(a))}jp.bpfApi={async get(e,t){let n=`/workflows(${(0,gn.normalizeGuid)(t,"id")})${(0,gn.odataQuery)([["$select",Uie]])}`,i=(0,Ye.ensureSuccess)(await e.get(n),e.apiUrl(n));return{raw:i.body,etag:(0,Ye.readEtag)(i)}},async list(e,t){let r=[Fie];t?.entityLogicalName&&r.push(`primaryentity eq '${(0,gn.odataLiteral)(t.entityLogicalName)}'`);let n=`/workflows${(0,gn.odataQuery)([["$select",Mie],["$filter",r.join(" and ")]])}`;return(await(0,kie.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,gn.normalizeGuid)(r.record.workflowid,"workflowid"),i="/workflows",o=(0,Ye.ensureSuccess)(await e.post(i,r.record,{headers:xv}),e.apiUrl(i)),a=(0,Ye.readEtag)(o);if(!a)throw Zx(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 Kx(e,n,a)),await Wp(e,r)}catch(l){let u=await zie(e,n,s);throw u==="survived"?jie(n,l):u==="unknown"?Hie(n,l):l instanceof Qe.SdkError&&l.code===Ye.VERSION_CONFLICT_CODE?Kie(n,l):l}if(!s)throw Zx(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,gn.normalizeGuid)(t,"id"),a=(0,Ye.requireEtag)(n,"bpf",o),s=await wc(e,o);if(s===mr.StateCode.Activated&&i.status==="Active"&&e.supportsAtomicBatch&&Yie(i.record)){let p=await Qie(e,o,i.record,a);return await Wp(e,i),{id:o,etag:p}}let{deactivated:l,etag:u,uncertainCause:c}=await Fv(e,o,a,s),d=u,f=!1,m=!1;try{if(c!==void 0)throw c;let p=a;if(l){if(!u)throw Jx(o,"deactivation");p=u}let h=`/workflows(${o})`,g;try{g=(0,Ye.ensureSuccess)(await e.patch(h,Bv(i.record),{headers:{...xv,"If-Match":p}}),e.apiUrl(h))}catch(w){throw Hx(w)&&(d=null),w}let b=(0,Ye.readEtag)(g);if(d=b,i.status==="Active"){if(!b)throw Jx(o,"definition write");try{b=await Kx(e,o,b)}catch(w){throw Hx(w)&&(d=null),m=(0,Ye.isConcurrencyLockRefusalError)(w),w}f=!0}return await Wp(e,i),{id:o,etag:b}}catch(p){if(l&&!f){let{outcome:h,attempted:g,acknowledged:b,echo:w}=await Qx(e,o,d,rF(p));if(m&&b)return f=!0,await Wp(e,i),{id:o,etag:w};if(h!=="restored")throw Xx(o,"to apply an edit, the edit failed",h,p,g)}throw p}},async delete(e,t){let r=(0,gn.normalizeGuid)(t,"id"),n=await(0,$ie.assertWorkflowKind)(e,r,mr.WorkflowCategory.BusinessProcessFlow),{deactivated:i,etag:o}=await Fv(e,r,null,void 0,n);try{await(0,vc.deleteWorkflowResending)(e,r,{bindingToken:i?o:n,kindName:"business process flow",deactivated:i,resendDeadlockVictim:!0})}catch(a){if(i&&!(0,vc.isWorkflowDeleteUnsettled)(a)){let{outcome:s,attempted:l}=await Qx(e,r,o,!1);if(s==="changed")throw Gie(r,a);if(s!=="restored")throw Xx(r,"so it could be deleted, the delete failed",s,a,l)}throw a}}}});var qF=v(fl=>{"use strict";Object.defineProperty(fl,"__esModule",{value:!0});fl.bpfRegistration=fl.BpfAdapter=void 0;var Hp=Qi(),Xie=iF(),qv=so(),Ra=uo(),yF=lo(),Hr=rn(),Mr=pt(),Fn=Q(),Zie=100,Vv='<?xml version="1.0" encoding="utf-16"?>',oF=1033,bF="mxswa:Workflow",eoe="mxswa:ActivityReference.Properties",toe="mcwo:StepLabel",roe="mcwb:Control",aF="mcwb:Control.ControlDisplayName",vF="mcwb:Control.DataFieldName",wF="DataFieldName",sF="ControlDisplayName",CF="Literal",Jp="x:Null",lF="x:String",Gv="x:Key",Wv="DisplayName",Qp="Activities",noe="StepLabels",EF="StageId",AF="StageCategory",SF="NextStageId",NF="ProcessStepId",Kp="IsProcessRequired",_F="EntityComposite",TF="StageComposite",DF="StepComposite";function Cc(e){return(0,Hr.isJsonObject)(e)?e:{}}function ci(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 ka(e,t){var r;return(r=ci(e).find(n=>n.tagName===t))!==null&&r!==void 0?r:null}function fi(e){return ka(e,eoe)}function hr(e,t){var r;return(r=ci(e).find(n=>n.getAttribute(Gv)===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 di(e){var t;return!e||!e.firstChild?"":(t=e.firstChild.nodeValue)!==null&&t!==void 0?t:""}function IF(e,t,r){e.firstChild?e.firstChild.nodeValue=r:e.appendChild(t.createTextNode(r))}function Ec(e){var t;let r=(t=e.getAttribute(Wv))!==null&&t!==void 0?t:"",n=r.indexOf(": ");return n>=0?r.slice(n+2):r}function OF(e,t){var r;let n=(r=e.getAttribute(Wv))!==null&&r!==void 0?r:"",i=n.indexOf(": ");e.setAttribute(Wv,i>=0?n.slice(0,i+2)+t:t)}function PF(e,t){let r=hr(e,noe),n=ka(r,toe);n&&n.setAttribute("Description",t)}function ioe(e){let t=hr(e,AF);if(!t||t.tagName===Jp)return;let r=di(t).trim();return r===""?void 0:Number(r)}function ooe(e){let t=hr(e,SF);if(!t||t.tagName===Jp)return;let r=di(t).trim();return r===""?void 0:r}function RF(e){let t=kF(e);if(!t)return;let r=$F(t,wF,vF);return r===""?void 0:r}function zv(e,t){let r=ci(e);for(;r.length>0;){let n=r.pop();if(n.tagName===t)return n;for(let i of ci(n))r.push(i)}return null}function kF(e){let t=hr(fi(e),Qp);return t?zv(t,roe):null}function LF(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 $F(e,t,r){var n;return LF(e,t)?(n=e.getAttribute(t))!==null&&n!==void 0?n:"":coe(e,r)}function uF(e,t,r,n){if(LF(e,t)){e.setAttribute(t,n);return}if(ka(e,r)){aoe(e,r,n);return}throw new Fn.InvalidArgumentError(`BPF step control exposes neither a '${t}' attribute nor a <${r}> wrapper to bind a column`)}function aoe(e,t,r){let n=ka(e,t),i=n?zv(n,CF):null;if(!i)throw new Fn.InvalidArgumentError(`BPF step control's <${t}> wrapper holds no <Literal> to bind a column`);i.setAttribute("Value",r)}function xF(e){return Ec(e)}function Xp(e){let t=ka(e,bF),r=[];for(let n of ci(t).filter(i=>dl(i,_F))){let i=hr(fi(n),Qp);for(let o of ci(i).filter(a=>dl(a,TF)))r.push({el:o,entity:xF(n)})}return r}function jv(e){let t=hr(fi(e),Qp);return ci(t).filter(r=>dl(r,DF))}function soe(e){let t=fi(e),r=di(hr(t,Kp)).trim().toLowerCase(),n=RF(e),i={id:di(hr(t,NF)),name:Ec(e)};return n!==void 0&&(i.fieldName=n),r==="true"&&(i.required=!0),i}function loe(e,t){let r=fi(e),n=ioe(r),i=ooe(r),o={id:di(hr(r,EF)),name:Ec(e),entityLogicalName:t,steps:jv(e).map(soe)};return n!==void 0&&(o.category=n),i!==void 0&&(o.nextStageId=i),o}function uoe(e){return Xp(e).map(({el:t,entity:r})=>loe(t,r))}function ui(e){return new Fn.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 coe(e,t){var r;let n=ka(e,t),i=n?zv(n,CF):null;return(r=i?.getAttribute("Value"))!==null&&r!==void 0?r:""}function Hv(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(Hv(e,s)):s.nodeType===3&&n.appendChild(e.createTextNode((r=s.nodeValue)!==null&&r!==void 0?r:""))}return n}function FF(e){return hr(fi(e),Qp)}function doe(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,Mr.newId)(),{body:a}=Zp(Kv(i,(0,Mr.newId)(),t.id,o));return Hv(e,Xp((0,Ra.parseXmlRoot)(a,"<Activity/>"))[0].el)}function foe(e,t){let{body:r}=Zp(Kv("account",(0,Mr.newId)(),(0,Mr.newId)(),t.id));return Hv(e,jv(Xp((0,Ra.parseXmlRoot)(r,"<Activity/>"))[0].el)[0])}function MF(e,t){for(;e.firstChild;)e.removeChild(e.firstChild);for(let r of t)e.appendChild(r)}function UF(e,t,r,n){let i=hr(e,r);if(!i||!i.parentNode){if(n!==void 0&&n!=="")throw ui(`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!==Jp&&di(i).trim()!==""){let s=t.createElement(Jp);s.setAttribute(Gv,r),o.replaceChild(s,i)}return}if(i.tagName===lF){di(i).trim()!==n&&IF(i,t,n);return}let a=t.createElement(lF);a.setAttribute(Gv,r),a.appendChild(t.createTextNode(n)),o.replaceChild(a,i)}function poe(e,t,r){UF(e,t,AF,r===void 0?void 0:String(r))}function moe(e,t,r){UF(e,t,SF,r)}function BF(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 cF(e){return di(hr(fi(e),EF))}function dF(e){return di(hr(fi(e),NF))}function fF(e,t,r){var n,i,o,a;let s=fi(e);r.name!==Ec(e)&&(OF(e,r.name),PF(s,r.name));let l=di(hr(s,Kp)).trim().toLowerCase()==="true";if(((n=r.required)!==null&&n!==void 0?n:!1)!==l){let u=hr(s,Kp);if(!u)throw ui(`setting '${Kp}' on a step whose xaml does not expose that slot`);IF(u,t,r.required?"True":"False")}if(((i=r.fieldName)!==null&&i!==void 0?i:"")!==((o=RF(e))!==null&&o!==void 0?o:"")){let u=kF(e);if(!u)throw new Fn.InvalidArgumentError("BPF step has no <mcwb:Control> element to bind a column to");let c=(a=r.fieldName)!==null&&a!==void 0?a:"";uF(u,wF,vF,c),c!==""&&$F(u,sF,aF)===""&&uF(u,sF,aF,c)}}function pF(e,t,r,n){var i;let o=fi(e);if(!o)throw new Fn.InvalidArgumentError("BPF stage composite has no <\u2026ActivityReference.Properties>");if(r.name!==Ec(e)&&(OF(e,r.name),PF(o,r.name)),poe(o,t,r.category),moe(o,t,n),r.relationshipName&&r.relationshipName.trim()!=="")throw ui("a stage relationship / table change (multi-table authoring)");if(r.actions&&r.actions.length>0||r.branch)throw ui("stage actions or conditional branching");let a=FF(e);if(!a)throw new Fn.InvalidArgumentError("BPF stage has no [Activities] collection");let s=(i=r.steps)!==null&&i!==void 0?i:[];if(s.length===0)throw new Fn.InvalidArgumentError(`BPF stage '${r.name}' must have at least one step`);let l=jv(e);if(BF(l,s.map(d=>d.id),dF)){l.forEach((d,f)=>fF(d,t,s[f]));return}let u=new Map(l.map(d=>[dF(d),d]));if(ci(a).some(d=>!dl(d,DF)))throw ui("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:foe(t,d)});MF(a,c),c.forEach((d,f)=>fF(d,t,s[f]))}function hoe(e,t,r){let n=ka(e,bF);if(!n)throw new Fn.InvalidArgumentError("BPF xaml has no <mxswa:Workflow> root activity");if(r.globalActions&&r.globalActions.length>0)throw ui("global (process-completed/abandoned) actions");if(!r.stages||r.stages.length===0)throw new Fn.InvalidArgumentError("a BPF must have at least one stage");let i=Xp(e),o=i.map(f=>f.el);if(BF(o,r.stages.map(f=>f.id),cF)){i.forEach(({el:f,entity:m},p)=>{let h=r.stages[p];if(h.entityLogicalName&&h.entityLogicalName.trim()!==""&&h.entityLogicalName!==m)throw ui(`changing a stage's table ('${h.entityLogicalName}' vs the process's '${m}')`);pF(f,t,h,h.nextStageId)});return}let a=ci(n).filter(f=>dl(f,_F));if(a.length!==1)throw ui("adding, removing or reordering stages on a multi-table process");let s=a[0],l=xF(s),u=FF(s);if(!u)throw new Fn.InvalidArgumentError("BPF primary entity composite has no [Activities] collection");if(ci(u).some(f=>!dl(f,TF)))throw ui("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 ui(`a stage on a different table ('${f.entityLogicalName}') than the process primary ('${l}')`);let c=new Map(o.map(f=>[cF(f),f])),d=r.stages.map(f=>{var m;return(m=c.get(f.id))!==null&&m!==void 0?m:doe(t,f,l)});MF(u,d),d.forEach((f,m)=>{let p=m<d.length-1?r.stages[m+1].id:void 0;pF(f,t,r.stages[m],p)})}function Zp(e){let t=e.match(/^<\?xml[^>]*\?>\s*/),r=t?t[0]:"";return{prolog:r,body:e.slice(r.length)}}function goe(e){var t,r,n,i,o,a;(0,yF.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,qv.mergeAttrs)(s.a,[]),c:(0,qv.spliceChildren)(s.c,[])};return{root:(0,qv.rebuildRaw)(m,(0,Ra.domEngine)(f),null),prolog:(n=(r=e.bag)===null||r===void 0?void 0:r.xamlProlog)!==null&&n!==void 0?n:Vv,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=Kv(e.entityLogicalName,(0,Mr.newId)(),l?.id&&l.id.trim()!==""?l.id:(0,Mr.newId)(),u?.id&&u.id.trim()!==""?u.id:(0,Mr.newId)()),{body:d}=Zp(c);return{root:(0,Ra.parseXmlRoot)(d,"<Activity/>"),prolog:Vv,eol:"lf"}}function yoe(e){let{root:t,prolog:r,eol:n}=goe(e);hoe(t,t.ownerDocument,e);let i=(0,Ra.serializeNode)(t);return n==="crlf"&&(i=i.replace(/\n/g,`\r-`)),r+i}function boe(e){return e.uniqueName&&e.uniqueName.trim()!==""?e.uniqueName:`new_${(e.name||"businessprocessflow").toLowerCase().replace(/[^a-z0-9]/g,"")||"businessprocessflow"}`}var Yp=class{toArtifact(t){return t}fromArtifact(t){return t}fromApiResponse(t){var r,n;(0,yF.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}=Zp(o),u=(0,Ra.parseXmlRoot)(l,"<Activity/>");a.stages=uoe(u),a.bag={xaml:(0,Ra.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,Mr.newId)(),name:t.name,uniquename:boe(t),primaryentity:t.entityLogicalName,xaml:yoe(t),category:Hp.WorkflowCategory.BusinessProcessFlow,type:Hp.WorkflowTypeCode.Definition,businessprocesstype:Hp.BusinessProcessType.BusinessFlow,scope:Hp.WorkflowScope.Organization,processorder:(r=t.order)!==null&&r!==void 0?r:Zie};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 Fn.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(hF):[hF({id:(0,Mr.newId)(),name:"New Stage",steps:[]})],a={id:t.id&&t.id.trim()!==""?t.id:(0,Mr.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=Cc(t);(typeof r.id!="string"||r.id.trim()==="")&&(r.id=(0,Mr.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,Hr.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,Hr.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=Cc(l),f=typeof d.id=="string"?d.id.trim():"";f===""?r.push((0,Hr.issue)(`${c}/id`,"stage-id-required","a stage needs an id")):a.has(f.toLowerCase())?r.push((0,Hr.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,Hr.issue)(`${c}/steps`,"stage-needs-step","a BPF stage must have at least one step")),m.length>30&&r.push((0,Hr.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 Cc(h).id=="string"?h.id.trim():"";w===""?r.push((0,Hr.issue)(`${b}/id`,"step-id-required","a step needs an id")):p.has(w.toLowerCase())?r.push((0,Hr.issue)(`${b}/id`,"step-id-duplicate",`two steps in this stage share the id '${h.id}'`)):p.set(w.toLowerCase(),g)}),d.branch&&!mF(i,d.branch.nextStageId)&&r.push((0,Hr.issue)(`${c}/branch/nextStageId`,"branch-target-unknown",`branch nextStageId '${d.branch.nextStageId}' does not match any stage id`)),typeof d.nextStageId=="string"&&d.nextStageId!==""&&!mF(i,d.nextStageId)&&r.push((0,Hr.issue)(`${c}/nextStageId`,"next-stage-unknown",`nextStageId '${d.nextStageId}' does not match any stage id`))}),o.size>5&&r.push((0,Hr.issue)("/stages","too-many-tables",`a BPF spans at most 5 tables, got ${o.size}`));let s=voe(i);return s>=0&&r.push((0,Hr.issue)(`/stages/${s}/nextStageId`,"next-stage-cycle","the stage nextStageId links form a cycle; the flow must be acyclic")),r}};fl.BpfAdapter=Yp;function voe(e){let t=new Map(e.map(r=>[Cc(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 mF(e,t){return e.some(r=>Cc(r).id===t)}function hF(e){var t,r;let n=e.steps&&e.steps.length>0?e.steps.map(gF):[gF({id:(0,Mr.newId)(),name:"New Step"})],i={id:e.id&&e.id.trim()!==""?e.id:(0,Mr.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 gF(e){var t;let r={id:e.id&&e.id.trim()!==""?e.id:(0,Mr.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 Kv(e,t,r,n){return`${Vv}<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="${oF}" /></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="${oF}" /></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 woe(){return{adapter:new Yp,api:Xie.bpfApi,languageSensitive:!0}}fl.bpfRegistration=woe});var VF=v(em=>{"use strict";Object.defineProperty(em,"__esModule",{value:!0});em.buildRegistrations=void 0;var Coe=Lk(),Eoe=eL(),Aoe=x1(),Soe=e$(),Noe=N$(),_oe=W$(),Toe=sx(),Doe=Gx(),Ioe=qF();function Ooe(e){let t=new Map;return t.set("form",(0,Coe.formRegistration)(e)),t.set("view",(0,Eoe.viewRegistration)()),t.set("businessRule",(0,Aoe.businessRuleRegistration)()),t.set("app",(0,Soe.appRegistration)(e)),t.set("command",(0,Noe.commandRegistration)()),t.set("chart",(0,_oe.chartRegistration)()),t.set("dashboard",(0,Toe.dashboardRegistration)(e)),t.set("genPage",(0,Doe.genPageRegistration)()),t.set("bpf",(0,Ioe.bpfRegistration)()),t}em.buildRegistrations=Ooe});var rM=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 zi=Lt(),yn=ye(),qe=le(),GF=pt(),Ve=Q();Te.AI_GATE={formFill:"FormFillBarUXEnabled",formFillSuggestions:"FormPredictEnabled",formFillSmartPaste:"FormPredictSmartPasteEnabled",formFillFiles:"FormFillFileUploadEnabled",nlSearch:"EnableNLGridSearch",nlChart:"NLChartVisualizationSetting",summaries:"EnableFormInsights",m365:"m365copilotmodelappenabled"};var JF={formFill:"FormFillBarUXEnabled",formFillSuggestions:"FormPredictEnabled",formFillSmartPaste:"FormPredictSmartPasteEnabledOnByDefault",formFillFiles:"FormFillFileUploadEnabled",nlSearch:"NLGridSearchSetting",nlChart:"NLChartDataVisualizationSetting",m365:"m365copilotmodelappenabled"},Poe=new Set(Object.entries(Te.AI_GATE).filter(([e,t])=>JF[e]===t).map(([e])=>e)),Roe={formFill:{enabled:"2",disabled:"1"},formFillSuggestions:{enabled:"2",disabled:"1"},formFillSmartPaste:{enabled:"2",disabled:"1"},formFillFiles:{enabled:"2",disabled:"1"}};function Jv(e){return Roe[e]}var tm=1e6;function koe(e,t){let r=Jv(t),n=()=>{throw new Ve.InvalidArgumentError(`setAppAiFeatures: '${t}' must be a boolean or an integer between 0 and ${tm} (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>tm?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(tm).length||Number(s)>tm?n():s}}return n()}function Loe(e,t){let r=Jv(t);return r?e===r.enabled:e!=="0"}async function $oe(e,t){var r,n;let i=`/appmodules${(0,qe.odataQuery)([["$select","appmoduleid"],["$filter",`uniquename eq '${(0,qe.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 Ve.ConnectionError(e.apiUrl(i),o.status,`the app lookup for '${t}' returned a malformed answer \u2014 expected an OData 'value' array but got ${(0,zi.describeMalformedValue)(a)}`);return(n=a[0])===null||n===void 0?void 0:n.appmoduleid}async function xoe(e,t){var r,n;let i=`/appmodules${(0,qe.odataQuery)([["$select","appmoduleid"],["$filter",`uniquename eq '${(0,qe.odataLiteral)(t)}'`]])}`,o;try{o=await e.get(i)}catch(l){throw new Ve.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 Ve.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 Ve.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 Ve.InvalidArgumentError(`setAppAiFeatures: cannot confirm that the supplied appModuleId belongs to app '${t}' \u2014 the lookup returned a row with no appmoduleid.`);return s}var WF=new WeakMap;async function Foe(e,t){var r,n;let i=WF.get(e);if(i||(i=new Map,WF.set(e,i)),i.has(t))return i.get(t);let o=`/settingdefinitions${(0,qe.odataQuery)([["$select","settingdefinitionid"],["$filter",`uniquename eq '${(0,qe.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 Ve.ConnectionError(e.apiUrl(o),a.status,`the setting definition lookup returned a malformed answer \u2014 expected an OData 'value' array but got ${(0,zi.describeMalformedValue)(s)}`);let l=(n=s[0])===null||n===void 0?void 0:n.settingdefinitionid;return l&&i.set(t,l),l}async function Moe(e,t,r){var n,i;let o=await Foe(e,r);if(!t||!o)return;let a=`/appsettings/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()${(0,qe.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 Ve.ConnectionError(e.apiUrl(a),s.status,`the app-scope override read returned a malformed answer \u2014 expected an OData 'value' array but got ${(0,zi.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 Uoe=4,Boe=500,zF=20,jF=3e4;function qoe(e){if(e===void 0)return Uoe;if(!Number.isFinite(e))throw new Ve.InvalidArgumentError(`setAppAiFeatures: verifyAttempts must be a finite integer between 1 and ${zF}; got ${e}.`);return Math.min(zF,Math.max(1,Math.floor(e)))}function Voe(e){if(e===void 0)return Boe;if(!Number.isFinite(e))throw new Ve.InvalidArgumentError(`setAppAiFeatures: verifyDelayMs must be a finite number between 0 and ${jF}; got ${e}.`);return Math.min(jF,Math.max(0,Math.floor(e)))}async function Goe(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 Moe(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 YF(e,t,r){if(t===2)return String(e).toLowerCase()==="true";let n=r?Jv(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,qe.odataPathLiteral)(t)}'`];r.appUniqueName&&i.push(`AppUniqueName='${(0,qe.odataPathLiteral)(r.appUniqueName)}'`);let o=`/RetrieveSetting(${i.join(",")})`,a=(0,yn.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 Ve.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 QF(e,t,r,n={}){let i={SettingName:t,Value:r};n.appUniqueName&&(i.AppUniqueName=n.appUniqueName),n.solutionUniqueName&&(i.SolutionUniqueName=n.solutionUniqueName),(0,yn.ensureSuccess)(await e.post("/SaveSettingValue",i),e.apiUrl("/SaveSettingValue"))}Te.saveSettingValue=QF;async function Woe(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:YF(o,a,n),setting:i,value:o}}return r}Te.getAiReadiness=Woe;async function zoe(e,t,r,n={}){var i;if(!t||!t.trim())throw new Ve.InvalidArgumentError("setAppAiFeatures: a non-empty appUniqueName is required (an empty value would write the setting at organization scope, affecting every app).");let o=qoe(n.verifyAttempts),a=Voe(n.verifyDelayMs),s=[];for(let[p,h]of Object.entries(r)){if(h===void 0)continue;let g=JF[p];g&&s.push({feature:p,setting:g,requestedValue:koe(h,p)})}let l=[],u=n.appModuleId?(0,qe.normalizeGuid)(n.appModuleId,"appModuleId"):void 0;if(u){let p=await xoe(e,t);if(p&&(0,qe.normalizeGuid)(p,"appModuleId")!==u)throw new Ve.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 $oe(e,t)),c),f=new Map,m=async p=>{if(Poe.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:YF(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 QF(e,h,g,{appUniqueName:t,solutionUniqueName:n.solutionUniqueName});let b=await Goe(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=Loe(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=zoe;var XF="GptPowerPrompt",joe='{ "consumptionSource": "Api", "partnerSource": "AIBuilder", "consumptionSourceVersion": "GptApiClient"}';function ZF(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=ZF;async function Hoe(e,t){var r;let n=`/EntityDefinitions(LogicalName='${(0,qe.odataPathLiteral)(t)}')${(0,qe.odataQuery)([["$select","MetadataId"]])}`,i=(0,yn.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 Ve.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,zi.describeMalformedValue)(o)}`);return o}function Yv(e,t,r,n){if(e.length===0)return;let i=e[0];if(typeof i!="object"||i===null||Array.isArray(i))throw new Ve.ConnectionError(t,r,`${n} returned a malformed row \u2014 expected an object but got ${Array.isArray(i)?"an array":(0,zi.describeMalformedValue)(i)}`);return i}async function eM(e){var t;let r=`/msdyn_aitemplates${(0,qe.odataQuery)([["$select","msdyn_aitemplateid"],["$filter",`msdyn_uniquename eq '${XF}'`],["$top",1]])}`,n=(0,yn.ensureSuccess)(await e.get(r),e.apiUrl(r)),i=(t=n.body)===null||t===void 0?void 0:t.value;if(!Array.isArray(i))throw new Ve.ConnectionError(e.apiUrl(r),n.status,`the row-summary template lookup returned a malformed answer \u2014 expected an OData 'value' array but got ${(0,zi.describeMalformedValue)(i)}`);let o=Yv(i,e.apiUrl(r),n.status,"the row-summary template lookup");if(!o)return;let a=o.msdyn_aitemplateid;if(typeof a=="string"&&a!=="")try{return(0,qe.normalizeGuid)(a,"msdyn_aitemplateid")}catch{}throw new Ve.ConnectionError(e.apiUrl(r),n.status,`the row-summary template lookup returned a malformed row \u2014 expected a GUID 'msdyn_aitemplateid' but got ${a===""?"an empty string":typeof a=="string"?"a string that is not a GUID":(0,zi.describeMalformedValue)(a)}`)}function tM(e){return`${e} row summary`}async function Koe(e,t,r){var n;let i=`/msdyn_aimodels(${t})${(0,qe.odataQuery)([["$select","msdyn_name,_msdyn_templateid_value"]])}`,o=await e.get(i);if(o.status===404)return!1;let a=(n=(0,yn.ensureSuccess)(o,e.apiUrl(i)).body)!==null&&n!==void 0?n:{},s=await eM(e);return typeof a.msdyn_name=="string"&&a.msdyn_name.toLowerCase()===tM(r).toLowerCase()&&typeof a._msdyn_templateid_value=="string"&&s!==void 0&&a._msdyn_templateid_value.toLowerCase()===s.toLowerCase()}async function Joe(e,t,r={}){var n;let i=`ais_RowSummary_${t.entityLogicalName}`,o=`/aiskillconfigs${(0,qe.odataQuery)([["$select","aiskillconfigid,_aimodel_value"],["$filter",`uniquename eq '${(0,qe.odataLiteral)(i)}'`],["$top",1]])}`,a=(0,yn.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 Ve.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,zi.describeMalformedValue)(s)}`);let l=Yv(s,e.apiUrl(o),a.status,"the existing row-summary skill lookup");if(l)return{modelId:l._aimodel_value,aiSkillConfigId:l.aiskillconfigid};let u=await Hoe(e,t.entityLogicalName),c=await eM(e);if(c===void 0)throw new Ve.SdkError(Te.ROW_SUMMARY_TEMPLATE_NOT_FOUND_CODE,`Cannot configure the row summary of '${t.entityLogicalName}': this org has no AI template '${XF}' (msdyn_aitemplates), which a row-summary model is built from. Nothing was written.`);let d=(0,GF.newId)(),f=(0,GF.newId)(),m=JSON.stringify(ZF(t)),p={ModelId:d,RunConfigurationId:f,ModelName:tM(t.entityLogicalName),TemplateId:c,CustomConfiguration:m,Source:joe,RunConfiguration:""};(0,yn.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,yn.ensureSuccess)(await e.post("/aiskillconfigs",h),e.apiUrl("/aiskillconfigs")),b=(0,yn.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=Joe;async function Yoe(e,t){var r;let n=`ais_RowSummary_${t.entityLogicalName}`,i=`/aiskillconfigs${(0,qe.odataQuery)([["$select","aiskillconfigid,_aimodel_value"],["$filter",`uniquename eq '${(0,qe.odataLiteral)(n)}'`],["$top",1]])}`,o=(0,yn.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 Ve.ConnectionError(e.apiUrl(i),o.status,`the row-summary skill lookup returned a malformed answer \u2014 expected an OData 'value' array but got ${(0,zi.describeMalformedValue)(a)}`);let s=Yv(a,e.apiUrl(i),o.status,"the row-summary skill lookup");if(!s)return{removed:!1};let l=(0,qe.normalizeGuid)(s.aiskillconfigid,"aiskillconfigid"),u=s._aimodel_value?(0,qe.normalizeGuid)(s._aimodel_value,"_aimodel_value"):void 0,c=u?await Koe(e,u,t.entityLogicalName):!1,d=t.entityLogicalName,f=`/aiskillconfigs(${l})`,m=await HF(e,f,`${f}${(0,qe.odataQuery)([["$select","aiskillconfigid"]])}`);if(m.kind==="failed")throw m.stillThere===void 0&&u&&c?(0,Ve.attachCause)(new Ve.SdkError(Te.ROW_SUMMARY_REMOVAL_UNCONFIRMED_CODE,`Removing the row summary of '${d}' could not be confirmed: deleting its skill row failed (${KF(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 HF(e,p,`${p}${(0,qe.odataQuery)([["$select","msdyn_aimodelid"]])}`,Xoe);if(h.kind==="failed")throw(0,Ve.attachCause)(new Ve.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"} (${KF(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)}return{removed:!0}}Te.removeRowSummary=Yoe;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 Qoe="0x8004f01f";function Xoe(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()===Qoe}function Zoe(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 HF(e,t,r,n=()=>!1){let i;try{let o=await(0,yn.resendWhile)(Zoe,()=>e.delete(t));if(o.status>=200&&o.status<300||o.status===404)return{kind:"gone"};if(n(o))return{kind:"kept"};try{(0,yn.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 KF(e){return e instanceof Error?e.message:String(e)}});var oM=v(pl=>{"use strict";Object.defineProperty(pl,"__esModule",{value:!0});pl.findArtifact=pl.resolveArtifact=void 0;var qt=le(),ji=$d(),eae=zd(),tae=Lt(),rae=ye(),nM=Q();async function iM(e,t,r){let n="/uxagentprojects"+(0,qt.odataQuery)([["$select","uxagentprojectid,name"],["$filter",`name eq '${(0,qt.odataLiteral)(t)}'`],...r!==void 0?[["$top",String(r)]]:[]]);return(await(0,tae.collectPages)(e,n,"resolveArtifact('genPage')",void 0,{headers:{"MSCRM.IncludeUnpublished":"true"}})).map(o=>({id:String(o.uxagentprojectid),name:String(o.name)}))}async function nae(e,t,r){var n,i,o,a,s,l,u,c,d,f,m,p;switch(t){case"app":{let h=(0,eae.unpublishedAppModulesQuery)("appmoduleid,name,appmoduleidunique",`uniquename eq '${(0,qt.odataLiteral)((n=r.uniqueName)!==null&&n!==void 0?n:"")}'`,1),b=(i=(0,rae.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,ji.queryRecords)(e,"systemform",{select:["formid","name"],filter:`name eq '${(0,qt.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,ji.queryRecords)(e,"appaction",{select:["appactionid","buttonlabeltext"],filter:`contextvalue eq '${(0,qt.odataLiteral)(r.entity)}'`,top:1});return h&&h.length?[{id:r.entity,entity:r.entity}]:[]}case"form":return(await(0,ji.queryRecords)(e,"systemform",{select:["formid","name"],filter:`name eq '${(0,qt.odataLiteral)((a=r.name)!==null&&a!==void 0?a:"")}' and objecttypecode eq '${(0,qt.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,ji.queryRecords)(e,"savedqueryvisualization",{select:["savedqueryvisualizationid","name"],filter:`name eq '${(0,qt.odataLiteral)((l=r.name)!==null&&l!==void 0?l:"")}' and primaryentitytypecode eq '${(0,qt.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,ji.queryRecords)(e,"savedquery",{select:["savedqueryid","name"],filter:`name eq '${(0,qt.odataLiteral)((c=r.name)!==null&&c!==void 0?c:"")}' and returnedtypecode eq '${(0,qt.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,ji.queryRecords)(e,"webresource",{select:["webresourceid","name"],filter:`name eq '${(0,qt.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,ji.queryRecords)(e,"solution",{select:["solutionid","uniquename"],filter:`uniquename eq '${(0,qt.odataLiteral)((m=r.uniqueName)!==null&&m!==void 0?m:"")}'`,top:1})||[]).map(g=>({id:String(g.solutionid),name:String(g.uniquename)}));case"genPage":return iM(e,(p=r.name)!==null&&p!==void 0?p:"");default:return[]}}pl.resolveArtifact=nae;async function iae(e,t,r){var n,i,o,a,s,l;let u=(0,qt.odataLiteral)((n=r.name)!==null&&n!==void 0?n:""),c=(0,qt.odataLiteral)((i=r.entity)!==null&&i!==void 0?i:"");if(t==="command"){if(!r.entity)return null;let h=await(0,ji.queryRecords)(e,"appaction",{select:["appactionid"],filter:`contextvalue eq '${(0,qt.odataLiteral)(r.entity)}'`,top:1});return h&&h.length?r.entity:null}if(t==="genPage"){let h=await iM(e,(o=r.name)!==null&&o!==void 0?o:"",2);if(h.length>1)throw new nM.AmbiguousArtifactError(t,(a=r.name)!==null&&a!==void 0?a:"",h.length);return h.length===1?h[0].id:null}let d=oae(t,u,c,r),f=t!=="app",m=await(0,ji.queryRecords)(e,d.set,{select:[d.idField],filter:d.filter,top:f?2:1});if(f&&m&&m.length>1)throw new nM.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}pl.findArtifact=iae;function oae(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,qt.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 sM=v(im=>{"use strict";Object.defineProperty(im,"__esModule",{value:!0});im.seedRecordGraph=void 0;var aM=$d(),aae=bd(),nm=le(),sae=Q();async function lae(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,aae.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 k of f.records){let I={...k.body};for(let D of(a=k.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 sae.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,nm.assertODataName)(await u(P),`entity set for parent '${D.parentEntity}'`),Oe=(0,nm.normalizeGuid)(x,`parent id for bind '${D.navProperty}'`);I[`${D.navProperty}@odata.bind`]=`/${K}(${Oe})`}h.push(I)}let g=p?h.map(k=>{let I=k[p];return I!=null&&I!==""?String(I):null}):h.map(()=>null),b=new Map;if(p){let k=(0,nm.assertODataName)(p,"RecordGraph matchOn key"),I=[...new Set(g.filter(D=>D!==null))];if(I.length){let D=I.map(x=>`${k} eq '${(0,nm.odataLiteral)(x)}'`).join(" or "),P=await(0,aM.queryRecords)(e,m,{select:[k,`${m}id`],filter:D,top:5e3});for(let x of P??[]){let K=x[k];K!=null&&b.set(String(K).toLowerCase(),String(x[`${m}id`]))}}}let w=[],C=new Map,S=h.map((k,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(k)-1;return C.set(P,K),K}return w.push(k)-1}),O=w.length?await(0,aM.createRecordsBulk)(e,m,w):[];c[m]=h.map((k,I)=>{let D=g[I];return D&&b.has(D.toLowerCase())?b.get(D.toLowerCase()):O[S[I]]})}return{createdIds:c}}im.seedRecordGraph=lae});var yM=v(tr=>{"use strict";Object.defineProperty(tr,"__esModule",{value:!0});tr.getEntityPrivileges=tr.addEntityPrivilegesToRole=tr.deleteSecurityRole=tr.createPersonaRole=tr.createSecurityRole=tr.SDK_ROLE_MARKER=void 0;var Mn=ye(),Rt=le(),Kr=Q(),om={read:"Read",create:"Create",write:"Write",delete:"Delete",append:"Append",appendTo:"AppendTo",assign:"Assign",share:"Share"},Xv={user:"Basic",businessUnit:"Local",parentChild:"Deep",organization:"Global"},lM={user:1,businessUnit:2,parentChild:3,organization:4},Qv={user:"CanBeBasic",businessUnit:"CanBeLocal",parentChild:"CanBeDeep",organization:"CanBeGlobal"};tr.SDK_ROLE_MARKER="Authored by @maker-studio/cds-maker-sdk (persona/security role).";function uae(e){return Object.prototype.hasOwnProperty.call(om,e)?om[e]:void 0}function cae(e){return Object.prototype.hasOwnProperty.call(Xv,e)}var uM=new WeakMap,cM=new WeakMap;async function pM(e,t){var r,n;(0,Rt.assertODataName)(t,"entity logical name");let i=uM.get(e);i||(i=new Map,uM.set(e,i));let o=i.get(t);if(o)return o;let a=`/EntityDefinitions(LogicalName='${(0,Rt.odataPathLiteral)(t)}')${(0,Rt.odataQuery)([["$select","LogicalName,Privileges"]])}`,l=(n=(r=(0,Mn.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 Kr.InvalidArgumentError(`Entity '${t}' exposes no privileges (unknown or non-securable entity).`);return i.set(t,l),l}async function dae(e){var t,r,n;let i=cM.get(e);if(i)return i;let o=`/businessunits${(0,Rt.odataQuery)([["$select","businessunitid"],["$filter","_parentbusinessunitid_value eq null"],["$top",1]])}`,l=(n=((r=(t=(0,Mn.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 Kr.InvalidArgumentError("Could not resolve the root business unit.");let u=(0,Rt.normalizeGuid)(l,"businessUnitId");return cM.set(e,u),u}async function mM(e,t){var r;let n=new Map;for(let i of t){if(!i.access||i.access.length===0)throw new Kr.InvalidArgumentError(`Entity '${i.entity}' privilege request has no access levels.`);let o=(r=i.scope)!==null&&r!==void 0?r:"user";if(!cae(o))throw new Kr.InvalidArgumentError(`Unknown privilege scope '${o}' for entity '${i.entity}'.`);let a=await pM(e,i.entity);for(let s of i.access){let l=uae(s);if(!l)throw new Kr.InvalidArgumentError(`Unknown access level '${s}' for entity '${i.entity}'.`);let u=a.find(p=>p.PrivilegeType===l);if(!u)throw new Kr.InvalidArgumentError(`Entity '${i.entity}' does not support '${s}' access.`);let c=Qv[o];if(u[c]===!1)throw new Kr.InvalidArgumentError(`Privilege '${u.Name}' on '${i.entity}' does not support the '${o}' scope.`);let d=(0,Rt.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 Kr.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=lM[o]>lM[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 fae(e,t,r,n){if(r.length===0&&!n)return;let i={Privileges:r.map(a=>({Depth:Xv[a.scope],PrivilegeId:a.privilegeId}))},o=`/roles(${t})/Microsoft.Dynamics.CRM.ReplacePrivilegesRole`;(0,Mn.ensureSuccess)(await e.post(o,i),e.apiUrl(o))}async function dM(e,t,r,n,i){var o,a;let s=`/${t}(${r})/${n}${(0,Rt.odataQuery)([["$select","roleid"],["$filter",`roleid eq ${i}`]])}`;return((a=(o=(0,Mn.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 pae(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,Rt.normalizeGuid)(l,"teamId");if(!await dM(e,"teams",u,"teamroles_association",t)){let c=`/teams(${u})/teamroles_association/$ref`;(0,Mn.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,Rt.normalizeGuid)(l,"userId");if(!await dM(e,"systemusers",u,"systemuserroles_association",t)){let c=`/systemusers(${u})/systemuserroles_association/$ref`;(0,Mn.ensureSuccess)(await e.post(c,s),e.apiUrl(c))}a.push(u)}return{teams:o,users:a}}async function fM(e,t,r){var n,i;let o=`/roles${(0,Rt.odataQuery)([["$select","roleid,description,ismanaged"],["$filter",`name eq '${(0,Rt.odataLiteral)(t)}' and _businessunitid_value eq ${r}`]])}`,l=((i=(n=(0,Mn.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:"")===tr.SDK_ROLE_MARKER};if(l.some(d=>!u(d)))throw new Kr.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 Kr.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,Rt.normalizeGuid)(c,"roleId"):void 0}function mae(e){var t,r;return{teams:((t=e?.teams)!==null&&t!==void 0?t:[]).map(n=>(0,Rt.normalizeGuid)(n,"teamId")),users:((r=e?.users)!==null&&r!==void 0?r:[]).map(n=>(0,Rt.normalizeGuid)(n,"userId"))}}function hM(e){return e.map(t=>({entity:t.entity,privilegeName:t.privilegeName,privilegeType:t.privilegeType,scope:t.scope}))}async function gM(e,t){var r,n;let i=(r=t.name)===null||r===void 0?void 0:r.trim();if(!i)throw new Kr.InvalidArgumentError("createSecurityRole: a non-empty role name is required.");let o=t.businessUnitId?(0,Rt.normalizeGuid)(t.businessUnitId,"businessUnitId"):await dae(e),a=await mM(e,(n=t.privileges)!==null&&n!==void 0?n:[]),s=mae(t.assignTo),l=await fM(e,i,o),u=l!==void 0;if(!l){let d="/roles",f={name:i,description:tr.SDK_ROLE_MARKER,"[email protected]":`/businessunits(${o})`};try{let m=(0,Mn.ensureSuccess)(await e.post(d,f),e.apiUrl(d));l=(0,Rt.normalizeGuid)((0,Mn.requireCreatedId)(m,"roleid","role"),"roleId")}catch(m){let p;try{p=await fM(e,i,o)}catch{p=void 0}if(!p)throw m;l=p}}await fae(e,l,a,u);let c=await pae(e,l,s);return{roleId:l,name:i,reused:u,appliedPrivileges:hM(a),assignedTeams:c.teams,assignedUsers:c.users}}tr.createSecurityRole=gM;async function hae(e,t){var r,n;let i=(r=t.persona)===null||r===void 0?void 0:r.trim();if(!i)throw new Kr.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 gM(e,{name:i,businessUnitId:t.businessUnitId,privileges:o,assignTo:t.assignTo})}tr.createPersonaRole=hae;async function gae(e,t){let n=`/roles(${(0,Rt.normalizeGuid)(t,"roleId")})`;(0,Mn.ensureSuccess)(await e.delete(n),e.apiUrl(n))}tr.deleteSecurityRole=gae;async function yae(e,t,r){let n=(0,Rt.normalizeGuid)(t,"roleId");if(r.length===0)throw new Kr.InvalidArgumentError("addEntityPrivilegesToRole requires at least one entity privilege (an empty grant would be a silent no-op).");let i=await mM(e,r),o={Privileges:i.map(s=>({Depth:Xv[s.scope],PrivilegeId:s.privilegeId}))},a=`/roles(${n})/Microsoft.Dynamics.CRM.AddPrivilegesRole`;return(0,Mn.ensureSuccess)(await e.post(a,o),e.apiUrl(a)),hM(i)}tr.addEntityPrivilegesToRole=yae;var bae=new Map(Object.keys(om).map(e=>[om[e],e]));async function vae(e,t){return(await pM(e,t)).map(n=>{let i=Object.keys(Qv).filter(a=>n[Qv[a]]!==!1),o=bae.get(n.PrivilegeType);return{name:n.Name,privilegeId:n.PrivilegeId,privilegeType:n.PrivilegeType,...o?{access:o}:{},scopes:i}})}tr.getEntityPrivileges=vae});var LM=v(yr=>{"use strict";Object.defineProperty(yr,"__esModule",{value:!0});yr.createMakerSdk=yr.MakerSdk=yr.PUSH_NOT_ATTEMPTED_CODE=yr.ALREADY_EXISTS_CODE=void 0;var bM=Fm(),vM=Qr(),Z=Q(),bn=Ma(),wae=MC(),OM=zC(),ml=QC(),Cae=Um(),Eae=bE(),hl=CE(),Aae=$E(),Sae=qE(),Nae=bA(),wM=mS(),kt=bd(),Zv=_g(),CM=_N(),am=ru(),Hi=$d(),sm=$N(),gl=Fd(),_ae=Ud(),rr=Tg(),Tae=$g(),Dae=zg(),EM=xg(),Iae=VF(),lm=pt(),Oae=Jo(),pi=qb(),vn=Wm(),ew=_v(),Pae=3e5,gr=ye(),La=le(),yl=rM(),AM=oM(),Rae=sM(),kae=nb(),Ac=yM(),PM=Symbol("cds-maker-sdk.committedWrite");function Lae(e){return typeof e=="object"&&e!==null&&(e[PM]=!0),e}function $ae(e){return typeof e=="object"&&e!==null&&e[PM]===!0}var xae={fileConcurrency:1},tw="SOLUTION_COMPONENT_UNCLASSIFIED",Fae=2,Mae=4,Uae="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 SM(e){return{componentId:e.objectId,componentType:e.componentType,workflowCategory:e.workflowCategory,reason:"unsupported",...e.includesAllSubcomponents?{detail:Uae}:{}}}function NM(e,t){return{componentId:e.objectId,componentType:e.componentType,workflowCategory:e.workflowCategory,reason:"failed",error:Ro(t)}}function _M(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,gr.nowIso)(),isDirty:!1}}var Bae=new Set(["entity","appmodule","dashboard","uxagentproject"]);function qae(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,La.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 Vae(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 OM.WorkspaceManager(Wae,e.instanceUrl,(0,Cae.assertStorageContract)(t))}yr.ALREADY_EXISTS_CODE="ARTIFACT_ALREADY_EXISTS";var Gae="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";yr.PUSH_NOT_ATTEMPTED_CODE="PUSH_NOT_ATTEMPTED";var Wae="<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,ew.resolveReadConcurrency)(t.readConcurrency),this.languageCode=(r=t.languageCode)!==null&&r!==void 0?r:Oae.DEFAULT_LCID,this.cacheStalenessMs=(n=t.cacheStalenessMs)!==null&&n!==void 0?n:Pae,this.compiler={load:(0,Tae.createGenPageTypeScriptLoader)(t.typescript)},this.workspace=Vae(t),this.versions=new ml.VersionManager(this.workspace),this.dataverse=new Eae.DataverseClient(t.instanceUrl,t.httpClient,t.solutionUniqueName,this.readConcurrency),this.connectivity=new Nae.ConnectivityRouter(this.dataverse,t.instanceUrl,{powerAppsServiceClient:t.powerAppsServiceClient,powerPlatformApiClient:t.powerPlatformApiClient,connectorRuntimeClient:t.connectorRuntimeClient}),this.registrations=(0,Iae.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,vn.deepEqual)(b.snapshot,m))throw new Z.LocalEditsWouldBeLostError(t,r,h,c);await this.versions.storeMeta(t,r,{...b,etag:c,fetchedAt:(0,gr.nowIso)()},b)}return(0,pi.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:ml.PROJECTION_VERSION,fetchedAt:(0,gr.nowIso)(),snapshot:(0,pi.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,pi.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,rr.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(SM(o));continue}let s=await this.fetchArtifact(a,o.objectId);n.push(_M(a,o,s))}catch(a){i.push(NM(o,a))}return await this.workspace.updateManifest({lastSyncAt:(0,gr.nowIso)()}),{summaries:n,skipped:i}}async fetchComponentsOverlapped(t,r,n){await(0,ew.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(SM(o));return}let s=await this.applyFetchedArtifactUnlocked(a.type,o.objectId,a.reg,a.fetched);await this.acknowledgeRefresh(a.type,o.objectId),r.push(_M(a.type,o,s))}catch(a){n.push(NM(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,xae);return{kind:"artifact",type:r,reg:n,fetched:i}}):(0,ew.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,hl.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,Aae.generateGenPageRuntimeTypes)(n=>this.fetchEntityMetadata(n),t,r)}findTables(t,r){return(0,hl.findTables)(this.dataverse,t,r)}getEnvironmentLanguages(){return(0,Sae.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,hl.findColumns)(this.dataverse,t,r,n)}createTable(t){return this.schemaWrite([t.schemaName],()=>(0,kt.createTable)(this.dataverse,t))}createColumn(t,r){return this.schemaWrite([t],()=>(0,kt.createColumn)(this.dataverse,t,r))}createColumns(t,r){return this.schemaWrite([t],()=>(0,kt.createColumns)(this.dataverse,t,r))}updateColumn(t,r,n){return this.schemaWrite([t],()=>(0,kt.updateColumn)(this.dataverse,t,r,n))}deleteColumn(t,r){return this.schemaWrite([t],()=>(0,kt.deleteColumn)(this.dataverse,t,r))}setFormSecurityRoles(t,r){return(0,Zv.setFormSecurityRoles)(this.dataverse,t,r)}getFormSecurityRoles(t){return(0,Zv.getFormSecurityRoles)(this.dataverse,t)}setColumnVisualization(t,r,n){return(0,kt.setColumnVisualization)(this.dataverse,t,r,n)}getColumnVisualization(t,r){return(0,kt.getColumnVisualization)(this.dataverse,t,r)}createCustomerColumn(t,r){return this.schemaWrite([t,"account","contact"],()=>(0,kt.createCustomerColumn)(this.dataverse,t,r))}insertStatusValue(t,r){return this.schemaWrite([t],()=>(0,kt.insertStatusValue)(this.dataverse,t,r))}updateTable(t,r){return this.schemaWrite([t],()=>(0,kt.updateTable)(this.dataverse,t,r))}async setEntityIcon(t,r){if(await this.schemaWrite([t],()=>(0,kt.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,La.xmlText)(t)}</entity></entities></importexportxml>`;(0,gr.ensureSuccess)(await this.dataverse.post("/PublishXml",{ParameterXml:n}),this.dataverse.apiUrl("/PublishXml"))}}createAlternateKey(t,r){return(0,kt.createAlternateKey)(this.dataverse,t,r)}deleteAlternateKey(t,r){return(0,kt.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,kt.createRelationship)(this.dataverse,t))}deleteRelationship(t){return this.schemaWrite(void 0,()=>(0,kt.deleteRelationship)(this.dataverse,t))}createGlobalOptionSet(t){return(0,kt.createGlobalOptionSet)(this.dataverse,t)}deleteGlobalOptionSet(t){return(0,kt.deleteGlobalOptionSet)(this.dataverse,t)}deleteTable(t){return this.schemaWrite(void 0,()=>(0,kt.deleteTable)(this.dataverse,t))}createSecurityRole(t){return(0,Ac.createSecurityRole)(this.dataverse,t)}createPersonaRole(t){return(0,Ac.createPersonaRole)(this.dataverse,t)}deleteSecurityRole(t){return(0,Ac.deleteSecurityRole)(this.dataverse,t)}addEntityPrivilegesToRole(t,r){return(0,Ac.addEntityPrivilegesToRole)(this.dataverse,t,r)}getEntityPrivileges(t){return(0,Ac.getEntityPrivileges)(this.dataverse,t)}createRecord(t,r){return(0,Hi.createRecord)(this.dataverse,t,r)}createRecordsBulk(t,r){return(0,Hi.createRecordsBulk)(this.dataverse,t,r)}updateRecord(t,r,n){return(0,Hi.updateRecord)(this.dataverse,t,r,n)}upsertRecord(t,r,n){return(0,Hi.upsertRecord)(this.dataverse,t,r,n)}deleteRecord(t,r){return(0,Hi.deleteRecord)(this.dataverse,t,r)}getRecord(t,r,n){return(0,Hi.getRecord)(this.dataverse,t,r,n)}queryRecords(t,r){return(0,Hi.queryRecords)(this.dataverse,t,r)}seedRecordGraph(t,r){return(0,Rae.seedRecordGraph)(this.dataverse,t,r)}resolveArtifact(t,r){return(0,AM.resolveArtifact)(this.dataverse,t,r)}findArtifact(t,r){return(0,AM.findArtifact)(this.dataverse,t,r)}async deleteAppCascade(t,r){await this.workspace.ensureReady();let n=await(0,Dae.deleteAppCascade)(this.dataverse,t,r),i=(0,La.normalizeGuid)(t,"appModuleId");return await this.workspace.readArtifact("app",i)&&await this.workspace.deleteArtifact("app",i),n}associateRecords(t,r,n){return(0,Hi.associateRecords)(this.dataverse,t,r,n)}disassociateRecords(t,r,n,i){return(0,Hi.disassociateRecords)(this.dataverse,t,r,n,i)}createWebResource(t){return(0,sm.createWebResource)(this.dataverse,t)}updateWebResource(t,r){return(0,sm.updateWebResource)(this.dataverse,t,r)}getWebResource(t){return(0,sm.getWebResource)(this.dataverse,t)}deleteWebResource(t){return(0,sm.deleteWebResource)(this.dataverse,t)}getAppSettings(t){return(0,gl.readAppSettings)(this.dataverse,t)}setAppSetting(t,r,n){return(0,gl.setAppSetting)(this.dataverse,t,r,n)}setHeaderAndNavigationRefresh(t,r){if(typeof r!="boolean")throw new Z.ValidationError("app",t,[{pointer:"/headerAndNavigationRefresh",rule:_ae.HEADER_NAV_BOOLEAN_RULE,message:`enabled must be a boolean, got ${typeof r}`}]);return(0,gl.setAppSetting)(this.dataverse,t,gl.HEADER_AND_NAVIGATION_REFRESH,r?gl.APP_SETTING_ON:gl.APP_SETTING_OFF)}getSolution(t){return(0,rr.getSolution)(this.dataverse,t)}createPublisher(t){return(0,rr.createPublisher)(this.dataverse,t)}createSolution(t){return(0,rr.createSolution)(this.dataverse,t)}setSolutionVersion(t,r){return(0,rr.setSolutionVersion)(this.dataverse,t,r)}addSolutionComponent(t){return(0,rr.addSolutionComponent)(this.dataverse,t)}removeSolutionComponent(t,r,n){return(0,rr.removeSolutionComponent)(this.dataverse,t,r,n)}exportSolution(t){return(0,rr.exportSolution)(this.dataverse,t)}importSolution(t){return this.schemaWrite(void 0,()=>(0,rr.importSolution)(this.dataverse,t))}getDeploymentSettingsTemplate(t){return(0,rr.getDeploymentSettingsTemplate)(this.dataverse,t)}deleteSolution(t){return this.schemaWrite(void 0,()=>(0,rr.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,OM.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,vn.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=bn.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,wae.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=bn.JsonPointer.resolve(a,n);if(s===void 0)throw new Z.PathNotFoundError(t,r,n);let l=Ki(s)&&Ki(i)?{...s,...i}:i;return bn.JsonPointer.set(a,n,(0,pi.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=bn.JsonPointer.resolve(s,n);if(l===void 0)throw new Z.PathNotFoundError(t,r,n);if(!Array.isArray(l)){if(!Ki(l)||!Ki(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,pi.cloneJson)(i[f]),p=(0,lm.isValueMapKey)(f)||(0,lm.pointerTouchesValueMap)(n);d[f]=p?m:Array.isArray(m)?m.map(h=>Ki(h)?this.assignMissingIds(t,h):h):Ki(m)?this.assignMissingIds(t,m):m}for(let f of Object.keys(d))bn.JsonPointer.set(s,bn.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,lm.pointerTouchesValueMap)(n)?(0,pi.cloneJson)(i):this.assignMissingIds(t,(0,pi.cloneJson)(i)),c=Kae(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=bn.JsonPointer.resolve(l,n);if(u===void 0)throw new Z.PathNotFoundError(t,r,n);let c=bn.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");bn.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),IM(c);let f=bn.JsonPointer.resolve(l,DM(n));return Array.isArray(f)&&f!==c&&IM(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(bn.JsonPointer.resolve(o,n)===void 0)throw new Z.PathNotFoundError(t,r,n);return bn.JsonPointer.remove(o,n),this.assertStructurallyValid(t,r,o,DM(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,yl.retrieveSetting)(this.dataverse,t,r)}saveSettingValue(t,r,n){return(0,yl.saveSettingValue)(this.dataverse,t,r,n)}getAiReadiness(t){return(0,yl.getAiReadiness)(this.dataverse,t)}setAppAiFeatures(t,r,n){return(0,yl.setAppAiFeatures)(this.dataverse,t,r,n)}configureRowSummary(t,r){return(0,yl.configureRowSummary)(this.dataverse,t,r)}removeRowSummary(t){return(0,yl.removeRowSummary)(this.dataverse,t)}async enrichDefaultViews(t,r,n={}){let i=await(0,kae.findDefaultViews)(this.dataverse,t,{excludeViewIds:n.excludeViewIds}),o=n.publish===!1,a=[],s=[],l=()=>({updated:[...a],results:[...s],pendingPublish:a.length>0?[{scope:(0,vM.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&&$ae(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,pi.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=qae(a),f;if(d)try{await(0,vM.publishXml)(this.dataverse,d)}catch(p){f=Ro(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||!Bae.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,vn.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:Ro(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,gr.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||!jae(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,vn.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,gr.isVersionToken)(o)||!RM(a,t.heldSiblings)||!kM(a)||!(o!==t.heldEtag||!(0,vn.deepEqual)(a??void 0,t.heldSiblings))||!(0,vn.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,gr.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 (${Ro(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,vn.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,vn.deepEqual)(c(i.snapshot),c(u)))return;await this.versions.storeMeta(r,n,{...i,etag:a,fetchedAt:(0,gr.nowIso)(),...s?{memberEtags:s}:{},...l?{siblingEtags:l}:{}},i)}catch{}}async verifyPublished(t,r,n){var i;if(t!=="app"){let o=this.registrations.get(t);return o?.api.getPublished?this.verifyPublishedContent(o,t,r,n):{kind:"unverifiable",reason:`published-projection verification is not characterised for '${t}'; the publish was submitted`}}try{let o=`/appmodules(${(0,La.normalizeGuid)(r,"id")})${(0,La.odataQuery)([["$select","appmoduleid,name,description"]])}`,a=await this.dataverse.get(o);if(a.status>=200&&a.status<300){let s=(i=a.body)!==null&&i!==void 0?i:{},l=n;if(!l)return{kind:"unverifiable",reason:"there is no local copy of the app to compare the published projection with"};let u=["name","description"].filter(d=>l[d]!==void 0);if(u.length===0)return{kind:"unverifiable",reason:"the local copy of the app holds neither a name nor a description to compare the published projection with, and its presence alone proves nothing for a re-publish"};let c=u.filter(d=>{var f,m;return((f=l[d])!==null&&f!==void 0?f:"")!==((m=s[d])!==null&&m!==void 0?m:"")});return c.length>0?{kind:"unverifiable",reason:`the published projection does not yet match the saved app (${c.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 ${a.status}`}}catch(o){return{kind:"unverifiable",reason:Ro(o).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,vn.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,vn.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:Ro(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,hl.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 k=S?.artifact!==void 0&&!(0,vn.deepEqual)(S.artifact,p),I=k?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:ml.PROJECTION_VERSION,fetchedAt:(0,gr.nowIso)(),snapshot:(0,pi.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}:{}})():{},...k?{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===yr.ALREADY_EXISTS_CODE)return{type:d,id:f,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:w};if(w instanceof Z.SdkError&&w.code===bM.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===bM.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===gr.VERSION_CONFLICT_CODE)return{type:d,id:f,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:(0,EM.isFailureAfterPrimaryWrite)(w)?w:new Z.VersionConflictError(d,f,(c=h?.etag)!==null&&c!==void 0?c:null,null,w.message)};throw b?Lae(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!==ml.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 ${ml.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,Zv.readPrimaryCreateRefusal)(a):void 0;if(s?.status===404&&await(0,CM.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(yr.ALREADY_EXISTS_CODE,rw(r,n,u)+(this.createRecovery==="adoptExact"?` ${TM(Gae)}`:"")),a)}if(!(a instanceof Z.SdkError)||a.code!==gr.VERSION_CONFLICT_CODE||(0,EM.isFailureAfterPrimaryWrite)(a))throw a;if(this.createRecovery==="adoptExact"&&s?.status===412){let l=await(0,CM.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(yr.ALREADY_EXISTS_CODE,`${rw(r,n)} ${TM(l.refused)}`)}throw new Z.SdkError(yr.ALREADY_EXISTS_CODE,rw(r,n))}}async persistAdoption(t,r,n,i){let{artifact:o,etag:a}=i,s=!(0,vn.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:ml.PROJECTION_VERSION,fetchedAt:(0,gr.nowIso)(),snapshot:(0,pi.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(k=>k.entityLogicalName).filter(k=>!!k)),c=new Set(l.filter(k=>k.needsColumnDetail).map(k=>k.entityLogicalName)),d=new Set(l.filter(k=>k.needsColumnDetail||!k.fieldName).map(k=>k.entityLogicalName)),f=k=>l.filter(I=>I.entityLogicalName===k).every(I=>I.fetchRequired===!1),m=new Map,p=new Map;for(let k of u){let I=await this.readCachedEntityMetadata(k);if(I&&c.has(k)&&(I.columnDetailComplete!==!0||!(typeof I.columnDetailVersion=="number"&&I.columnDetailVersion>=hl.COLUMN_DETAIL_VERSION)||I.attributes.some(D=>typeof D.attributeTypeName!="string"))&&(I=null),!I&&!d.has(k)){if(!f(k)){let D=l.filter(P=>P.entityLogicalName===k).map(P=>P.fieldName);try{let P=await(0,hl.readColumnHints)(this.dataverse,k,D);p.set(k,new Map(P.map(x=>[x.logicalName,x])))}catch{}}continue}if(!I&&!f(k))try{await this.loadMissedEntityMetadata(k),I=await this.readCachedEntityMetadata(k)}catch{}I&&m.set(k,I)}let h=(k,I)=>{var D,P,x;return(P=(D=m.get(k))===null||D===void 0?void 0:D.attributes.find(K=>K.logicalName===I))!==null&&P!==void 0?P:(x=p.get(k))===null||x===void 0?void 0:x.get(I)},g=this.languageCode,w=l.some(k=>{if(!k.needsLabel||!k.fieldName)return!1;let I=h(k.entityLogicalName,k.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:(k,I)=>{let D=h(k,I);return D?{displayName:Hae(D,g,w),attributeType:D.attributeType}:void 0},resolveEntity:k=>m.get(k),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,wM.readControlManifest)(this.dataverse,i));let n=new Map;for(let i of t.columns)n.set(i,await(0,wM.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:Ro(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(yr.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:Ro(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,lm.assignMissingIds)(r)}async resolveComponentType(t){if(t.genPage)return"genPage";switch(t.componentType){case rr.SolutionComponentType.SavedQuery:return"view";case rr.SolutionComponentType.SavedQueryVisualization:return"chart";case rr.SolutionComponentType.AppModule:return"app";case rr.SolutionComponentType.Workflow:return this.workflowArtifactType(t);case rr.SolutionComponentType.SystemForm:return this.systemFormArtifactType(t.objectId);default:return}}async systemFormArtifactType(t){let r=await(0,am.readSystemFormType)(this.dataverse,t);if(Number.isNaN(r))throw new Z.SdkError(tw,`System form '${t}' answered without a readable type, so whether it is a form or a dashboard cannot be told.`);return(0,am.systemFormKindOf)(r)}async workflowArtifactType(t){let r=(0,La.normalizeGuid)(t.objectId,"workflowId"),n=`/workflows(${r})${(0,La.odataQuery)([["$select","category,businessprocesstype"]])}`,o=(0,gr.ensureSuccess)(await this.dataverse.get(n),this.dataverse.apiUrl(n)).body,a=(0,am.decodeCode)(o?.category);if(Number.isNaN(a))throw new Z.SdkError(tw,`Workflow '${r}' answered without a readable category, so its kind cannot be told.`);if(t.workflowCategory=a,a===Fae)return"businessRule";if(a===Mae){let s=(0,am.decodeCode)(o?.businessprocesstype);if(Number.isNaN(s))throw new Z.SdkError(tw,`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}};yr.MakerSdk=um;function zae(e){return new um(e)}yr.createMakerSdk=zae;function Ro(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 kM(e){return Object.values(e??{}).every(gr.isVersionToken)}function jae(e,t){return RM(e,t)&&kM(e)&&Object.keys(e??{}).every(r=>t?.[r]===e?.[r])}function TM(e){return`createRecovery 'adoptExact' did not adopt it: ${e}.`}function rw(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 Hae(e,t,r){let n=e.localizedDisplayName;return n?.[t]||(r===void 0?void 0:n?.[r])||e.displayName}function Ki(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function DM(e){let t=e.lastIndexOf("/");return t<=0?"":e.slice(0,t)}function IM(e){e.length===0||!e.every(t=>Ki(t)&&typeof t.order=="number")||e.forEach((t,r)=>{t.order=r})}function Kae(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=>Ki(i)&&i.id===t.before);return n<0?e.length:n}let r=e.findIndex(n=>Ki(n)&&n.id===t.after);return r<0?e.length:r+1}});var $M=v(cm=>{"use strict";Object.defineProperty(cm,"__esModule",{value:!0});cm.ARTIFACT_TYPES=void 0;cm.ARTIFACT_TYPES=["form","view","businessRule","app","command","chart","dashboard","genPage","bpf"]});var FM=v(xM=>{"use strict";Object.defineProperty(xM,"__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(KM=>{"use strict";Object.defineProperty(KM,"__esModule",{value:!0})});var QM=v(YM=>{"use strict";Object.defineProperty(YM,"__esModule",{value:!0})});var ZM=v(XM=>{"use strict";Object.defineProperty(XM,"__esModule",{value:!0})});var tU=v(eU=>{"use strict";Object.defineProperty(eU,"__esModule",{value:!0})});var nU=v(rU=>{"use strict";Object.defineProperty(rU,"__esModule",{value:!0})});var oU=v(iU=>{"use strict";Object.defineProperty(iU,"__esModule",{value:!0})});var sU=v(aU=>{"use strict";Object.defineProperty(aU,"__esModule",{value:!0})});var uU=v(lU=>{"use strict";Object.defineProperty(lU,"__esModule",{value:!0})});var dU=v(cU=>{"use strict";Object.defineProperty(cU,"__esModule",{value:!0})});var pU=v(fU=>{"use strict";Object.defineProperty(fU,"__esModule",{value:!0})});var hU=v(mU=>{"use strict";Object.defineProperty(mU,"__esModule",{value:!0})});var yU=v(gU=>{"use strict";Object.defineProperty(gU,"__esModule",{value:!0})});var vU=v(bU=>{"use strict";Object.defineProperty(bU,"__esModule",{value:!0})});var CU=v(wU=>{"use strict";Object.defineProperty(wU,"__esModule",{value:!0})});var AU=v(EU=>{"use strict";Object.defineProperty(EU,"__esModule",{value:!0})});var NU=v(pe=>{"use strict";var Jae=pe&&pe.__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]})),Ge=pe&&pe.__exportStar||function(e,t){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(t,r)&&Jae(t,e,r)};Object.defineProperty(pe,"__esModule",{value:!0});pe.projectConnectorOperationSchema=pe.projectConnectorOperations=pe.createMakerSdk=void 0;var Yae=LM();Object.defineProperty(pe,"createMakerSdk",{enumerable:!0,get:function(){return Yae.createMakerSdk}});Ge($M(),pe);Ge(FM(),pe);Ge(UM(),pe);Ge(qM(),pe);Ge(GM(),pe);Ge(zM(),pe);Ge(HM(),pe);Ge(JM(),pe);Ge(QM(),pe);Ge(ZM(),pe);Ge(tU(),pe);Ge(nU(),pe);Ge(oU(),pe);Ge(sU(),pe);Ge(uU(),pe);Ge(Ud(),pe);Ge(dU(),pe);Ge(pU(),pe);Ge(hU(),pe);Ge(yU(),pe);Ge(vU(),pe);Ge(CU(),pe);Ge(AU(),pe);Ge(Q(),pe);var SU=Tl();Object.defineProperty(pe,"projectConnectorOperations",{enumerable:!0,get:function(){return SU.projectConnectorOperations}});Object.defineProperty(pe,"projectConnectorOperationSchema",{enumerable:!0,get:function(){return SU.projectConnectorOperationSchema}})});var iw=v(mi=>{"use strict";var Qae=mi&&mi.__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]})),Xae=mi&&mi.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),DU=mi&&mi.__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)&&Qae(t,e,r);return Xae(t,e),t};Object.defineProperty(mi,"__esModule",{value:!0});mi.NodeFileSystemStorage=void 0;var Ct=DU(require("fs")),nr=DU(require("path")),_U=Q(),TU=Bm();async function IU(e){let t;try{t=await Ct.promises.lstat(e)}catch{return}if(t.isSymbolicLink()){try{await Ct.promises.unlink(e)}catch{await Ct.promises.rmdir(e)}return}if(!t.isDirectory()){await Ct.promises.unlink(e);return}for(let r of await Ct.promises.readdir(e))await IU(nr.join(e,r));await Ct.promises.rmdir(e)}var nw=class{constructor(t){this.root=t}getRoot(){return this.root}pathFor(t,r=!0){return this.assertWithinRoot(nr.join(this.root,...t),r)}realPathThroughNearestAncestor(t){let r=t,n=[];for(;!Ct.existsSync(r);){n.unshift(nr.basename(r));let i=nr.dirname(r);if(i===r)return nr.resolve(t);r=i}return nr.resolve(Ct.realpathSync(r),...n)}assertWithinRoot(t,r){let n=nr.resolve(this.root),i=nr.resolve(t);if(i!==n&&!i.startsWith(n+nr.sep))throw new _U.PathTraversalError(t,this.root);let o=this.realPathThroughNearestAncestor(n),a=r?this.realPathThroughNearestAncestor(i):nr.resolve(this.realPathThroughNearestAncestor(nr.dirname(i)),nr.basename(i));if(a!==o&&!a.startsWith(o+nr.sep))throw new _U.PathTraversalError(t,this.root);return i}async readText(t){let r=this.pathFor(t);if(!Ct.existsSync(r))return null;try{return await(0,TU.retryTransientIoAsync)(()=>Ct.promises.readFile(r,"utf8"))}catch(n){if(n.code==="ENOENT")return null;throw n}}async writeTextAtomic(t,r){let n=this.pathFor(t),i=nr.dirname(n);await Ct.promises.mkdir(i,{recursive:!0});let o=nr.join(i,`.${nr.basename(n)}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`);try{await Ct.promises.writeFile(o,r,"utf8"),await(0,TU.retryTransientIoAsync)(()=>Ct.promises.rename(o,n))}catch(a){try{Ct.existsSync(o)&&await Ct.promises.unlink(o)}catch{}throw a}}async deleteFile(t){let r=this.pathFor(t);Ct.existsSync(r)&&await Ct.promises.unlink(r)}async deleteByPrefix(t){await IU(this.pathFor(t,!1))}async ensureContainer(t){await Ct.promises.mkdir(this.pathFor(t),{recursive:!0})}async exists(t){return Ct.existsSync(this.pathFor(t))}};mi.NodeFileSystemStorage=nw});var OU=v(Ur=>{"use strict";var Zae=Ur&&Ur.__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]})),ese=Ur&&Ur.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),tse=Ur&&Ur.__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)&&Zae(t,e,r);return ese(t,e),t};Object.defineProperty(Ur,"__esModule",{value:!0});Ur.loadNodeTypeScript=Ur.createNodeWorkspaceStorage=Ur.NodeFileSystemStorage=void 0;var rse=iw(),nse=iw();Object.defineProperty(Ur,"NodeFileSystemStorage",{enumerable:!0,get:function(){return nse.NodeFileSystemStorage}});function ise(e){return new rse.NodeFileSystemStorage(e)}Ur.createNodeWorkspaceStorage=ise;async function ose(){return await Promise.resolve().then(()=>tse(require("typescript")))}Ur.loadNodeTypeScript=ose});var Ji={};module.exports=Br(Ji);Yi(Ji,Ae(NU()),module.exports);Yi(Ji,Ae(OU()),module.exports);+`),diagnostics:p}}});var G2={};Fi(G2,{Guid:()=>H});var H,Dn=B(()=>{"use strict";H=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 n=Math.random()*16|0,r=t=="x"?n:n&3|8;return r.toString(16)})}constructor(t,n=!1){this.guidString=t;let r=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}$");(n||r.test(t))&&(this.guid=t)}ToString(){return this.guid}}});var Q,Sr=B(()=>{"use strict";En();Q=class e{static get EmptyString(){return""}static IsTrue(t){let n=!1;return n=t&&(this.IsStrictTrue(t)||this.IsYes(t)),n}static IsStrictTrue(t){let n=!1;return t&&(n=t.toLowerCase()==="true"),n}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,n){return e.IsNullOrEmpty(t)?t:t.replace(/\{\{|\}\}|\{(\d+)\}/g,function(r,i){return r=="{{"?"{":r=="}}"?"}":n[i]})}static EndsWithString(t,n){return t.indexOf(n,t.length-n.length)!==-1}static IsBlankString(t){return t.replace(/\s/g,"").length==0}static EscapeXml(t,n){let r=t;return this.IsNullOrEmpty(r)||(r=r.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">"),n&&(r=r.replace(/"/g,""").replace(/'/g,"'"))),r}static EscapeDomId(t){return t.replace(".","\\.")}static ToSnakeCase(t){let n=e.EmptyString;for(let r=0;r<t.length;r++)r!==0&&t[r]==t[r].toUpperCase()&&(n+="-"),n+=t[r].toLowerCase();return n}static GetSnakeCaseMarkup(t,n){let r="<"+this.ToSnakeCase(t);if(!F.IsNullOrUndefined(n))for(let i of n.getKeys())r+=" "+this.ToSnakeCase(i)+'="'+n.getValue(i)+'"';return r+">"}static StripBraces(t){return t&&t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"?t.substr(1,t.length-2):t}static AddBraces(t){return F.IsNullOrUndefined(t)||t.charAt(0)==="{"||t.charAt(t.length-1)==="}"?t:`{${t}}`}static GuidStringEquals(t,n){return t===n?!0:!t||!n?!1:e.StripBraces(t).toUpperCase()===e.StripBraces(n).toUpperCase()}static AddBracesToArrayValues(t){return t.length>0?t.map(r=>(r.charAt(0)!=="{"&&(r="{"+r),r.charAt(r.length-1)!=="}"&&(r=r+"}"),r)):t}static StripBracesOnArrayValues(t){return t.length>0?t.map(r=>{let i;return r.charAt(0)==="{"&&(i=r.substr(1,r.length-1)),r.charAt(r.length-1)==="}"&&(i=i.substr(0,r.length-2)),i}):t}}});var j2={};Fi(j2,{ScriptUtilities:()=>F});var F,En=B(()=>{"use strict";Dn();Sr();F=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:H.EmptyGuid.ToString()===t.ToString()}static IsNullOrUndefinedNested(t,n){return n.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,n){let r=t.getNamedItem(n);return e.IsNullOrUndefined(r)?null:r.value}static getBooleanValue(t,n){let r=e.getNamedItemValue(t,n);return e.IsNullOrUndefined(r)?null:Q.IsTrue(r)}static getNumericValue(t){return e.IsNullOrUndefined(t)?null:parseInt(t)}static getAllUniqueTagNames(t){let n=new Set;return e.getAllUniqueTagNamesHelper(t,n),n}static getAllUniqueTagNamesHelper(t,n){if(t.nodeType===Node.ELEMENT_NODE&&(n.add(t.tagName),t.hasChildNodes()))for(let r=0;r<t.children.length;r++)this.getAllUniqueTagNamesHelper(t.children.item(r),n)}}});var _0,I0,yl,T0,yC,O0,bC=B(()=>{"use strict";(function(e){e[e.FormElementNodeChange=0]="FormElementNodeChange",e[e.FormElementAttributeChange=1]="FormElementAttributeChange"})(_0||(_0={}));I0=class{type;targetNode;constructor(t,n){this.type=t,this.targetNode=n}},yl=class extends I0{key;oldValue;newValue;constructor(t,n,r,i){super(_0.FormElementNodeChange,t),this.key=n,this.oldValue=r,this.newValue=i}apply(){this.targetNode.replaceObjectPropertyValue(this.key,this.newValue)}revert(){this.targetNode.replaceObjectPropertyValue(this.key,this.oldValue)}},T0=class extends I0{property;oldValue;newValue;constructor(t,n,r,i){super(_0.FormElementAttributeChange,t),this.property=n,this.oldValue=r,this.newValue=i}apply(){this.targetNode.replaceAttributeValue(this.property,this.newValue)}revert(){this.targetNode.replaceAttributeValue(this.property,this.oldValue)}},yC=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()})}},O0=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 yC(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 W2={};Fi(W2,{ChartGridMode:()=>Zi,ColumnLayoutWidths:()=>Bse,ComponentCategory:()=>P0,ComponentType:()=>vC,ControlLayoutTypes:()=>_C,DisplayConditionsInfo:()=>Use,ElementNames:()=>D,ElementProperties:()=>A,ElementType:()=>EC,EntityAttributeProperty:()=>AC,EventType:()=>kp,FormActivationState:()=>NC,FormCanvasServiceScope:()=>Zse,FormDesignerSideBarTab:()=>wC,FormPresentation:()=>CC,FormState:()=>D0,FormType:()=>Pn,HeaderDensityType:()=>su,LookUpTable:()=>fa,MORE_TAB_PREFIX:()=>Gse,NavBarChildElementType:()=>SC,PREVIEW_ID_HEADER_FLYOUT:()=>Hse,PREVIEW_ID_HEADER_OVERFLOW_BUTTON:()=>Jse,PREVIEW_ID_NAVIGATION_AREA:()=>Wse,PREVIEW_ID_QUICKCREATE_ROOT:()=>Qse,PREVIEW_ID_TAB:()=>Yse,PREVIEW_ID_TAB_LIST:()=>Kse,PREVIEW_ID_TAB_PANEL:()=>zse,PropertyModelKeys:()=>OC,PropertyModelSectionKeys:()=>Vse,RELATED_TAB_ID:()=>DC,RELATED_TAB_PREFIX:()=>jse,SectionDefaultProperties:()=>qse,SectionLayoutTypes:()=>Vt,TabContentType:()=>IC,TabDefaultProperties:()=>uu,TabLayoutTypes:()=>Bt,TelemetryPropertyNames:()=>Xse,UnboundControlPropertyKeys:()=>TC,compositeAddressFields:()=>Fse,compositeFieldNames:()=>Li,compositeFields:()=>xse});var Pn,vC,wC,D,A,EC,Li,xse,Fse,AC,fa,D0,su,CC,Use,SC,NC,Bt,qse,uu,Vt,_C,IC,Bse,TC,OC,Vse,kp,Zi,DC,Gse,jse,Wse,zse,Hse,Kse,Jse,Yse,Qse,Xse,P0,Zse,Re=B(()=>{"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"})(Pn||(Pn={}));(function(e){e[e.Form=0]="Form",e[e.Dialog=1]="Dialog"})(vC||(vC={}));(function(e){e[e.Components=0]="Components",e[e.Properties=1]="Properties",e[e.Relationship=2]="Relationship",e[e.BusinessRules=3]="BusinessRules"})(wC||(wC={}));(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"})(D||(D={}));A={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"})(EC||(EC={}));Li={fullname:"fullname",yomifullname:"yomifullname",address1_composite:"address1_composite",address2_composite:"address2_composite",address3_composite:"address3_composite",billto:"billto_composite",shipto:"shipto_composite"},xse=[Li.fullname,Li.yomifullname,Li.address1_composite,Li.address2_composite,Li.address3_composite,Li.billto,Li.shipto],Fse=[Li.address1_composite,Li.address2_composite,Li.address3_composite,Li.billto,Li.shipto];(function(e){e[e.IsValidForForm=0]="IsValidForForm",e[e.IsValidForCreate=1]="IsValidForCreate"})(AC||(AC={}));(function(e){e[e.DependencyFieldTable=0]="DependencyFieldTable",e[e.LockedFieldTable=1]="LockedFieldTable"})(fa||(fa={}));(function(e){e[e.Published=0]="Published",e[e.Draft=1]="Draft",e[e.New=2]="New",e[e.SaveAs=3]="SaveAs"})(D0||(D0={}));(function(e){e.Low="Low",e.HighReadOnlyValues="HighReadOnlyValues",e.HighWithControls="HighWithControls"})(su||(su={}));(function(e){e[e.ClassicForm=0]="ClassicForm",e[e.AirForm=1]="AirForm",e[e.ConvertedICForm=2]="ConvertedICForm"})(CC||(CC={}));Use={TopOrderFormId:"topOrderFormId",NextDisplayOrder:"nextDisplayOrder"};(function(e){e[e.NavBarRelationShipItem=0]="NavBarRelationShipItem",e[e.NavBarItem=1]="NavBarItem"})(SC||(SC={}));(function(e){e[e.InActive=0]="InActive",e[e.Active=1]="Active"})(NC||(NC={}));(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"})(Bt||(Bt={}));qse={ShowLabel:"false",LockLevel:"0",IsUserDefined:"0",LabelWidth:"115",columns:"1",ShowBar:"false",Layout:"varwidth",namePrefix:"_section_"},uu={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"})(Vt||(Vt={}));(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"})(_C||(_C={}));(function(e){e.cardSections="cardSections",e.singleComponent="singleComponent",e.default="default",e.expandAvailableSpace="expandAvailableSpace"})(IC||(IC={}));Bse={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"})(TC||(TC={}));(function(e){e.entityName="entityName",e.formName="formName",e.formDisplayName="formDisplayName",e.description="description",e.maxWidth="maxWidth",e.showNavigation="showNavigation",e.showImageCheck="showImageCheck",e.downloadFormXml="downloadFormXml",e.downloadRawFormXml="downloadRawFormXml",e.expandTab="expandTab",e.singleComponent="singleComponent",e.label="label",e.name="name",e.hiddenByDefault="hiddenByDefault",e.hideForPhone="hideForPhone",e.tabLayout="tabLayout",e.column1Width="column1Width",e.column2Width="column2Width",e.column3Width="column3Width",e.hideLabel="hideLabel",e.lockElement="lockElement",e.sectionLayout="sectionLayout",e.labelWidth="labelWidth",e.fieldLabelAlignment="fieldLabelAlignment",e.fieldLabelPosition="fieldLabelPosition",e.cellWidth="cellWidth",e.fieldHeight="fieldHeight",e.cellHeight="cellHeight",e.showLine="showLine",e.readonly="readonly",e.required="required",e.maxLength="maxLength",e.isTitle="isTitle",e.minValue="minValue",e.maxValue="maxValue",e.precision="precision",e.autoExpand="autoExpand",e.highDensityEnabled="highDensityEnabled",e.hideExtendedHeader="hideExtendedHeader",e.defaultViewProperty="defaultViewProperty",e.defaultChartProperty="defaultChartProperty",e.teamTemplateProperty="teamTemplateProperty",e.datasourceProperty="datasourceProperty",e.eventType="eventType",e.addEvent="addEvent",e.cellOnChange="cellOnChange",e.cellOnChangeEventDependencies="cellOnChangeEventDependencies",e.cellOnChangeHandlers="cellOnChangeHandlers",e.gridOnChange="gridOnChange",e.gridOnChangeEventDependencies="gridOnChangeEventDependencies",e.gridOnChangeHandlers="gridOnChangeHandlers",e.gridOnChangeTargetField="gridOnChangeTargetField",e.gridOnRecordSelect="gridOnRecordSelect",e.gridOnRecordSelectEventDependencies="gridOnRecordSelectEventDependencies",e.gridOnRecordSelectHandlers="gridOnRecordSelectHandlers",e.cellOnReadyStateEventDependencies="cellOnReadyStateEventDependencies",e.cellOnReadyStateHandlers="cellOnReadyStateEventHandlers",e.tabOnChange="tabOnChange",e.tabOnChangeEventDependencies="tabOnChangeEventDependencies",e.tabOnChangeHandlers="tabOnChangeHandlers",e.formOnLoad="formOnLoad",e.formOnLoadEventDependencies="formOnLoadEventDependencies",e.formOnLoadHandlers="formOnLoadHandlers",e.formOnSave="formOnSave",e.formOnSaveDependencies="formOnSaveDependencies",e.formOnSaveHandlers="formOnSaveHandlers",e.gridOnSave="gridOnSave",e.gridOnSaveDependencies="gridOnSaveDependencies",e.gridOnSaveHandlers="gridOnSaveHandlers",e.formHasNoLibraries="formHasNoLibraries",e.hideHeaderCommandBar="hideHeaderCommandBar",e.hideHeaderBody="hideHeaderBody",e.hideHeaderTabNavigator="hideHeaderTabNavigator",e.hideFooter="hideFooter",e.scrollingDropdown="scrollingDropdown",e.displayBorder="displayBorder",e.crossScripting="crossScripting",e.passParams="passParams",e.webResourceCustomParamData="webResourceCustomParameterData",e.webResourceAltText="webResourceAltText",e.verticalAlignment="verticalAlignment",e.horizontalAlignment="horizontalAlignment",e.specificSize="specificSize",e.urlProperty="urlProperty",e.enableViewPicker="enableViewPicker",e.enableChartPicker="enableChartPicker",e.chartGridMode="chartGridMode",e.relatedRecords="relatedRecords",e.hideSearchBox="hideSearchBox",e.showAllViews="showAllViews",e.availableViewsProperty="availableViewsProperty",e.recordsPerPage="recordsPerPage",e.businessRulePill="business-rule-pill-",e.addBusinessRule="addBusinessRule",e.rowHeight="rowHeight",e.refPanelSectionTabs="refPanelSectionTabs",e.editCanvasAppProperty="editCanvasAppProperty"})(OC||(OC={}));Vse={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"})(kp||(kp={}));(function(e){e.All="All",e.Chart="Chart",e.Grid="Grid"})(Zi||(Zi={}));DC="tab_related3b554255-7717-4d17-bb7f-9936fb1e75ca",Gse="more_tab_",jse="related_tab_",Wse="preview_id_navigation_area",zse="tab-section",Hse="headerFieldsFlyout",Kse="tablist",Jse="header_overflowButton",Yse="tab",Qse="quickCreateRoot",Xse={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"})(P0||(P0={}));Zse="CellCanvasServiceScope"});var z2={};Fi(z2,{Attribute:()=>R0,FormElementNode:()=>Se});var R0,Se,Jn=B(()=>{"use strict";En();Sr();bC();Re();Dn();R0=class{key;value;constructor(t,n){this.key=t,this.value=n}},Se=class e{nodeName;properties;childrenNodes;parentNode;nodeId;isTransient;constructor(t,n){this.nodeName=t,this.properties=[],this.childrenNodes=[],this.parentNode=n,this.isTransient=!1,this.nodeId=`nodeId-${H.NewGuid()}`}getProperty(t){for(let n of this.properties)if(n.key===t)return n.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,n){this.properties.find(r=>r===t)&&(t.value=n)}replaceObjectPropertyValue(t,n){this[t]=n}getAllChildren(){return this.childrenNodes}getParentNode(){return this.parentNode}visit(t){let n=!1;if(t){n=!!t(this);let r=this.childrenNodes;if(!n&&r)for(let i=0;!n&&i<r.length;i++)n=r[i].visit(t)}return n}findAll(t){let n=[];return t&&this.visit(r=>{t(r)&&n.push(r)}),n}findFirst(t){let n=null;return t&&this.visit(r=>{if(t(r))return n=r,!0}),n}raiseMetadataChange(t){let n=this.getAncestor(D.form);n&&n.raiseMetadataChange(t)}trackPropertyAddition(t,n){this.trackPropertyCollectionChange(()=>{this.properties.push(new R0(t,n))})}trackPropertyDeletion(t){this.trackPropertyCollectionChange(()=>{let n=this.properties.findIndex(r=>r.key===t);n>-1&&this.properties.splice(n,1)})}trackPropertyCollectionChange(t){let n=this.changeTracker();if(n&&n.isTracking){let r=this.properties.slice();t(),n.addChange(new yl(this,"properties",r,this.properties.slice()))}else t()}trackChildrenCollectionChange(t){let n=this.changeTracker();if(n&&n.isTracking){let r=this.childrenNodes.slice();t(),n.addChange(new yl(this,"childrenNodes",r,this.childrenNodes.slice()))}else t()}trackParentNodeChange(t){let n=this.changeTracker();if(n&&n.isTracking){let r=this.parentNode;if(t(),r===this.parentNode)return;n.addChange(new yl(this,"parentNode",r,this.parentNode))}else t()}trackAttributeValueChange(t,n){let r=this.changeTracker();if(r&&r.isTracking){let i=t.value;if(i===n)return;t.value=n,r.addChange(new T0(this,t,i,n))}else t.value=n}trackObjectPropertyChange(t,n){let r=this.changeTracker();if(r&&r.isTracking){let i=this[t];if(i===n)return;this[t]=n,r.addChange(new yl(this,t,i,n))}else this[t]=n}setProperty(t,n){if(!t)throw new Error("Invalid property key");let r=this.properties.find(i=>i.key===t);r?this.trackAttributeValueChange(r,n):this.addProperty(t,n)}addProperty(t,n){if(!t)throw new Error("Invalid property key");this.trackPropertyAddition(t,n)}removeProperty(t){this.trackPropertyDeletion(t)}addChild(t){t.trackParentNodeChange(()=>{t.parentNode=this}),this.trackChildrenCollectionChange(()=>{this.childrenNodes.push(t)})}insertChildAtIndex(t,n){F.IsNullOrUndefined(t)||(t.trackParentNodeChange(()=>{t.parentNode=this}),this.trackChildrenCollectionChange(()=>{this.childrenNodes.splice(n,0,t)}))}moveChild(t,n){let r=this.childrenNodes.indexOf(t);if(r<0)return!1;let i=Math.min(Math.max(0,r+n),this.childrenNodes.length-1);return r!==i&&this.trackChildrenCollectionChange(()=>{this.childrenNodes.splice(i,0,this.childrenNodes.splice(r,1)[0])}),!0}getChildren(t){let n=[];for(let r of this.childrenNodes)r.nodeName===t&&n.push(r);return n}getFirstChild(t){for(let n of this.childrenNodes)if(n.nodeName===t)return n;return null}getAllGrandChildren(t){let n=this.getChildren(t),r=null;return n.length===0?new Array:(r=n[0],r.childrenNodes)}deleteChild(t){if(F.IsNullOrUndefined(t))return-1;for(let n=0;n<this.childrenNodes.length;n++)if(this.childrenNodes[n]===t)return this.trackChildrenCollectionChange(()=>{this.childrenNodes.splice(n,1)}),n;return-1}deleteAllChildren(){this.trackChildrenCollectionChange(()=>{this.childrenNodes=[]})}getParent(){return this.parentNode}getParentType(){return this.parentNode?this.parentNode.nodeName:Q.EmptyString}updateChild(t,n){let r=this.childrenNodes.indexOf(t);return r>-1?(n.trackParentNodeChange(()=>{n.parentNode=this}),this.trackChildrenCollectionChange(()=>{this.childrenNodes.splice(r,1,n)}),!0):!1}getAncestor(t){let n=this.getParent(),r=this.getParentType();for(;n;){if(r===t)return n;r=n.getParentType(),n=n.getParent()}return null}deleteFirstGrandChildOfName(t,n){return this.getChildren(t)[0].deleteChild(n)}deleteChildren(t,n){n=F.IsNullOrUndefined(n)?this.childrenNodes.length:n,this.trackChildrenCollectionChange(()=>{this.childrenNodes.splice(t,n)})}deleteGrandChildren(t,n,r){this.getChildren(t)[0].deleteChildren(n,r)}addGrandChild(t,n){let r=this.getChildren(t),i=null;r.length===0?(i=new e(t,this),this.addChild(i)):i=r[0],i.addChild(n)}addGrandChildAtIndex(t,n,r){let i=this.getChildren(t),o=null;i.length===0?(o=new e(t,this),this.addChild(o)):o=i[0],o.insertChildAtIndex(n,r)}GetPropertyByParameter(t){return this.getProperty(t)}getSemanticParent(){switch(this.getNodeName()){case D.formCell:let t=this.getAncestor(D.formSection);return t||(t=this.getAncestor(D.formHeader),t)||(t=this.getAncestor(D.formFooter),t)?t:null;case D.formSection:return this.getAncestor(D.formTab);case D.formTab:return this.getAncestor(D.form);default:return null}}isDirty(){return this.visit(t=>t.isInChangeSet())}isInChangeSet(){return this.changeTracker().getChangeSets().some(n=>n.changeSet.some(r=>r.targetNode.getNodeId()===this.getNodeId()))}changeTracker(){let t=this.getAncestor(D.form);return t?t.changeTracker():null}}});var H2={};Fi(H2,{ControlClassId:()=>k,ControlNamePrefixes:()=>k0,getControlDisplayNames:()=>eue});function eue(e){return{[k.AccessPrivilegeControl]:e("controls.controlNames.accessPrivilege"),[k.AccessTeamTablePickerControl]:e("controls.controlNames.accessTeamTablePicker"),[k.ACIControl]:e("controls.controlNames.aci"),[k.ActivitiesContainerControl]:e("controls.controlNames.activitiesContainer"),[k.ActivitiesWallControl]:e("controls.controlNames.activitiesWall"),[k.AppliedFiltersControl]:e("controls.controlNames.appliedFilters"),[k.ArticleContentControl]:e("controls.controlNames.articleContent"),[k.BooleanControl]:e("controls.controlNames.twoOption"),[k.ButtonControl]:e("controls.controlNames.button"),[k.CheckboxControl]:e("controls.controlNames.checkbox"),[k.CompositionLinkControl]:e("controls.controlNames.compositionLink"),[k.ConnectionControl]:e("controls.controlNames.connection"),[k.ConnectionRoleObjectTypeListControl]:e("controls.controlNames.connectionRoleObjectTypeList"),[k.CoverageChoiceControl]:e("controls.controlNames.coverageChoice"),[k.DashboardControl]:e("controls.controlNames.dashboard"),[k.DynamicPropertyListControl]:e("controls.controlNames.dynamicPropertyList"),[k.EditFilterControl]:e("controls.controlNames.editFilter"),[k.ErrorStatusControl]:e("controls.controlNames.errorStatus"),[k.GlobalFilterControl]:e("controls.controlNames.globalFilter"),[k.HiddenInputControl]:e("controls.controlNames.hiddenInput"),[k.KBViewerControl]:e("controls.controlNames.kbViewer"),[k.LabelControl]:e("controls.controlNames.label"),[k.MailMergeLanguagePickerControl]:e("controls.controlNames.mailMergeLanguagePicker"),[k.MapLinkControl]:e("controls.controlNames.mapLink"),[k.OrgInsightsControl]:e("controls.controlNames.orgInsights"),[k.ChoiceLookupControl]:e("controls.controlNames.choiceLookup"),[k.PowerBIControl]:e("controls.controlNames.powerBI"),[k.ProcessControl]:e("controls.controlNames.process"),[k.RelatedInformationControl]:e("controls.controlNames.relatedInformation"),[k.RelationshipRoleChoiceControl]:e("controls.controlNames.relationshipRoleChoice"),[k.ReportControl]:e("controls.controlNames.report"),[k.StreamsControl]:e("controls.controlNames.streams"),[k.WebResourceSilverlightControl]:e("controls.controlNames.webResourceSilverlight"),[k.CurrencyControl]:e("controls.controlNames.currency"),[k.DateTimeControl]:e("controls.controlNames.dateAndTime"),[k.DecimalControl]:e("controls.controlNames.decimal"),[k.DurationControl]:e("controls.controlNames.duration"),[k.EmailAddressControl]:e("controls.controlNames.email"),[k.FileControl]:e("controls.controlNames.file"),[k.FloatingNumberControl]:e("controls.controlNames.floatingNumber"),[k.IframeControl]:e("controls.controlNames.iframe"),[k.ImageControl]:e("controls.controlNames.image"),[k.LookupControl]:e("controls.controlNames.lookup"),[k.MapsControl]:e("controls.controlNames.maps"),[k.PhoneNumberControl]:e("controls.controlNames.phoneNumber"),[k.ChoiceControl]:e("controls.controlNames.choice"),[k.QuickViewControl]:e("controls.controlNames.quickView"),[k.QuickFormControl]:e("controls.controlNames.quickForm"),[k.CustomControl]:e("controls.controlNames.customControl"),[k.SearchWidgetControl]:e("controls.controlNames.searchWidget"),[k.SocialInsightsControl]:e("controls.controlNames.socialInsights"),[k.SubgridControl]:e("controls.controlNames.subgrid"),[k.TextAreaControl]:e("controls.controlNames.textArea"),[k.TextboxControl]:e("controls.controlNames.textBox"),[k.TickerControl]:e("controls.controlNames.ticker"),[k.UrlControl]:e("controls.controlNames.url"),[k.WebResourceHTMLControl]:e("controls.controlNames.webResourceHTML"),[k.WebResourceImageControl]:e("controls.controlNames.webResourceImage"),[k.IntegerControl]:e("controls.controlNames.integer"),[k.TimerControl]:e("controls.controlNames.timer"),[k.TimelineControl]:e("controls.controlNames.timeline"),[k.EmailBodyControl]:e("controls.controlNames.emailBody"),[k.PartyListControl]:e("controls.controlNames.partyList"),[k.TimezoneControl]:e("controls.controlNames.timezone"),[k.LanguageControl]:e("controls.controlNames.language"),[k.ChoiceStatusControl]:e("controls.controlNames.choiceStatus"),[k.ChoicesControl]:e("controls.controlNames.choices"),[k.RegardingControl]:e("controls.controlNames.regarding"),[k.EmailEngagementActionsControl]:e("controls.controlNames.emailEngagementActions"),[k.EmailRecipientActivityControl]:e("controls.controlNames.emailRecipientActivity"),[k.ReferencePanelSearchWidgetControl]:e("controls.controlNames.referencePanelSearchWidget"),[k.ReferencePanelQuickViewControl]:e("controls.controlNames.referencePanelQuickView"),[k.ReferencePanelSubgridControl]:e("controls.controlNames.referencePanelSubgrid"),[k.KBEditorControl]:e("controls.controlNames.KBEditor"),[k.LinkControl]:e("controls.controlNames.link")}}var k,k0,bl=B(()=>{"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"})(k||(k={}));k0={[k.WebResourceHTMLControl]:"WebResource",[k.WebResourceImageControl]:"WebResource",[k.IframeControl]:"IFRAME",[k.SearchWidgetControl]:"Search widget",[k.SubgridControl]:"Subgrid",[k.TimelineControl]:"Timeline",[k.QuickViewControl]:"QuickviewControl"}});var vl=C((lOe,J2)=>{var $p=new Proxy(function(){return $p},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:$p},apply:function(){return $p},construct:function(){return{}}}),K2=function(){return $p};Object.setPrototypeOf(K2,$p);J2.exports=K2});var Vr,us,Y2,Q2,td=B(()=>{"use strict";Vr="cds-designer-models",us="FormCustomControl",Y2="FormCell",Q2="Form"});var wl,PC=B(()=>{"use strict";bp();Re();wl=class e{static lockedFieldCount=new qr;static dependencyFieldCount=new qr;static getNecessaryLookUpTable(t){switch(t){case fa.DependencyFieldTable:return e.dependencyFieldCount;case fa.LockedFieldTable:return e.lockedFieldCount}}static initCanvasLockedFieldLookUp(t){switch(t){case fa.DependencyFieldTable:e.dependencyFieldCount=new qr;case fa.LockedFieldTable:e.lockedFieldCount=new qr}}}});var $0,X2=B(()=>{"use strict";Dn();En();Re();Jn();$0=class extends Se{constructor(t){super(D.controlDescription,t)}get forControl(){let t=this.getProperty(A.ForControl);return F.IsNullOrUndefined(t)?null:(t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"&&(t=t.substr(1,t.length-2)),new H(t))}set forControl(t){this.setProperty(A.ForControl,`{${t.ToString()}}`)}get customControls(){return this.getChildren(D.customControl)}set customControls(t){this.deleteAllChildren();for(let n of t)this.addChild(n)}get DefaultControlClassId(){for(let t of this.customControls)if(!F.IsNullOrUndefined(t.id))return t.id;return null}get DefaultCustomControl(){for(let t of this.customControls)if(!F.IsNullOrUndefined(t.id))return t;return null}get DefaultCustomControls(){let t=[];for(let n of this.customControls)F.IsNullOrUndefined(n.id)||t.push(n);return t}async toJSON(t){let n=await this.getCustomControlsJSON(t);return n?{UniqueId:this.forControl.guidString,CustomControls:n,VersionNumber:0,OverallVersionNumber:0}:null}async getCustomControlsJSON(t){if(this.customControls){let n=[];for(let r of this.customControls){let i=await r.toJSON(t);i&&n.push(i)}return n}return null}}});function ls(){return pa||(pa=window._makerConfig,pa&&window?.location?.search?.indexOf("useProductionConfig")>-1&&(pa={...pa,region:"prod",graphQLEndpoint:"https://graph.make.powerapps.com/"}),pa?.region==="prod"&&(pa={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/"}}},...pa}),pa||{aadClientId:"a8f7a65c-f5ba-4859-b2d6-df772c264e9d",location:"cus",region:"test",publicPath:"/",graphQLEndpoint:"https://graph.make.test.powerapps.com/"})}var pa,L0=B(()=>{"use strict";});function Z2(e,t,n){if(!e)return M0.has(e)||(window._ppux?.log?.("PPUX/Geo/NonExistent",{eventType:"Trace",team:"Shell",severity:"Error",errorCode:"GeoIsEmpty"}),M0.add("")),!1;if(e){if(e=e.toLowerCase(),M0.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:n}}),M0.add(e),!1}return!0}function tue(e){return Z2(e,RC,"Location dictionary")?RC[e.toLowerCase()]:"us"}function nue(){let e=ls().location.toLowerCase();return Z2(e,RC,"Current location dictionary")?e:"us"}var M0,RC,AOe,e1=B(()=>{"use strict";L0();M0=new Set,RC={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"};AOe=tue(nue())});var ue,SOe,t1=B(()=>{"use strict";ue={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"},SOe={[ue.USWest]:{geoName:"us",regionShortName:"wus"},[ue.USCentral]:{geoName:"us",regionShortName:"cus"},[ue.USEast]:{geoName:"us",regionShortName:"eus"},[ue.USEast2]:{geoName:"us",regionShortName:"eus2"},[ue.USWestCentral]:{geoName:"us",regionShortName:"wcus"},[ue.USWest2]:{geoName:"us",regionShortName:"wus2"},[ue.USSouthCentral]:{geoName:"br",regionShortName:"scus"},[ue.BrazilSouth]:{geoName:"br",regionShortName:"sbr"},[ue.UKSouth]:{geoName:"uk",regionShortName:"suk"},[ue.UKWest]:{geoName:"uk",regionShortName:"wuk"},[ue.JapanEast]:{geoName:"jp",regionShortName:"ejp"},[ue.JapanWest]:{geoName:"jp",regionShortName:"wjp"},[ue.IndiaCentral]:{geoName:"in",regionShortName:"cin"},[ue.IndiaSouth]:{geoName:"in",regionShortName:"sin"},[ue.ItalyNorth]:{geoName:"it",regionShortName:"nit"},[ue.GermanyWestCentral]:{geoName:"de",regionShortName:"wcde"},[ue.GermanyNorth]:{geoName:"de",regionShortName:"nde"},[ue.EuropeNorth]:{geoName:"eu",regionShortName:"neu"},[ue.EuropeWest]:{geoName:"eu",regionShortName:"weu"},[ue.AustraliaEast]:{geoName:"au",regionShortName:"eau"},[ue.AustraliaSouthEast]:{geoName:"au",regionShortName:"seau"},[ue.AsiaSouthEast]:{geoName:"as",regionShortName:"seas"},[ue.AsiaEast]:{geoName:"as",regionShortName:"eas"},[ue.CanadaCentral]:{geoName:"ca",regionShortName:"cca"},[ue.CanadaEast]:{geoName:"ca",regionShortName:"eca"},[ue.SouthAfricaNorth]:{geoName:"za",regionShortName:"nza"},[ue.SouthAfricaWest]:{geoName:"za",regionShortName:"wza"},[ue.FranceCentral]:{geoName:"fr",regionShortName:"cfr"},[ue.FranceSouth]:{geoName:"fr",regionShortName:"sfr"},[ue.UAENorth]:{geoName:"ae",regionShortName:"nae"},[ue.UAECentral]:{geoName:"ae",regionShortName:"cae"},[ue.SwedenCentral]:{geoName:"se",regionShortName:"cse"},[ue.SwitzerlandNorth]:{geoName:"ch",regionShortName:"nch"},[ue.SwitzerlandWest]:{geoName:"ch",regionShortName:"wch"},[ue.NorwayEast]:{geoName:"no",regionShortName:"eno"},[ue.NorwayWest]:{geoName:"no",regionShortName:"wno"},[ue.KoreaCentral]:{geoName:"kr",regionShortName:"ckr"},[ue.KoreaSouth]:{geoName:"kr",regionShortName:"skr"},[ue.SingaporeSouthEast]:{geoName:"sg",regionShortName:"seas"},[ue.PolandCentral]:{geoName:"pl",regionShortName:"cpl"},[ue.QatarCentral]:{geoName:"qa",regionShortName:"cqa"},[ue.NewZealandNorth]:{geoName:"nz",regionShortName:"nnz"},[ue.GovernmentUSTexas]:{geoName:"us",regionShortName:"ugtx"},[ue.GovernmentUSVirginia]:{geoName:"us",regionShortName:"ugva"},[ue.GovernmentUSDodCentral]:{regionShortName:"udc"},[ue.GovernmentUSDodEast]:{regionShortName:"ude"},[ue.ChinaEast]:{regionShortName:"cne"},[ue.ChinaEast2]:{regionShortName:"cne2"},[ue.ChinaEast3]:{regionShortName:"cne3"},[ue.ChinaNorth]:{regionShortName:"cnn"},[ue.ChinaNorth2]:{regionShortName:"cnn2"},[ue.ChinaNorth3]:{regionShortName:"cnn3"},[ue.UssecEast]:{geoName:"us",regionShortName:"erx"},[ue.UssecWest]:{geoName:"us",regionShortName:"wrx"},[ue.UsnatEast]:{geoName:"us",regionShortName:"eex"},[ue.UsnatWest]:{geoName:"us",regionShortName:"wex"}}});var n1=B(()=>{"use strict";L0();});var Lp=B(()=>{"use strict";L0();e1();t1();n1();});function Mp(e,t){return r1?r1.isOverridden(e,t):{overridden:!1}}var r1,xp=B(()=>{"use strict";});var kC=B(()=>{"use strict";Lp();xp();});function rue(e,t){let{region:n}=ls();return()=>{let r=e.settings[t];if(r.allowOverrides){let s=Mp(e.packageName,t);if(s.overridden)return typeof s.value=="string"?iue(s.value):s.value}let o=r.values,a=process.env.SETTINGS_FALLBACK_REGION?.[n];return o[n]!==void 0?o[n]:a&&o[a]!==void 0?o[a]:o.default}}function iue(e){return isNaN(Number(e))?e==="true"?!0:e==="false"?!1:e:Number(e)}function oue(e){let t=e.packageName;if(x0.has(t)){let n=`settings has already been created for this package ${t}`;throw console.error(n),new Error(n)}if(Object.keys(e.settings).some(n=>LC(t,n))){let n=`error parsing settings config for package ${t}, a feature gate with the same name exists`;throw console.error(n),new Error(n)}Object.keys(e.settings).forEach(n=>{if(Object.keys(e.settings[n].values).filter(i=>i!=="default").some(i=>!U0(i))){let i=`error parsing settings config for package ${t}, setting ${n} has invalid region`;throw console.error(i),new Error(i)}})}function Fp(e){oue(e);let t={};return Object.keys(e.settings).forEach(n=>{t[n]={enumerable:!0,get:rue(e,n)}}),x0.set(e.packageName,e),Object.defineProperties({},t)}function $C(e,t){return x0.has(e)?!!x0.get(e).settings[t]:!1}var x0,F0=B(()=>{"use strict";Lp();xp();MC();Up();x0=new Map});function i1(e,t){let{region:n}=ls();return()=>{let r=Mp(e.packageName,t);if(r.overridden)return r.value.toString()==="true";let i=e.features[t].enabledFor,o=process.env.SETTINGS_FALLBACK_REGION?.[n];return i[n]!==void 0?!!i[n]:o&&i[o]!==void 0?!!i[o]:!1}}function aue(e){let t=e.packageName;if(q0.has(t)){let n="feature gates has already been created for this package";throw console.error(n),new Error(n)}if(Object.keys(e.features).some(n=>$C(t,n))){let n=`error parsing feature gates config for package ${t}, a setting with the same name exists`;throw console.error(n),new Error(n)}Object.keys(e.features).forEach(n=>{if(Object.keys(e.features[n].enabledFor).some(i=>!U0(i))){let i=`error parsing feature gates config for package ${t}, feature ${n} has invalid region`;throw console.error(i),new Error(i)}})}function xC(e){aue(e);let t={};Object.keys(e.features).forEach(i=>{t[i]={enumerable:!0,configurable:!0,get:i1(e,i)}});let n={},r=new Set;return t.dangerouslySet={enumerable:!1,value:(i,o)=>{r.add(i),Object.defineProperty(n,i,{enumerable:!0,configurable:!0,value:o})}},t.dangerouslyReset={enumerable:!1,value:()=>{let i={};r.forEach(o=>{i[o.toString()]={enumerable:!0,configurable:!0,get:i1(e,o.toString())}}),Object.defineProperties(n,i),r.clear()}},q0.set(e.packageName,e),Object.defineProperties(n,t)}function LC(e,t){return q0.has(e)?!!q0.get(e).features[t]:!1}var q0,MC=B(()=>{"use strict";Lp();Up();xp();F0();q0=new Map});var a1=C((JOe,o1)=>{"use strict";o1.exports=function(t,n){if(n=n.split(":")[0],t=+t,!t)return!1;switch(n){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 l1=C(FC=>{"use strict";var sue=Object.prototype.hasOwnProperty,uue;function s1(e){try{return decodeURIComponent(e.replace(/\+/g," "))}catch{return null}}function u1(e){try{return encodeURIComponent(e)}catch{return null}}function lue(e){for(var t=/([^=?#&]+)=?([^&]*)/g,n={},r;r=t.exec(e);){var i=s1(r[1]),o=s1(r[2]);i===null||o===null||i in n||(n[i]=o)}return n}function cue(e,t){t=t||"";var n=[],r,i;typeof t!="string"&&(t="?");for(i in e)if(sue.call(e,i)){if(r=e[i],!r&&(r===null||r===uue||isNaN(r))&&(r=""),i=u1(i),r=u1(r),i===null||r===null)continue;n.push(i+"="+r)}return n.length?t+n.join("&"):""}FC.stringify=cue;FC.parse=lue});var BC=C((QOe,h1)=>{"use strict";var d1=a1(),B0=l1(),f1=/[\n\r\t]/g,due=/^[A-Za-z][A-Za-z0-9+-.]*:\/\//,fue=/^([a-z][a-z0-9.+-]*:)?(\/\/)?([\\/]+)?([\S\s]*)/i,pue=/^[a-zA-Z]:/,mue=/^[\x00-\x20\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]+/;function qC(e){return(e||"").toString().replace(mue,"")}var UC=[["#","hash"],["?","query"],function(t,n){return ma(n.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]],c1={hash:1,query:1};function p1(e){var t;typeof window<"u"?t=window:typeof global<"u"?t=global:typeof self<"u"?t=self:t={};var n=t.location||{};e=e||n;var r={},i=typeof e,o;if(e.protocol==="blob:")r=new ha(unescape(e.pathname),{});else if(i==="string"){r=new ha(e,{});for(o in c1)delete r[o]}else if(i==="object"){for(o in e)o in c1||(r[o]=e[o]);r.slashes===void 0&&(r.slashes=due.test(e.href))}return r}function ma(e){return e==="file:"||e==="ftp:"||e==="http:"||e==="https:"||e==="ws:"||e==="wss:"}function m1(e,t){e=qC(e),e=e.replace(f1,""),t=t||{};var n=fue.exec(e),r=n[1]?n[1].toLowerCase():"",i=!!n[2],o=!!n[3],a=0,s;return i?o?(s=n[2]+n[3]+n[4],a=n[2].length+n[3].length):(s=n[2]+n[4],a=n[2].length):o?(s=n[3]+n[4],a=n[3].length):s=n[4],r==="file:"?a>=2&&(s=s.slice(2)):ma(r)?s=n[4]:r?i&&(s=s.slice(2)):a>=2&&ma(t.protocol)&&(s=n[4]),{protocol:r,slashes:i||ma(r),slashesCount:a,rest:s}}function hue(e,t){if(e==="")return t;for(var n=(t||"/").split("/").slice(0,-1).concat(e.split("/")),r=n.length,i=n[r-1],o=!1,a=0;r--;)n[r]==="."?n.splice(r,1):n[r]===".."?(n.splice(r,1),a++):a&&(r===0&&(o=!0),n.splice(r,1),a--);return o&&n.unshift(""),(i==="."||i==="..")&&n.push(""),n.join("/")}function ha(e,t,n){if(e=qC(e),e=e.replace(f1,""),!(this instanceof ha))return new ha(e,t,n);var r,i,o,a,s,u,l=UC.slice(),c=typeof t,d=this,f=0;for(c!=="object"&&c!=="string"&&(n=t,t=null),n&&typeof n!="function"&&(n=B0.parse),t=p1(t),i=m1(e||"",t),r=!i.protocol&&!i.slashes,d.slashes=i.slashes||r&&t.slashes,d.protocol=i.protocol||t.protocol||"",e=i.rest,(i.protocol==="file:"&&(i.slashesCount!==2||pue.test(e))||!i.slashes&&(i.protocol||i.slashesCount<2||!ma(d.protocol)))&&(l[3]=[/(.*)/,"pathname"]);f<l.length;f++){if(a=l[f],typeof a=="function"){e=a(e,d);continue}o=a[0],u=a[1],o!==o?d[u]=e:typeof o=="string"?(s=o==="@"?e.lastIndexOf(o):e.indexOf(o),~s&&(typeof a[2]=="number"?(d[u]=e.slice(0,s),e=e.slice(s+a[2])):(d[u]=e.slice(s),e=e.slice(0,s)))):(s=o.exec(e))&&(d[u]=s[1],e=e.slice(0,s.index)),d[u]=d[u]||r&&a[3]&&t[u]||"",a[4]&&(d[u]=d[u].toLowerCase())}n&&(d.query=n(d.query)),r&&t.slashes&&d.pathname.charAt(0)!=="/"&&(d.pathname!==""||t.pathname!=="")&&(d.pathname=hue(d.pathname,t.pathname)),d.pathname.charAt(0)!=="/"&&ma(d.protocol)&&(d.pathname="/"+d.pathname),d1(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:"&&ma(d.protocol)&&d.host?d.protocol+"//"+d.host:"null",d.href=d.toString()}function gue(e,t,n){var r=this;switch(e){case"query":typeof t=="string"&&t.length&&(t=(n||B0.parse)(t)),r[e]=t;break;case"port":r[e]=t,d1(t,r.protocol)?t&&(r.host=r.hostname+":"+t):(r.host=r.hostname,r[e]="");break;case"hostname":r[e]=t,r.port&&(t+=":"+r.port),r.host=t;break;case"host":r[e]=t,/:\d+$/.test(t)?(t=t.split(":"),r.port=t.pop(),r.hostname=t.join(":")):(r.hostname=t,r.port="");break;case"protocol":r.protocol=t.toLowerCase(),r.slashes=!n;break;case"pathname":case"hash":if(t){var i=e==="pathname"?"/":"#";r[e]=t.charAt(0)!==i?i+t:t}else r[e]=t;break;case"username":case"password":r[e]=encodeURIComponent(t);break;case"auth":var o=t.indexOf(":");~o?(r.username=t.slice(0,o),r.username=encodeURIComponent(decodeURIComponent(r.username)),r.password=t.slice(o+1),r.password=encodeURIComponent(decodeURIComponent(r.password))):r.username=encodeURIComponent(decodeURIComponent(t))}for(var a=0;a<UC.length;a++){var s=UC[a];s[4]&&(r[s[1]]=r[s[1]].toLowerCase())}return r.auth=r.password?r.username+":"+r.password:r.username,r.origin=r.protocol!=="file:"&&ma(r.protocol)&&r.host?r.protocol+"//"+r.host:"null",r.href=r.toString(),r}function yue(e){(!e||typeof e!="function")&&(e=B0.stringify);var t,n=this,r=n.host,i=n.protocol;i&&i.charAt(i.length-1)!==":"&&(i+=":");var o=i+(n.protocol&&n.slashes||ma(n.protocol)?"//":"");return n.username?(o+=n.username,n.password&&(o+=":"+n.password),o+="@"):n.password?(o+=":"+n.password,o+="@"):n.protocol!=="file:"&&ma(n.protocol)&&!r&&n.pathname!=="/"&&(o+="@"),r[r.length-1]===":"&&(r+=":"),o+=r+n.pathname,t=typeof n.query=="object"?e(n.query):n.query,t&&(o+=t.charAt(0)!=="?"?"?"+t:t),n.hash&&(o+=n.hash),o}ha.prototype={set:gue,toString:yue};ha.extractProtocol=m1;ha.location=p1;ha.trimLeft=qC;ha.qs=B0;h1.exports=ha});var bue,g1=B(()=>{"use strict";bue=Xe(BC());});function VC(e,t,n){let r=Object.keys(n).sort();if(r.length===0)throw new Error(`ECS feature has no properties: ${e}.${t}`);let i=`ecs.${e}.${t}`;return r.length===1?`${i}.${r[0]}`:`${i}.{${r.join(";")}}`}var V0=B(()=>{"use strict";});var GC,jC,WC=B(()=>{"use strict";V0();GC=class{features=new Map;register(t,n){let r=VC(n,t.teamName,t.fallback),i={clientName:n,teamName:t.teamName,fullName:r,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(r,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(n=>n.clientName===t)}getByTeam(t){return this.getAll().filter(n=>n.teamName===t)}search(t){let n=t.toLowerCase();return this.getAll().filter(r=>r.fullName.toLowerCase().includes(n)||r.description?.toLowerCase().includes(n)||r.teamName.toLowerCase().includes(n)||r.clientName.toLowerCase().includes(n))}getClientNames(){let t=new Set;return this.features.forEach(n=>t.add(n.clientName)),Array.from(t)}getTeamNames(){let t=new Set;return this.features.forEach(n=>t.add(n.teamName)),Array.from(t)}clear(){this.features.clear()}},jC=new GC});var zC=B(()=>{"use strict";});function U0(e){return vue.has(e)}var vue,Up=B(()=>{"use strict";kC();MC();F0();xp();kC();g1();WC();V0();zC();vue=new Set(["tie","test","prod","preview","preprod","gov","high","dod","mooncake","ex","rx"])});var wue,y1=B(()=>{"use strict";Up();wue=Fp({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 E1,KC,nd,El,HC,G0,rd,cs,xt,b1,v1,w1,Io=B(()=>{"use strict";E1={ThreeEqColumn_FirstColumn:34,ThreeEqColumn_SecondColumn:33,ThreeEqColumn_ThirdColumn:33,FiveEqColumn:20},KC={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"})(nd||(nd={}));(function(e){e.Left="Left",e.Right="Right",e.Center="Center"})(El||(El={}));(function(e){e[e.Mobile=0]="Mobile",e[e.Tablet=1]="Tablet",e[e.Web=2]="Web"})(HC||(HC={}));G0=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"})(rd||(rd={}));cs=class{static StartTag="<"},xt={ShowLabel:"true",LockLevel:"0",IsUserDefined:"0",LabelWidth:"115",columns:"1",ShowBar:"false",Layout:"varwidth",namePrefix:"_section_",labelAlignment:El.Left,labelPosition:rd.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"})(b1||(b1={}));(function(e){e.TabWithLockedFieldRemoval="TabWithLockedFieldRemoval",e.SectionWithLockedFieldRemoval="SectionWithLockedFieldRemoval",e.LockedSectionRemoval="LockedSectionRemoval",e.LockedFieldRemoval="LockedFieldRemoval",e.RequiredFieldRemoval="RequiredFieldRemoval",e.LastRemainingTab="LastRemainingTab",e.UnknownRemoval="UnknownRemoval"})(v1||(v1={}));(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"})(w1||(w1={}))});var JC,A1=B(()=>{"use strict";(function(e){e.DefaultValue="defaultValue",e.Loaded="loaded"})(JC||(JC={}))});var N1,Eue,C1,zDe,HDe,qp,S1,KDe,JDe,_1=B(()=>{"use strict";N1=Xe(vl());En();td();y1();xc();Io();cl();Re();Eue=Xe(Ds());A1();(function(e){e.Model="Model",e.Canvas="Canvas",e.CustomPages="CustomPages"})(C1||(C1={}));zDe={Read:eu.Read,Edit:eu.Edit,Both:eu.Both,Container:eu.Container},HDe={input:ll.Input,bound:ll.Bound,output:ll.Output};(function(e){e[e.dataset=0]="dataset",e[e.property=1]="property",e[e.groups=2]="groups",e[e.group=3]="group"})(qp||(qp={}));(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"})(S1||(S1={}));KDe=new Set([j.Currency,j.Decimal,j.FP,j.Multiple,j.SingleLineEmail,j.SingleLinePhone,j.SingleLineText,j.SingleLineTextArea,j.SingleLineURL,j.SingleLineTickerSymbol,j.WholeNone,j.WholeDuration,j.WholeLanguage,j.WholeTimeZone,j.Enum,j.LookupSimple,j.LookupCustomer,j.LookupOwner,j.LookupPartyList,j.LookupRegarding,j.TwoOptions,j.Boolean,j.PowerBIReport,j.DateAndTimeDateAndTime,j.DateAndTimeDateOnly,j.OptionSet,j.MultiSelectOptionSet,j.CardForm]),JDe={numbers:[j.WholeNone,j.FP,j.Decimal,j.Currency],text:[j.SingleLineText,j.SingleLineTextArea,j.Multiple],lookup:[j.LookupSimple,j.LookupCustomer,j.LookupOwner,j.LookupPartyList,j.LookupRegarding],dates:[j.DateAndTimeDateOnly,j.DateAndTimeDateAndTime],allFields:[j.TwoOptions,j.DateAndTimeDateOnly,j.DateAndTimeDateAndTime,j.FP,j.Decimal,j.WholeNone,j.WholeDuration,j.WholeTimeZone,j.WholeLanguage,j.LookupSimple,j.LookupCustomer,j.LookupOwner,j.LookupPartyList,j.LookupRegarding,j.Multiple,j.OptionSet,j.SingleLineText,j.SingleLineTextArea,j.SingleLineEmail,j.SingleLineURL,j.SingleLineTickerSymbol,j.SingleLinePhone]}});var To,j0,I1=B(()=>{"use strict";To=Xe(vl());Dn();En();Sr();td();cl();_1();xc();Re();Jn();Io();j0=class extends Se{constructor(t){super(D.customControl,t)}customControlId;get id(){let t=this.getProperty(A.id);return F.IsNullOrUndefined(t)?null:t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"?new H(t.substr(1,t.length-2)):new H(t)}getParameters(){let t=new Map,n=this.getAllChildren();if(n&&n.length!==0&&n[0]){let r=n[0].getAllChildren();if(r!=null){for(let i of r)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 n=this.getParameters()?.get(vr.value);if(n?.length>0){let r=n[0],i=r?.getAllChildren()?.length>0?r.getAllChildren().find(a=>a.getNodeName()===t):null,o=i?.getAllChildren()?.length>0?i.getAllChildren()[0].getNodeName():"";return this.normalizePropertyValue(o)}}getParameterValue(t){let n=this.getParameterNodeChild(t);return n&&this.normalizePropertyValue(n.getNodeName())}getParameterNodeChild(t){let n=this.getParameters().get(t);return n?.length>0&&n[0].getAllChildren()?.length>0?n[0].getAllChildren()[0]:null}getDatasetName(t){return t.getAllProperties().find(n=>n.key===vr.name)?.value}getParameterChildrenValues(t,n,r){if(this.isDataSet(t)){let i=n.find(l=>l.key===vr.name)?.value,o={Name:i,Type:j.Grid,Columns:[]},u=this.getParameters().get(vr.dataset).find(l=>this.getDatasetName(l)===i).getAllChildren();for(let l of u){let c=l.getNodeName();if(l&&l.getAllChildren().length>0){let d=this.normalizePropertyValue(l.getAllChildren()[0].getNodeName());o[c]=d}}return o}}getParameterIsStatic(t){let n=!1,r=this.getParameters().get(t)[0],i=r&&r.getAllProperties();if(i){for(let o of i)if(o.key===A.static&&o.value==="true"){n=!0;break}}return n}get name(){return this.getProperty(A.Name)}get formFactor(){return this.getProperty(A.formFactor)}set formFactor(t){this.setProperty(A.formFactor,t)}async toJSON(t){if(this.id)return null;let n=await this.parametersToJSON(t),r=parseInt(this.formFactor,10);return{CustomControlId:this.customControlId,FormFactor:isNaN(r)?-1:r,Name:this.name,Version:null,Parameters:n,ShouldOverrideControlVisible:!1}}normalizePropertyValue(t){return t.startsWith(cs.StartTag)&&(t=t.substring(1)),t}async parametersToJSON(t){let n=[];if(!this.name)return n;try{let r=await t.formModelService.customControlDiscoveryService.getCustomControlMetadata(this.name);if(r)if(r.configurations){let i=r.configurations,o=this.getParameters();for(let[a,s]of o)if(this.isDataSet(a))for(let u of o.get(a)){let l=u.getAllProperties(),c=this.getDatasetName(u),d=i.get(c),f=await this.parameterJSON(a,l,d,t);n.push({Name:c,Value:f})}else if(this.isGroups(s))n.push({Name:a,Value:{Type:IA.GroupDefinition,Value:this.normalizePropertyValue(this.getParameterNodeChild(s[0].NodeName).NodeName)}}),i.get(a).groupSet?.forEach(l=>{l.groupConfigurableProperties.forEach(async c=>{let d=c.name;c.propertyType===qp.dataset?o.get(vr.dataset)?.some(p=>this.getDatasetName(p)===d)||n.push({Name:d,Value:{Name:d,Columns:[],Type:j.Grid}}):c.propertyType===qp.property&&(o.has(d)||n.push({Name:d,Value:{Usage:c.usage}}))})});else{let u=s[0].getAllProperties(),l=i.get(a),c=await this.parameterJSON(a,u,l,t);if(c)n.push({Name:a,Value:c});else{(0,To.trackInfoTrace)(Vr,{eventName:`${us}/parametersToJSON`,eventData:{message:`Configuration metadata for custom control parameter ${a} is not available for custom control : ${this.name}.`}}),n=[];break}}}else(0,To.trackErrorTrace)(Vr,{eventName:`${us}/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,To.trackErrorTrace)(Vr,{eventName:`${us}/parametersToJSON`,eventData:{message:"Custom Control Manifest not found"}},new Error(`No custom control manifest found for ${this.name}`))}catch(r){(0,To.trackErrorTrace)(Vr,{eventName:`${us}/parametersToJSON`,eventData:{message:"parameters to json failed"}},r)}return n}async parameterJSON(t,n,r,i){if(this.isDataSet(t)){let o=r,a=n.find(s=>s.key===vr.name)?.value;if(o)return this.getParameterChildrenValues(t,n);{let s=new Error(`No dataset manifest info for ${a}`);(0,To.trackErrorTrace)(Vr,{eventName:`${us}/parameterJSON`,eventData:{message:"Missing custom control manifest dataset info"}},s)}}else{let o=r,a=n&&n.find(u=>u.key===A.Type),s=o&&!o.ofTypeGroup.every(u=>!Xg.includes(u));if(this.isLookupType(a?.value)||this.isLookupType(o?.ofType)||s)if(o){let u=o.usage,l=this.getParameterIsStatic(t),c=o.isPrimary;if(this.name===is.FormComponent){let d=this.getFormComponentValueByParameterName(A.bindAttribute),f=await i.formModelService.loadLookupModel(d),p=f.lookupColumn,m=this.getLookupDataTypeFromAttributeMetadata(p);return{Name:t,Type:m,Usage:u,Static:l,Primary:c,EntityName:f.primaryTableName,Value:d,ViewId:this.getFormComponentValueByParameterName(_A.DefaultViewId),TargetEntityType:p.targets[0],FilterRelationshipName:this.getFormComponentValueByParameterName(A.FilterRelationshipName),AvailableViewIds:this.getFormComponentValueByParameterName(A.AvailableViewIds),DependentAttributeName:this.getFormComponentValueByParameterName(A.DependentAttributeName),DependentAttributeType:this.getFormComponentValueByParameterName(A.DependentAttributeType),AllowFilterOff:Q.IsStrictTrue(this.getFormComponentValueByParameterName(A.AllowFilterOff)),DisableQuickFind:Q.IsStrictTrue(this.getFormComponentValueByParameterName(A.DisableQuickFind)),EnableViewPicker:!Q.IsStrictTrue(this.getFormComponentValueByParameterName(A.DisableViewPicker))}}return{Name:t,Usage:u,Static:l,Primary:c,Value:this.getParameterValue(t)}}else{let u=new Error(`No lookup manifest info for ${t}`);(0,To.trackErrorTrace)(Vr,{eventName:`${us}/parameterJSON`,eventData:{message:"Missing custom control manifest lookup property info"}},u)}if(o){let u=o.usage,l=this.getParameterIsStatic(t),c=this.getParameterValue(t),d=o.isPrimary;if(a){let p=a.value;return{Type:p,Static:l,Usage:u,Value:this.isNumberTypeProperty(o,p)&&Number(c)?Number(c):c,Primary:d}}if(o.ofType)return{Type:o.ofType,Static:l,Usage:u,Value:c,Primary:!0};if(o.ofTypeGroup)return{Static:l,Usage:u,Value:c,Primary:!0};let f=new Error(`No property type info for ${t}`);(0,To.trackErrorTrace)(Vr,{eventName:`${us}/parameterJSON`,eventData:{message:"Missing property type info"}},f)}else{let u=new Error(`No property manifest info for ${t}`);(0,To.trackWarningTrace)(Vr,{eventName:`${us}/parameterJSON`,eventData:{message:"Missing custom control manifest property info"}},u)}}return null}getLookupDataTypeFromAttributeMetadata(t){let{attributeType:n,format:r}=t;switch(n){case V.Customer:return j.LookupCustomer;case V.Owner:return j.LookupOwner;case V.PartyList:return j.LookupPartyList;default:return r===ne.Regarding?j.LookupRegarding:j.LookupSimple}}isLookupType(t){return Xg.includes(t)}isNumberTypeProperty(t,n){return Zg.includes(n)||t.ofTypeGroup.some(r=>Zg.includes(r))}isDataSet(t){return vr.dataset===t}isGroups(t){return!!t[0].getAllProperties().find(r=>r.key==="isGroup"&&r.value==="true")}}});var be,YC=B(()=>{"use strict";be=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 T1={};Fi(T1,{CustomControlUniqueId:()=>Al,DeprecatedControlClassIds:()=>te,FieldControlTypes:()=>An,mapFieldTypeToControl:()=>Aue});function Aue(e,t){switch(e){case V.TwoOptions:return k.BooleanControl;case V.Customer:case V.CustomerType:return k.LookupControl;case V.DateTime:return t===ne.DateAndTime?k.DateTimeControl:k.DateTimeControl;case V.DecimalNumber:return k.DecimalControl;case V.FloatingPointNumber:return k.FloatingNumberControl;case V.WholeNumber:return t===ne.Duration?k.DurationControl:t===ne.Language?k.LanguageControl:t===ne.TimeZone?k.TimezoneControl:k.IntegerControl;case V.CustomerType:case V.Lookup:case V.LookupType:return t===ne.Regarding?k.RegardingControl:k.LookupControl;case V.MultipleLineofText:return t===ne.Email?k.EmailBodyControl:k.TextAreaControl;case V.Currency:return k.CurrencyControl;case V.Owner:case V.OwnerType:return k.LookupControl;case V.PartyList:case V.PartyListType:return k.PartyListControl;case V.Status:case V.OptionSet:return k.ChoiceControl;case V.SingleLineofText:return t===ne.Email?k.EmailAddressControl:t===ne.Phone?k.PhoneNumberControl:t===ne.Text?k.TextboxControl:t===ne.TextArea?k.TextAreaControl:t===ne.TickerSymbol?k.TickerControl:t===ne.Url?k.UrlControl:t===ne.PhoneticGuide?k.TextboxControl:k.TextboxControl;case V.MultiSelectOptionSet:return k.ChoicesControl;case V.Image:return k.ImageControl;case V.File:return k.FileControl;case V.State:return k.ChoiceControl;case V.Status:return k.ChoiceStatusControl;default:throw new Error(`Cannot get base control for ${e} field type`)}}var te,Al,An,Bp=B(()=>{"use strict";Dn();bp();En();Sr();xc();bl();YC();Io();te=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"}};Al=class{static get RelationshipAssistant(){return"3ff9a528-dd50-4aca-8f10-2e5ed73513ad"}static get PredictiveLeadScoring(){return"6f503f2a-d033-4106-b62c-f8f2e5f01a57"}},An=class e{static FieldControlIds=e.initializeFieldControls();static UnboundControlIds=e.initializeUnboundControls();static ControlsAllowedForReferencePanel=e.initializeReferencePanelControls();static ControlsAllowedForFooter=e.initializeFooterControls();static CustomControlIdMap=new qr;static initializeFieldControls(){let t=new qr,n=e.getControlName(V.SingleLineofText,ne.Phone);t.add(n,new H(te.PhoneNumberControl));let r=e.getControlName(V.SingleLineofText,ne.TextArea);t.add(r,new H(te.TextAreaControl));let i=e.getControlName(V.SingleLineofText,ne.Text);t.add(i,new H(te.TextBoxControl));let o=e.getControlName(V.SingleLineofText,ne.Email);t.add(o,new H(te.EmailAddressControl));let a=e.getControlName(V.SingleLineofText,ne.Url);t.add(a,new H(te.UrlControl));let s=e.getControlName(V.SingleLineofText,ne.TickerSymbol);t.add(s,new H(te.TickerControl));let u=e.getControlName(V.SingleLineofText,ne.PhoneticGuide);t.add(u,new H(te.TextBoxControl));let l=e.getControlName(V.WholeNumber,ne.Duration);t.add(l,new H(te.DurationControl));let c=e.getControlName(V.WholeNumber,ne.Language);t.add(c,new H(te.LanguagePickerControl));let d=e.getControlName(V.WholeNumber,ne.TimeZone);t.add(d,new H(te.TimeZonePicklistControl));let f=e.getControlName(V.WholeNumber,ne.None);t.add(f,new H(te.IntegerControl));let p=e.getControlName(V.DateTime,ne.DateOnly);t.add(p,new H(te.DateTimeControl));let m=e.getControlName(V.DateTime,ne.DateAndTime);t.add(m,new H(te.DateTimeControl));let h=e.getControlName(V.LookupType,ne.None);t.add(h,new H(te.LookupControl));let g=e.getControlName(V.CustomerType,ne.None);t.add(g,new H(te.LookupControl));let y=e.getControlName(V.FloatingPointNumber,ne.None);t.add(y,new H(te.FloatControl));let b=e.getControlName(V.DecimalNumber,ne.None);t.add(b,new H(te.DecimalControl));let E=e.getControlName(V.Currency,ne.None);t.add(E,new H(te.MoneyControl));let w=e.getControlName(V.MultipleLineofText,ne.None);t.add(w,new H(te.TextAreaControl));let _=e.getControlName(V.MultipleLineofText,ne.Text);t.add(_,new H(te.TextAreaControl));let I=e.getControlName(V.MultipleLineofText,ne.TextArea);t.add(I,new H(te.TextAreaControl));let T=e.getControlName(V.MultipleLineofText,ne.Email);t.add(T,new H(te.EmailBodyControl));let O=e.getControlName(V.OptionSet,ne.None);t.add(O,new H(te.PicklistControl));let v=e.getControlName(V.TwoOptions,ne.None);t.add(v,new H(te.RadioControl));let N=e.getControlName(V.Image,ne.None);t.add(N,new H(te.WebResourceImageControl));let S=e.getControlName(V.Image,ne.None);t.add(S,new H(te.WebResourceHtmlControl));let R=e.getControlName(V.TwoOptions,"Radio");t.add(R,new H(te.RadioControl));let x=e.getControlName(V.TwoOptions,"CheckBox");t.add(x,new H(te.CheckBoxControl));let G=e.getControlName(V.TwoOptions,"List");t.add(G,new H(te.PicklistControl));let U=e.getControlName(V.State,ne.None);t.add(U,new H(te.PicklistControl));let M=e.getControlName(V.Status,ne.None);t.add(M,new H(te.PicklistStatusControl));let q=e.getControlName(V.OwnerType,ne.None);t.add(q,new H(te.LookupControl));let X=e.getControlName(V.PartyListType,ne.None);t.add(X,new H(te.PartyListControl));let ye=e.getControlName(V.LookupType,ne.Regarding);t.add(ye,new H(te.RegardingControl));let Ve=e.getControlName(V.MultiSelectOptionSet,ne.None);return t.add(Ve,new H(te.ChoicesControl)),t}static getControlName(t,n){return t+"_"+n}static getControlIdByTypeAndFormat(t,n){let r=e.getControlName(t.toString(),n.toString());return e.FieldControlIds.containsKey(r)?e.FieldControlIds.getValue(r):null}static getTypeAndFormatByControlOrUniqueId(t){for(let n in e.FieldControlIds.getKeys())if(e.FieldControlIds.getValue(e.FieldControlIds.getKeys()[n]).guidString.toLowerCase()===t)return e.FieldControlIds.getKeys()[n]}static getControlDataTypeByControlOrUniqueId(t){if(!F.IsNullOrEmptyGuid(t)){let n=e.getTypeAndFormatByControlOrUniqueId(t.guidString.toLowerCase());return n=F.IsNullOrUndefined(n)?e.getUnboundControlNameFromIdentifier(t):n.substring(0,n.indexOf("_")),n}return null}static isCustomControl(t){return F.IsNullOrUndefined(t.control)||F.IsNullOrUndefined(t.control.ClassId)||t.control.ClassId.guidString===te.CustomControl}static initializeUnboundControls(){let t=new qr;return t.add(te.ACIControl,be.ACIControl),t.add(te.IframeControl,be.IframeControl),t.add(te.SearchWidgetControl,be.SearchWidgetControl),t.add(te.MapsControl,be.MapsControl),t.add(te.QuickFormCollectionControl,be.QuickFormCollectionControl),t.add(te.GridControl,be.SubGridControl),t.add(te.WebResourceImageControl,be.WebResourceImageControl),t.add(te.WebResourceHtmlControl,be.WebResourceHtmlControl),t.add(te.ReferencePanelSearchWidget,be.SearchWidgetControl),t.add(te.ReferencePanelQuickFormCollectionControl,be.QuickFormCollectionControl),t.add(te.ReferencePanelSubgridControl,be.SubGridControl),t.add(te.TimerControl,be.TimerControl),t.add(te.TimeLineControl,be.NotesControl),t.add(te.TimeLineControlUC,be.NotesControl),t.add(te.SocialInsightControl,be.SocialInsightControl),t.add(Al.RelationshipAssistant,be.CustomControl),t}static initializeReferencePanelControls(){let t=new qr;return t.add(te.IframeControl,be.IframeControl),t.add(te.ReferencePanelSearchWidget,be.SearchWidgetControl),t.add(te.ReferencePanelQuickFormCollectionControl,be.QuickFormCollectionControl),t.add(te.ReferencePanelSubgridControl,be.SubGridControl),t.add(te.WebResourceHtmlControl,be.WebResourceHtmlControl),t.add(te.WebResourceImageControl,be.WebResourceHtmlControl),t}static initializeFooterControls(){let t=new Mc;return t.add(nd.IFRAME,!0),t.add(nd.SPACER,!0),t.add(nd.WEB_RESOURCE_HTML,!0),t}static isUnboundFormControl(t){if(F.IsNullOrUndefined(t)||F.IsNullOrUndefined(t.control)||F.IsNullOrUndefined(t.control.ClassId))return!1;let n=e.getUniqueIdentifierForControl(t.control);return e.UnboundControlIds.containsKey(n.guidString)}static isReferencePanelSection(t){return!F.IsNullOrUndefined(t)&&!F.IsNullOrUndefined(t.Name)&&t.Name.indexOf(xt.referencePanelNamePrefix)===0}static isUnboundFormControlByIdentifier(t){return F.IsNullOrUndefined(t)||F.IsNullOrUndefined(t.guidString)?!1:e.UnboundControlIds.containsKey(t.guidString)}static getUnboundFormControlName(t){let n=Q.EmptyString;if(F.IsNullOrUndefined(t)||F.IsNullOrUndefined(t.control)||F.IsNullOrUndefined(t.control.ClassId))return n;let r=e.getUniqueIdentifierForControl(t.control);return e.UnboundControlIds.getValue(r.guidString).toString()}static getUnboundControlNameFromIdentifier(t){return F.IsNullOrUndefined(t)||F.IsNullOrUndefined(t.guidString)?Q.EmptyString:e.UnboundControlIds.getValue(t.guidString).toString()}static isSpacerControl(t){return t===te.SpacerControl}static GetRowSpan(t){let n=t.ClassId;if(e.isRelationshipAssistantControl(t))n=t.UniqueId;else if(n.guidString===te.CustomControl&&!F.IsNullOrUndefined(t.UniqueId)){let r=t.UniqueId.ToString();e.CustomControlIdMap.containsKey(r)&&(n=e.CustomControlIdMap.getValue(r))}switch(e.UnboundControlIds.getValue(n.guidString)){case be.IframeControl:case be.ACIControl:case be.SocialInsightControl:return 6;case be.SubGridControl:case be.CustomControl:return 4;case be.WebResourceImageControl:return 15;case be.WebResourceHtmlControl:return 15;case be.MapsControl:return 8;case be.SearchWidgetControl:return 10;case be.NotesControl:case be.TimeLineControl:return 15;case be.TimerControl:return 2;default:}}static isLookUpControl(t){return!F.IsNullOrUndefined(t)&&t.ClassId.guidString===te.LookupControl}static isRelationshipAssistantOrLeadScoringControl(t){return!F.IsNullOrUndefined(t)&&e.isRelationshipAssistantOrLeadScoring(t.UniqueId)}static isRelationshipAssistantOrLeadScoring(t){return!F.IsNullOrUndefined(t)&&(t.guidString===Al.RelationshipAssistant||t.guidString===Al.PredictiveLeadScoring)}static isRelationshipAssistantControl(t){return!F.IsNullOrUndefined(t)&&e.isRelationshipAssistant(t.UniqueId)}static isRelationshipAssistant(t){return!F.IsNullOrUndefined(t)&&t.guidString===Al.RelationshipAssistant}static getUniqueIdentifierForControl(t){if(F.IsNullOrUndefined(t))return null;let n=t.ClassId;if(e.isRelationshipAssistantControl(t))n=t.UniqueId;else if(n.guidString===te.CustomControl&&!F.IsNullOrUndefined(t.UniqueId)){let r=t.UniqueId.ToString();e.CustomControlIdMap.containsKey(r)&&(n=e.CustomControlIdMap.getValue(r))}return n}}});var W0,O1=B(()=>{"use strict";W0=class{listeners=[];listenersOncer=[];on(t){return this.listeners.push(t),{dispose:()=>this.off(t)}}once(t){this.listenersOncer.push(t)}off(t){let n=this.listeners.indexOf(t);n>-1&&this.listeners.splice(n,1)}emit(t){this.listeners.forEach(n=>n(t)),this.listenersOncer.forEach(n=>n(t)),this.listenersOncer=[]}pipe(t){return this.on(n=>t.emit(n))}}});var Cl,id,D1,P1,lu,R1,k1,QC=B(()=>{"use strict";(function(e){e[e.Center=0]="Center",e[e.Left=1]="Left",e[e.Right=2]="Right"})(Cl||(Cl={}));(function(e){e[e.Left=0]="Left",e[e.Top=1]="Top"})(id||(id={}));(function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle"})(D1||(D1={}));(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"})(P1||(P1={}));(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"})(lu||(lu={}));(function(e){e[e.None=0]="None",e[e.SystemRequired=1]="SystemRequired",e[e.ApplicationRequired=2]="ApplicationRequired",e[e.Recommended=3]="Recommended"})(R1||(R1={}));(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"})(k1||(k1={}))});var od,$1=B(()=>{"use strict";Up();od=xC({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 L1(e){return{...e,extractConfig:t=>Cue(t,Object.keys(e.fallback))}}function Cue(e,t){let n={};for(let r of t)typeof e[r]<"u"&&(n[r]=e[r]);return n}var XC=B(()=>{"use strict";});var ZC=C((APe,x1)=>{var Vp=new Proxy(function(){return Vp},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:Vp},apply:function(){return Vp},construct:function(){return{}}}),M1=function(){return Vp};Object.setPrototypeOf(M1,Vp);x1.exports=M1});var q1=C((CPe,U1)=>{var Gp=new Proxy(function(){return Gp},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:Gp},apply:function(){return Gp},construct:function(){return{}}}),F1=function(){return Gp};Object.setPrototypeOf(F1,Gp);U1.exports=F1});var eS=C((SPe,V1)=>{var jp=new Proxy(function(){return jp},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:jp},apply:function(){return jp},construct:function(){return{}}}),B1=function(){return jp};Object.setPrototypeOf(B1,jp);V1.exports=B1});var j1=C((NPe,G1)=>{function Sue(){this.__data__=[],this.size=0}G1.exports=Sue});var ad=C((_Pe,W1)=>{function Nue(e,t){return e===t||e!==e&&t!==t}W1.exports=Nue});var Wp=C((IPe,z1)=>{var _ue=ad();function Iue(e,t){for(var n=e.length;n--;)if(_ue(e[n][0],t))return n;return-1}z1.exports=Iue});var K1=C((TPe,H1)=>{var Tue=Wp(),Oue=Array.prototype,Due=Oue.splice;function Pue(e){var t=this.__data__,n=Tue(t,e);if(n<0)return!1;var r=t.length-1;return n==r?t.pop():Due.call(t,n,1),--this.size,!0}H1.exports=Pue});var Y1=C((OPe,J1)=>{var Rue=Wp();function kue(e){var t=this.__data__,n=Rue(t,e);return n<0?void 0:t[n][1]}J1.exports=kue});var X1=C((DPe,Q1)=>{var $ue=Wp();function Lue(e){return $ue(this.__data__,e)>-1}Q1.exports=Lue});var ex=C((PPe,Z1)=>{var Mue=Wp();function xue(e,t){var n=this.__data__,r=Mue(n,e);return r<0?(++this.size,n.push([e,t])):n[r][1]=t,this}Z1.exports=xue});var zp=C((RPe,tx)=>{var Fue=j1(),Uue=K1(),que=Y1(),Bue=X1(),Vue=ex();function sd(e){var t=-1,n=e==null?0:e.length;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}sd.prototype.clear=Fue;sd.prototype.delete=Uue;sd.prototype.get=que;sd.prototype.has=Bue;sd.prototype.set=Vue;tx.exports=sd});var rx=C((kPe,nx)=>{var Gue=zp();function jue(){this.__data__=new Gue,this.size=0}nx.exports=jue});var ox=C(($Pe,ix)=>{function Wue(e){var t=this.__data__,n=t.delete(e);return this.size=t.size,n}ix.exports=Wue});var sx=C((LPe,ax)=>{function zue(e){return this.__data__.get(e)}ax.exports=zue});var lx=C((MPe,ux)=>{function Hue(e){return this.__data__.has(e)}ux.exports=Hue});var tS=C((xPe,cx)=>{var Kue=typeof global=="object"&&global&&global.Object===Object&&global;cx.exports=Kue});var Oo=C((FPe,dx)=>{var Jue=tS(),Yue=typeof self=="object"&&self&&self.Object===Object&&self,Que=Jue||Yue||Function("return this")();dx.exports=Que});var Hp=C((UPe,fx)=>{var Xue=Oo(),Zue=Xue.Symbol;fx.exports=Zue});var gx=C((qPe,hx)=>{var px=Hp(),mx=Object.prototype,ele=mx.hasOwnProperty,tle=mx.toString,Kp=px?px.toStringTag:void 0;function nle(e){var t=ele.call(e,Kp),n=e[Kp];try{e[Kp]=void 0;var r=!0}catch{}var i=tle.call(e);return r&&(t?e[Kp]=n:delete e[Kp]),i}hx.exports=nle});var bx=C((BPe,yx)=>{var rle=Object.prototype,ile=rle.toString;function ole(e){return ile.call(e)}yx.exports=ole});var Sl=C((VPe,Ex)=>{var vx=Hp(),ale=gx(),sle=bx(),ule="[object Null]",lle="[object Undefined]",wx=vx?vx.toStringTag:void 0;function cle(e){return e==null?e===void 0?lle:ule:wx&&wx in Object(e)?ale(e):sle(e)}Ex.exports=cle});var ds=C((GPe,Ax)=>{function dle(e){var t=typeof e;return e!=null&&(t=="object"||t=="function")}Ax.exports=dle});var z0=C((jPe,Cx)=>{var fle=Sl(),ple=ds(),mle="[object AsyncFunction]",hle="[object Function]",gle="[object GeneratorFunction]",yle="[object Proxy]";function ble(e){if(!ple(e))return!1;var t=fle(e);return t==hle||t==gle||t==mle||t==yle}Cx.exports=ble});var Nx=C((WPe,Sx)=>{var vle=Oo(),wle=vle["__core-js_shared__"];Sx.exports=wle});var Tx=C((zPe,Ix)=>{var nS=Nx(),_x=(function(){var e=/[^.]+$/.exec(nS&&nS.keys&&nS.keys.IE_PROTO||"");return e?"Symbol(src)_1."+e:""})();function Ele(e){return!!_x&&_x in e}Ix.exports=Ele});var rS=C((HPe,Ox)=>{var Ale=Function.prototype,Cle=Ale.toString;function Sle(e){if(e!=null){try{return Cle.call(e)}catch{}try{return e+""}catch{}}return""}Ox.exports=Sle});var Px=C((KPe,Dx)=>{var Nle=z0(),_le=Tx(),Ile=ds(),Tle=rS(),Ole=/[\\^$.*+?()[\]{}|]/g,Dle=/^\[object .+?Constructor\]$/,Ple=Function.prototype,Rle=Object.prototype,kle=Ple.toString,$le=Rle.hasOwnProperty,Lle=RegExp("^"+kle.call($le).replace(Ole,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function Mle(e){if(!Ile(e)||_le(e))return!1;var t=Nle(e)?Lle:Dle;return t.test(Tle(e))}Dx.exports=Mle});var kx=C((JPe,Rx)=>{function xle(e,t){return e?.[t]}Rx.exports=xle});var cu=C((YPe,$x)=>{var Fle=Px(),Ule=kx();function qle(e,t){var n=Ule(e,t);return Fle(n)?n:void 0}$x.exports=qle});var H0=C((QPe,Lx)=>{var Ble=cu(),Vle=Oo(),Gle=Ble(Vle,"Map");Lx.exports=Gle});var Jp=C((XPe,Mx)=>{var jle=cu(),Wle=jle(Object,"create");Mx.exports=Wle});var Ux=C((ZPe,Fx)=>{var xx=Jp();function zle(){this.__data__=xx?xx(null):{},this.size=0}Fx.exports=zle});var Bx=C((eRe,qx)=>{function Hle(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t}qx.exports=Hle});var Gx=C((tRe,Vx)=>{var Kle=Jp(),Jle="__lodash_hash_undefined__",Yle=Object.prototype,Qle=Yle.hasOwnProperty;function Xle(e){var t=this.__data__;if(Kle){var n=t[e];return n===Jle?void 0:n}return Qle.call(t,e)?t[e]:void 0}Vx.exports=Xle});var Wx=C((nRe,jx)=>{var Zle=Jp(),ece=Object.prototype,tce=ece.hasOwnProperty;function nce(e){var t=this.__data__;return Zle?t[e]!==void 0:tce.call(t,e)}jx.exports=nce});var Hx=C((rRe,zx)=>{var rce=Jp(),ice="__lodash_hash_undefined__";function oce(e,t){var n=this.__data__;return this.size+=this.has(e)?0:1,n[e]=rce&&t===void 0?ice:t,this}zx.exports=oce});var Jx=C((iRe,Kx)=>{var ace=Ux(),sce=Bx(),uce=Gx(),lce=Wx(),cce=Hx();function ud(e){var t=-1,n=e==null?0:e.length;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}ud.prototype.clear=ace;ud.prototype.delete=sce;ud.prototype.get=uce;ud.prototype.has=lce;ud.prototype.set=cce;Kx.exports=ud});var Xx=C((oRe,Qx)=>{var Yx=Jx(),dce=zp(),fce=H0();function pce(){this.size=0,this.__data__={hash:new Yx,map:new(fce||dce),string:new Yx}}Qx.exports=pce});var eF=C((aRe,Zx)=>{function mce(e){var t=typeof e;return t=="string"||t=="number"||t=="symbol"||t=="boolean"?e!=="__proto__":e===null}Zx.exports=mce});var Yp=C((sRe,tF)=>{var hce=eF();function gce(e,t){var n=e.__data__;return hce(t)?n[typeof t=="string"?"string":"hash"]:n.map}tF.exports=gce});var rF=C((uRe,nF)=>{var yce=Yp();function bce(e){var t=yce(this,e).delete(e);return this.size-=t?1:0,t}nF.exports=bce});var oF=C((lRe,iF)=>{var vce=Yp();function wce(e){return vce(this,e).get(e)}iF.exports=wce});var sF=C((cRe,aF)=>{var Ece=Yp();function Ace(e){return Ece(this,e).has(e)}aF.exports=Ace});var lF=C((dRe,uF)=>{var Cce=Yp();function Sce(e,t){var n=Cce(this,e),r=n.size;return n.set(e,t),this.size+=n.size==r?0:1,this}uF.exports=Sce});var K0=C((fRe,cF)=>{var Nce=Xx(),_ce=rF(),Ice=oF(),Tce=sF(),Oce=lF();function ld(e){var t=-1,n=e==null?0:e.length;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}ld.prototype.clear=Nce;ld.prototype.delete=_ce;ld.prototype.get=Ice;ld.prototype.has=Tce;ld.prototype.set=Oce;cF.exports=ld});var fF=C((pRe,dF)=>{var Dce=zp(),Pce=H0(),Rce=K0(),kce=200;function $ce(e,t){var n=this.__data__;if(n instanceof Dce){var r=n.__data__;if(!Pce||r.length<kce-1)return r.push([e,t]),this.size=++n.size,this;n=this.__data__=new Rce(r)}return n.set(e,t),this.size=n.size,this}dF.exports=$ce});var iS=C((mRe,pF)=>{var Lce=zp(),Mce=rx(),xce=ox(),Fce=sx(),Uce=lx(),qce=fF();function cd(e){var t=this.__data__=new Lce(e);this.size=t.size}cd.prototype.clear=Mce;cd.prototype.delete=xce;cd.prototype.get=Fce;cd.prototype.has=Uce;cd.prototype.set=qce;pF.exports=cd});var hF=C((hRe,mF)=>{var Bce="__lodash_hash_undefined__";function Vce(e){return this.__data__.set(e,Bce),this}mF.exports=Vce});var yF=C((gRe,gF)=>{function Gce(e){return this.__data__.has(e)}gF.exports=Gce});var vF=C((yRe,bF)=>{var jce=K0(),Wce=hF(),zce=yF();function J0(e){var t=-1,n=e==null?0:e.length;for(this.__data__=new jce;++t<n;)this.add(e[t])}J0.prototype.add=J0.prototype.push=Wce;J0.prototype.has=zce;bF.exports=J0});var EF=C((bRe,wF)=>{function Hce(e,t){for(var n=-1,r=e==null?0:e.length;++n<r;)if(t(e[n],n,e))return!0;return!1}wF.exports=Hce});var CF=C((vRe,AF)=>{function Kce(e,t){return e.has(t)}AF.exports=Kce});var oS=C((wRe,SF)=>{var Jce=vF(),Yce=EF(),Qce=CF(),Xce=1,Zce=2;function ede(e,t,n,r,i,o){var a=n&Xce,s=e.length,u=t.length;if(s!=u&&!(a&&u>s))return!1;var l=o.get(e),c=o.get(t);if(l&&c)return l==t&&c==e;var d=-1,f=!0,p=n&Zce?new Jce:void 0;for(o.set(e,t),o.set(t,e);++d<s;){var m=e[d],h=t[d];if(r)var g=a?r(h,m,d,t,e,o):r(m,h,d,e,t,o);if(g!==void 0){if(g)continue;f=!1;break}if(p){if(!Yce(t,function(y,b){if(!Qce(p,b)&&(m===y||i(m,y,n,r,o)))return p.push(b)})){f=!1;break}}else if(!(m===h||i(m,h,n,r,o))){f=!1;break}}return o.delete(e),o.delete(t),f}SF.exports=ede});var aS=C((ERe,NF)=>{var tde=Oo(),nde=tde.Uint8Array;NF.exports=nde});var IF=C((ARe,_F)=>{function rde(e){var t=-1,n=Array(e.size);return e.forEach(function(r,i){n[++t]=[i,r]}),n}_F.exports=rde});var OF=C((CRe,TF)=>{function ide(e){var t=-1,n=Array(e.size);return e.forEach(function(r){n[++t]=r}),n}TF.exports=ide});var $F=C((SRe,kF)=>{var DF=Hp(),PF=aS(),ode=ad(),ade=oS(),sde=IF(),ude=OF(),lde=1,cde=2,dde="[object Boolean]",fde="[object Date]",pde="[object Error]",mde="[object Map]",hde="[object Number]",gde="[object RegExp]",yde="[object Set]",bde="[object String]",vde="[object Symbol]",wde="[object ArrayBuffer]",Ede="[object DataView]",RF=DF?DF.prototype:void 0,sS=RF?RF.valueOf:void 0;function Ade(e,t,n,r,i,o,a){switch(n){case Ede:if(e.byteLength!=t.byteLength||e.byteOffset!=t.byteOffset)return!1;e=e.buffer,t=t.buffer;case wde:return!(e.byteLength!=t.byteLength||!o(new PF(e),new PF(t)));case dde:case fde:case hde:return ode(+e,+t);case pde:return e.name==t.name&&e.message==t.message;case gde:case bde:return e==t+"";case mde:var s=sde;case yde:var u=r&lde;if(s||(s=ude),e.size!=t.size&&!u)return!1;var l=a.get(e);if(l)return l==t;r|=cde,a.set(e,t);var c=ade(s(e),s(t),r,i,o,a);return a.delete(e),c;case vde:if(sS)return sS.call(e)==sS.call(t)}return!1}kF.exports=Ade});var MF=C((NRe,LF)=>{function Cde(e,t){for(var n=-1,r=t.length,i=e.length;++n<r;)e[i+n]=t[n];return e}LF.exports=Cde});var du=C((_Re,xF)=>{var Sde=Array.isArray;xF.exports=Sde});var UF=C((IRe,FF)=>{var Nde=MF(),_de=du();function Ide(e,t,n){var r=t(e);return _de(e)?r:Nde(r,n(e))}FF.exports=Ide});var BF=C((TRe,qF)=>{function Tde(e,t){for(var n=-1,r=e==null?0:e.length,i=0,o=[];++n<r;){var a=e[n];t(a,n,e)&&(o[i++]=a)}return o}qF.exports=Tde});var GF=C((ORe,VF)=>{function Ode(){return[]}VF.exports=Ode});var zF=C((DRe,WF)=>{var Dde=BF(),Pde=GF(),Rde=Object.prototype,kde=Rde.propertyIsEnumerable,jF=Object.getOwnPropertySymbols,$de=jF?function(e){return e==null?[]:(e=Object(e),Dde(jF(e),function(t){return kde.call(e,t)}))}:Pde;WF.exports=$de});var KF=C((PRe,HF)=>{function Lde(e,t){for(var n=-1,r=Array(e);++n<e;)r[n]=t(n);return r}HF.exports=Lde});var fu=C((RRe,JF)=>{function Mde(e){return e!=null&&typeof e=="object"}JF.exports=Mde});var QF=C((kRe,YF)=>{var xde=Sl(),Fde=fu(),Ude="[object Arguments]";function qde(e){return Fde(e)&&xde(e)==Ude}YF.exports=qde});var uS=C(($Re,eU)=>{var XF=QF(),Bde=fu(),ZF=Object.prototype,Vde=ZF.hasOwnProperty,Gde=ZF.propertyIsEnumerable,jde=XF((function(){return arguments})())?XF:function(e){return Bde(e)&&Vde.call(e,"callee")&&!Gde.call(e,"callee")};eU.exports=jde});var nU=C((LRe,tU)=>{function Wde(){return!1}tU.exports=Wde});var Y0=C((Qp,dd)=>{var zde=Oo(),Hde=nU(),oU=typeof Qp=="object"&&Qp&&!Qp.nodeType&&Qp,rU=oU&&typeof dd=="object"&&dd&&!dd.nodeType&&dd,Kde=rU&&rU.exports===oU,iU=Kde?zde.Buffer:void 0,Jde=iU?iU.isBuffer:void 0,Yde=Jde||Hde;dd.exports=Yde});var Q0=C((MRe,aU)=>{var Qde=9007199254740991,Xde=/^(?:0|[1-9]\d*)$/;function Zde(e,t){var n=typeof e;return t=t??Qde,!!t&&(n=="number"||n!="symbol"&&Xde.test(e))&&e>-1&&e%1==0&&e<t}aU.exports=Zde});var lS=C((xRe,sU)=>{var efe=9007199254740991;function tfe(e){return typeof e=="number"&&e>-1&&e%1==0&&e<=efe}sU.exports=tfe});var lU=C((FRe,uU)=>{var nfe=Sl(),rfe=lS(),ife=fu(),ofe="[object Arguments]",afe="[object Array]",sfe="[object Boolean]",ufe="[object Date]",lfe="[object Error]",cfe="[object Function]",dfe="[object Map]",ffe="[object Number]",pfe="[object Object]",mfe="[object RegExp]",hfe="[object Set]",gfe="[object String]",yfe="[object WeakMap]",bfe="[object ArrayBuffer]",vfe="[object DataView]",wfe="[object Float32Array]",Efe="[object Float64Array]",Afe="[object Int8Array]",Cfe="[object Int16Array]",Sfe="[object Int32Array]",Nfe="[object Uint8Array]",_fe="[object Uint8ClampedArray]",Ife="[object Uint16Array]",Tfe="[object Uint32Array]",It={};It[wfe]=It[Efe]=It[Afe]=It[Cfe]=It[Sfe]=It[Nfe]=It[_fe]=It[Ife]=It[Tfe]=!0;It[ofe]=It[afe]=It[bfe]=It[sfe]=It[vfe]=It[ufe]=It[lfe]=It[cfe]=It[dfe]=It[ffe]=It[pfe]=It[mfe]=It[hfe]=It[gfe]=It[yfe]=!1;function Ofe(e){return ife(e)&&rfe(e.length)&&!!It[nfe(e)]}uU.exports=Ofe});var dU=C((URe,cU)=>{function Dfe(e){return function(t){return e(t)}}cU.exports=Dfe});var pU=C((Xp,fd)=>{var Pfe=tS(),fU=typeof Xp=="object"&&Xp&&!Xp.nodeType&&Xp,Zp=fU&&typeof fd=="object"&&fd&&!fd.nodeType&&fd,Rfe=Zp&&Zp.exports===fU,cS=Rfe&&Pfe.process,kfe=(function(){try{var e=Zp&&Zp.require&&Zp.require("util").types;return e||cS&&cS.binding&&cS.binding("util")}catch{}})();fd.exports=kfe});var X0=C((qRe,gU)=>{var $fe=lU(),Lfe=dU(),mU=pU(),hU=mU&&mU.isTypedArray,Mfe=hU?Lfe(hU):$fe;gU.exports=Mfe});var dS=C((BRe,yU)=>{var xfe=KF(),Ffe=uS(),Ufe=du(),qfe=Y0(),Bfe=Q0(),Vfe=X0(),Gfe=Object.prototype,jfe=Gfe.hasOwnProperty;function Wfe(e,t){var n=Ufe(e),r=!n&&Ffe(e),i=!n&&!r&&qfe(e),o=!n&&!r&&!i&&Vfe(e),a=n||r||i||o,s=a?xfe(e.length,String):[],u=s.length;for(var l in e)(t||jfe.call(e,l))&&!(a&&(l=="length"||i&&(l=="offset"||l=="parent")||o&&(l=="buffer"||l=="byteLength"||l=="byteOffset")||Bfe(l,u)))&&s.push(l);return s}yU.exports=Wfe});var Z0=C((VRe,bU)=>{var zfe=Object.prototype;function Hfe(e){var t=e&&e.constructor,n=typeof t=="function"&&t.prototype||zfe;return e===n}bU.exports=Hfe});var fS=C((GRe,vU)=>{function Kfe(e,t){return function(n){return e(t(n))}}vU.exports=Kfe});var EU=C((jRe,wU)=>{var Jfe=fS(),Yfe=Jfe(Object.keys,Object);wU.exports=Yfe});var CU=C((WRe,AU)=>{var Qfe=Z0(),Xfe=EU(),Zfe=Object.prototype,epe=Zfe.hasOwnProperty;function tpe(e){if(!Qfe(e))return Xfe(e);var t=[];for(var n in Object(e))epe.call(e,n)&&n!="constructor"&&t.push(n);return t}AU.exports=tpe});var em=C((zRe,SU)=>{var npe=z0(),rpe=lS();function ipe(e){return e!=null&&rpe(e.length)&&!npe(e)}SU.exports=ipe});var _U=C((HRe,NU)=>{var ope=dS(),ape=CU(),spe=em();function upe(e){return spe(e)?ope(e):ape(e)}NU.exports=upe});var TU=C((KRe,IU)=>{var lpe=UF(),cpe=zF(),dpe=_U();function fpe(e){return lpe(e,dpe,cpe)}IU.exports=fpe});var PU=C((JRe,DU)=>{var OU=TU(),ppe=1,mpe=Object.prototype,hpe=mpe.hasOwnProperty;function gpe(e,t,n,r,i,o){var a=n&ppe,s=OU(e),u=s.length,l=OU(t),c=l.length;if(u!=c&&!a)return!1;for(var d=u;d--;){var f=s[d];if(!(a?f in t:hpe.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<u;){f=s[d];var y=e[f],b=t[f];if(r)var E=a?r(b,y,f,t,e,o):r(y,b,f,e,t,o);if(!(E===void 0?y===b||i(y,b,n,r,o):E)){h=!1;break}g||(g=f=="constructor")}if(h&&!g){var w=e.constructor,_=t.constructor;w!=_&&"constructor"in e&&"constructor"in t&&!(typeof w=="function"&&w instanceof w&&typeof _=="function"&&_ instanceof _)&&(h=!1)}return o.delete(e),o.delete(t),h}DU.exports=gpe});var kU=C((YRe,RU)=>{var ype=cu(),bpe=Oo(),vpe=ype(bpe,"DataView");RU.exports=vpe});var LU=C((QRe,$U)=>{var wpe=cu(),Epe=Oo(),Ape=wpe(Epe,"Promise");$U.exports=Ape});var xU=C((XRe,MU)=>{var Cpe=cu(),Spe=Oo(),Npe=Cpe(Spe,"Set");MU.exports=Npe});var UU=C((ZRe,FU)=>{var _pe=cu(),Ipe=Oo(),Tpe=_pe(Ipe,"WeakMap");FU.exports=Tpe});var HU=C((eke,zU)=>{var pS=kU(),mS=H0(),hS=LU(),gS=xU(),yS=UU(),WU=Sl(),pd=rS(),qU="[object Map]",Ope="[object Object]",BU="[object Promise]",VU="[object Set]",GU="[object WeakMap]",jU="[object DataView]",Dpe=pd(pS),Ppe=pd(mS),Rpe=pd(hS),kpe=pd(gS),$pe=pd(yS),Nl=WU;(pS&&Nl(new pS(new ArrayBuffer(1)))!=jU||mS&&Nl(new mS)!=qU||hS&&Nl(hS.resolve())!=BU||gS&&Nl(new gS)!=VU||yS&&Nl(new yS)!=GU)&&(Nl=function(e){var t=WU(e),n=t==Ope?e.constructor:void 0,r=n?pd(n):"";if(r)switch(r){case Dpe:return jU;case Ppe:return qU;case Rpe:return BU;case kpe:return VU;case $pe:return GU}return t});zU.exports=Nl});var tq=C((tke,eq)=>{var bS=iS(),Lpe=oS(),Mpe=$F(),xpe=PU(),KU=HU(),JU=du(),YU=Y0(),Fpe=X0(),Upe=1,QU="[object Arguments]",XU="[object Array]",ey="[object Object]",qpe=Object.prototype,ZU=qpe.hasOwnProperty;function Bpe(e,t,n,r,i,o){var a=JU(e),s=JU(t),u=a?XU:KU(e),l=s?XU:KU(t);u=u==QU?ey:u,l=l==QU?ey:l;var c=u==ey,d=l==ey,f=u==l;if(f&&YU(e)){if(!YU(t))return!1;a=!0,c=!1}if(f&&!c)return o||(o=new bS),a||Fpe(e)?Lpe(e,t,n,r,i,o):Mpe(e,t,u,n,r,i,o);if(!(n&Upe)){var p=c&&ZU.call(e,"__wrapped__"),m=d&&ZU.call(t,"__wrapped__");if(p||m){var h=p?e.value():e,g=m?t.value():t;return o||(o=new bS),i(h,g,n,r,o)}}return f?(o||(o=new bS),xpe(e,t,n,r,i,o)):!1}eq.exports=Bpe});var oq=C((nke,iq)=>{var Vpe=tq(),nq=fu();function rq(e,t,n,r,i){return e===t?!0:e==null||t==null||!nq(e)&&!nq(t)?e!==e&&t!==t:Vpe(e,t,n,r,rq,i)}iq.exports=rq});var sq=C((rke,aq)=>{var Gpe=oq();function jpe(e,t){return Gpe(e,t)}aq.exports=jpe});var vS=C((ike,uq)=>{var Wpe=cu(),zpe=(function(){try{var e=Wpe(Object,"defineProperty");return e({},"",{}),e}catch{}})();uq.exports=zpe});var ty=C((oke,cq)=>{var lq=vS();function Hpe(e,t,n){t=="__proto__"&&lq?lq(e,t,{configurable:!0,enumerable:!0,value:n,writable:!0}):e[t]=n}cq.exports=Hpe});var wS=C((ake,dq)=>{var Kpe=ty(),Jpe=ad();function Ype(e,t,n){(n!==void 0&&!Jpe(e[t],n)||n===void 0&&!(t in e))&&Kpe(e,t,n)}dq.exports=Ype});var pq=C((ske,fq)=>{function Qpe(e){return function(t,n,r){for(var i=-1,o=Object(t),a=r(t),s=a.length;s--;){var u=a[e?s:++i];if(n(o[u],u,o)===!1)break}return t}}fq.exports=Qpe});var hq=C((uke,mq)=>{var Xpe=pq(),Zpe=Xpe();mq.exports=Zpe});var wq=C((tm,md)=>{var eme=Oo(),vq=typeof tm=="object"&&tm&&!tm.nodeType&&tm,gq=vq&&typeof md=="object"&&md&&!md.nodeType&&md,tme=gq&&gq.exports===vq,yq=tme?eme.Buffer:void 0,bq=yq?yq.allocUnsafe:void 0;function nme(e,t){if(t)return e.slice();var n=e.length,r=bq?bq(n):new e.constructor(n);return e.copy(r),r}md.exports=nme});var Cq=C((lke,Aq)=>{var Eq=aS();function rme(e){var t=new e.constructor(e.byteLength);return new Eq(t).set(new Eq(e)),t}Aq.exports=rme});var Nq=C((cke,Sq)=>{var ime=Cq();function ome(e,t){var n=t?ime(e.buffer):e.buffer;return new e.constructor(n,e.byteOffset,e.length)}Sq.exports=ome});var Iq=C((dke,_q)=>{function ame(e,t){var n=-1,r=e.length;for(t||(t=Array(r));++n<r;)t[n]=e[n];return t}_q.exports=ame});var Dq=C((fke,Oq)=>{var sme=ds(),Tq=Object.create,ume=(function(){function e(){}return function(t){if(!sme(t))return{};if(Tq)return Tq(t);e.prototype=t;var n=new e;return e.prototype=void 0,n}})();Oq.exports=ume});var ES=C((pke,Pq)=>{var lme=fS(),cme=lme(Object.getPrototypeOf,Object);Pq.exports=cme});var kq=C((mke,Rq)=>{var dme=Dq(),fme=ES(),pme=Z0();function mme(e){return typeof e.constructor=="function"&&!pme(e)?dme(fme(e)):{}}Rq.exports=mme});var Lq=C((hke,$q)=>{var hme=em(),gme=fu();function yme(e){return gme(e)&&hme(e)}$q.exports=yme});var Fq=C((gke,xq)=>{var bme=Sl(),vme=ES(),wme=fu(),Eme="[object Object]",Ame=Function.prototype,Cme=Object.prototype,Mq=Ame.toString,Sme=Cme.hasOwnProperty,Nme=Mq.call(Object);function _me(e){if(!wme(e)||bme(e)!=Eme)return!1;var t=vme(e);if(t===null)return!0;var n=Sme.call(t,"constructor")&&t.constructor;return typeof n=="function"&&n instanceof n&&Mq.call(n)==Nme}xq.exports=_me});var AS=C((yke,Uq)=>{function Ime(e,t){if(!(t==="constructor"&&typeof e[t]=="function")&&t!="__proto__")return e[t]}Uq.exports=Ime});var CS=C((bke,qq)=>{var Tme=ty(),Ome=ad(),Dme=Object.prototype,Pme=Dme.hasOwnProperty;function Rme(e,t,n){var r=e[t];(!(Pme.call(e,t)&&Ome(r,n))||n===void 0&&!(t in e))&&Tme(e,t,n)}qq.exports=Rme});var Vq=C((vke,Bq)=>{var kme=CS(),$me=ty();function Lme(e,t,n,r){var i=!n;n||(n={});for(var o=-1,a=t.length;++o<a;){var s=t[o],u=r?r(n[s],e[s],s,n,e):void 0;u===void 0&&(u=e[s]),i?$me(n,s,u):kme(n,s,u)}return n}Bq.exports=Lme});var jq=C((wke,Gq)=>{function Mme(e){var t=[];if(e!=null)for(var n in Object(e))t.push(n);return t}Gq.exports=Mme});var zq=C((Eke,Wq)=>{var xme=ds(),Fme=Z0(),Ume=jq(),qme=Object.prototype,Bme=qme.hasOwnProperty;function Vme(e){if(!xme(e))return Ume(e);var t=Fme(e),n=[];for(var r in e)r=="constructor"&&(t||!Bme.call(e,r))||n.push(r);return n}Wq.exports=Vme});var SS=C((Ake,Hq)=>{var Gme=dS(),jme=zq(),Wme=em();function zme(e){return Wme(e)?Gme(e,!0):jme(e)}Hq.exports=zme});var Jq=C((Cke,Kq)=>{var Hme=Vq(),Kme=SS();function Jme(e){return Hme(e,Kme(e))}Kq.exports=Jme});var tB=C((Ske,eB)=>{var Yq=wS(),Yme=wq(),Qme=Nq(),Xme=Iq(),Zme=kq(),Qq=uS(),Xq=du(),ehe=Lq(),the=Y0(),nhe=z0(),rhe=ds(),ihe=Fq(),ohe=X0(),Zq=AS(),ahe=Jq();function she(e,t,n,r,i,o,a){var s=Zq(e,n),u=Zq(t,n),l=a.get(u);if(l){Yq(e,n,l);return}var c=o?o(s,u,n+"",e,t,a):void 0,d=c===void 0;if(d){var f=Xq(u),p=!f&&the(u),m=!f&&!p&&ohe(u);c=u,f||p||m?Xq(s)?c=s:ehe(s)?c=Xme(s):p?(d=!1,c=Yme(u,!0)):m?(d=!1,c=Qme(u,!0)):c=[]:ihe(u)||Qq(u)?(c=s,Qq(s)?c=ahe(s):(!rhe(s)||nhe(s))&&(c=Zme(u))):d=!1}d&&(a.set(u,c),i(c,u,r,o,a),a.delete(u)),Yq(e,n,c)}eB.exports=she});var NS=C((Nke,rB)=>{var uhe=iS(),lhe=wS(),che=hq(),dhe=tB(),fhe=ds(),phe=SS(),mhe=AS();function nB(e,t,n,r,i){e!==t&&che(t,function(o,a){if(i||(i=new uhe),fhe(o))dhe(e,t,a,n,nB,r,i);else{var s=r?r(mhe(e,a),o,a+"",e,t,i):void 0;s===void 0&&(s=o),lhe(e,a,s)}},phe)}rB.exports=nB});var _S=C((_ke,iB)=>{function hhe(e){return e}iB.exports=hhe});var aB=C((Ike,oB)=>{function ghe(e,t,n){switch(n.length){case 0:return e.call(t);case 1:return e.call(t,n[0]);case 2:return e.call(t,n[0],n[1]);case 3:return e.call(t,n[0],n[1],n[2])}return e.apply(t,n)}oB.exports=ghe});var lB=C((Tke,uB)=>{var yhe=aB(),sB=Math.max;function bhe(e,t,n){return t=sB(t===void 0?e.length-1:t,0),function(){for(var r=arguments,i=-1,o=sB(r.length-t,0),a=Array(o);++i<o;)a[i]=r[t+i];i=-1;for(var s=Array(t+1);++i<t;)s[i]=r[i];return s[t]=n(a),yhe(e,this,s)}}uB.exports=bhe});var dB=C((Oke,cB)=>{function vhe(e){return function(){return e}}cB.exports=vhe});var mB=C((Dke,pB)=>{var whe=dB(),fB=vS(),Ehe=_S(),Ahe=fB?function(e,t){return fB(e,"toString",{configurable:!0,enumerable:!1,value:whe(t),writable:!0})}:Ehe;pB.exports=Ahe});var gB=C((Pke,hB)=>{var Che=800,She=16,Nhe=Date.now;function _he(e){var t=0,n=0;return function(){var r=Nhe(),i=She-(r-n);if(n=r,i>0){if(++t>=Che)return arguments[0]}else t=0;return e.apply(void 0,arguments)}}hB.exports=_he});var bB=C((Rke,yB)=>{var Ihe=mB(),The=gB(),Ohe=The(Ihe);yB.exports=Ohe});var wB=C((kke,vB)=>{var Dhe=_S(),Phe=lB(),Rhe=bB();function khe(e,t){return Rhe(Phe(e,t,Dhe),e+"")}vB.exports=khe});var AB=C(($ke,EB)=>{var $he=ad(),Lhe=em(),Mhe=Q0(),xhe=ds();function Fhe(e,t,n){if(!xhe(n))return!1;var r=typeof t;return(r=="number"?Lhe(n)&&Mhe(t,n.length):r=="string"&&t in n)?$he(n[t],e):!1}EB.exports=Fhe});var IS=C((Lke,CB)=>{var Uhe=wB(),qhe=AB();function Bhe(e){return Uhe(function(t,n){var r=-1,i=n.length,o=i>1?n[i-1]:void 0,a=i>2?n[2]:void 0;for(o=e.length>3&&typeof o=="function"?(i--,o):void 0,a&&qhe(n[0],n[1],a)&&(o=i<3?void 0:o,i=1),t=Object(t);++r<i;){var s=n[r];s&&e(t,s,r,o)}return t})}CB.exports=Bhe});var NB=C((Mke,SB)=>{var Vhe=NS(),Ghe=IS(),jhe=Ghe(function(e,t,n,r){Vhe(e,t,n,r)});SB.exports=jhe});var eo,nm=B(()=>{"use strict";(function(e){e[e.NotLoaded=0]="NotLoaded",e[e.Initialized=1]="Initialized",e[e.ConfigsLoaded=2]="ConfigsLoaded",e[e.Error=3]="Error"})(eo||(eo={}))});function IB(e,t,n="PROD"){let r=i=>`ShellSettings_ECS_ClientCache_${e}_${_B.EcsConfigType[i]}_${n}`;return{getData:i=>{let o=t.getItem(r(i));return Promise.resolve(o?JSON.parse(o):void 0)},putData:(i,o)=>(t.setItem(r(i),JSON.stringify(o)),Promise.resolve())}}var _B,Whe,TB=B(()=>{"use strict";_B=Xe(eS()),Whe=Xe(ZC());});var TS,OB=B(()=>{"use strict";F0();TS=Fp({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 PB,RB,kB,$B,OS,zhe,ny,DB,DS=B(()=>{"use strict";PB=Xe(ZC()),RB=Xe(q1()),kB=Xe(eS()),$B=Xe(sq()),OS=Xe(NB());nm();TB();OB();zhe=60*1e3,ny=class{clientName;logger;ecsEndpoint;resolveLoadingPromise;loadingPromise=new Promise(t=>this.resolveLoadingPromise=t);_status=eo.NotLoaded;endpointType;clientConfigOverride;get status(){return this._status}constructor(t,n,r="PROD"){this.clientName=t,this.logger=n,this.endpointType=r,this.ecsEndpoint=r==="PROD"?TS.prodEcsEndpoint:TS.integrationEcsEndpoint}client=new RB.default;init=async({clientVersion:t,getFilters:n,cacheStorage:r=PB.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 n();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:[kB.EcsConfigType.Default],hosts:[this.ecsEndpoint],initialAppActiveState:!0,getEcsParameters:a,databaseInterface:IB(this.clientName,r,this.endpointType),...o}),this.client.requestUpdate(),this._status===eo.NotLoaded&&(this._status=eo.Initialized)}catch(s){this._status=eo.Error,this.resolveLoadingPromise(),this.logEvent("FeaturesClient/initializationFailed",{ecsClientName:this.clientName,error:s},"Error")}i&&window.setInterval(()=>this.client.requestUpdate(),i*zhe)};getConfig=t=>{let n=this.getMergedClientConfigByTeamName(t.teamName),r=n?t.extractConfig(n):{};return(0,OS.default)({},t.fallback,r,t.override,DB)};getAllConfigs=()=>this.getMergedClientConfig();getAllConfigsByTeamName=t=>this.getMergedClientConfigByTeamName(t);requestConfigUpdate=()=>{this.client.requestUpdate()};subscribe=(t,n)=>{let r=this.getConfig(t),i=this.client.configUpdated.subscribe(()=>{let o=this.getConfig(t);(0,$B.default)(o,r)||(r={...o},n(o))});return{unsubscribe:()=>i.unsubscribe()}};waitUntilLoaded=async t=>{if(t!==void 0){let n,r=new Promise((i,o)=>{n=window.setTimeout(()=>{o(new Error("Timed out waiting for configuration to load"))},t)});await Promise.race([this.loadingPromise,r]),clearTimeout(n)}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,OS.default)({},this.client.getConfig()?.config,this.clientConfigOverride,DB);getMergedClientConfigByTeamName=t=>this.getMergedClientConfig()?.[t];handleConfigUpdated=()=>{let t=this.client.getConfig();if(t===void 0)return;this.resolveLoadingPromise(),this._status=eo.ConfigsLoaded;let{ConfigIDs:n,Headers:r}=t.config;this.logEvent("FeaturesClient/configUpdated",{ecsClientName:this.clientName,configIDs:n,ETag:r?.ETag})};logEvent=(t,n)=>{this.logger.logEvent(t,{ecsClientName:this.clientName,ecsEndpointType:this.endpointType,...n})}},DB=(e,t)=>{if(Array.isArray(t))return t}});var MB=C((Wke,LB)=>{"use strict";var Hhe=()=>{let e={};return e.promise=new Promise((t,n)=>{e.resolve=t,e.reject=n}),e};LB.exports=Hhe});var PS=C((zke,FB)=>{var rm=new Proxy(function(){return rm},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:rm},apply:function(){return rm},construct:function(){return{}}}),xB=function(){return rm};Object.setPrototypeOf(xB,rm);FB.exports=xB});var BB=C((Hke,qB)=>{var im=new Proxy(function(){return im},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:im},apply:function(){return im},construct:function(){return{}}}),UB=function(){return im};Object.setPrototypeOf(UB,im);qB.exports=UB});var KB=C((Kke,HB)=>{"use strict";var RS=BB(),Khe={childContextTypes:!0,contextType:!0,contextTypes:!0,defaultProps:!0,displayName:!0,getDefaultProps:!0,getDerivedStateFromError:!0,getDerivedStateFromProps:!0,mixins:!0,propTypes:!0,type:!0},Jhe={name:!0,length:!0,prototype:!0,caller:!0,callee:!0,arguments:!0,arity:!0},Yhe={$$typeof:!0,render:!0,defaultProps:!0,displayName:!0,propTypes:!0},WB={$$typeof:!0,compare:!0,defaultProps:!0,displayName:!0,propTypes:!0,type:!0},kS={};kS[RS.ForwardRef]=Yhe;kS[RS.Memo]=WB;function VB(e){return RS.isMemo(e)?WB:kS[e.$$typeof]||Khe}var Qhe=Object.defineProperty,Xhe=Object.getOwnPropertyNames,GB=Object.getOwnPropertySymbols,Zhe=Object.getOwnPropertyDescriptor,ege=Object.getPrototypeOf,jB=Object.prototype;function zB(e,t,n){if(typeof t!="string"){if(jB){var r=ege(t);r&&r!==jB&&zB(e,r,n)}var i=Xhe(t);GB&&(i=i.concat(GB(t)));for(var o=VB(e),a=VB(t),s=0;s<i.length;++s){var u=i[s];if(!Jhe[u]&&!(n&&n[u])&&!(a&&a[u])&&!(o&&o[u])){var l=Zhe(t,u);try{Qhe(e,u,l)}catch{}}}}return e}HB.exports=zB});function YB(e,t,n){let[r,i]=(0,hd.useState)(e.getConfig(t));return(0,hd.useEffect)(()=>{if(!n?.subscribe&&e.status===eo.ConfigsLoaded)return;let o=e.subscribe(t,a=>{i(a),n?.subscribe||o.unsubscribe()});return o?.unsubscribe},[]),r}function QB(e){return function(t,n){return YB(e,t,n)}}function XB(e,t,n,r){let i=o=>{let a=YB(e,t,r),s={...o,...a};return hd.default.createElement(n,{...s})};return(0,JB.default)(i,n),i.displayName=`WithFeature(${n.name})`,i}function ZB(e,t,n,r){return t.reduce((i,o)=>XB(e,o,i,r),n)}function eV(e){return function(t,n,r){return XB(e,t,n,r)}}var JB,hd,$S=B(()=>{"use strict";JB=Xe(KB()),hd=Xe(PS());nm();});var nV=C((Qke,tV)=>{var tge=NS(),nge=IS(),rge=nge(function(e,t,n){tge(e,t,n)});tV.exports=rge});var ry=C((Xke,rV)=>{var ige=Sl(),oge=fu(),age="[object Symbol]";function sge(e){return typeof e=="symbol"||oge(e)&&ige(e)==age}rV.exports=sge});var oV=C((Zke,iV)=>{var uge=du(),lge=ry(),cge=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,dge=/^\w*$/;function fge(e,t){if(uge(e))return!1;var n=typeof e;return n=="number"||n=="symbol"||n=="boolean"||e==null||lge(e)?!0:dge.test(e)||!cge.test(e)||t!=null&&e in Object(t)}iV.exports=fge});var uV=C((e$e,sV)=>{var aV=K0(),pge="Expected a function";function LS(e,t){if(typeof e!="function"||t!=null&&typeof t!="function")throw new TypeError(pge);var n=function(){var r=arguments,i=t?t.apply(this,r):r[0],o=n.cache;if(o.has(i))return o.get(i);var a=e.apply(this,r);return n.cache=o.set(i,a)||o,a};return n.cache=new(LS.Cache||aV),n}LS.Cache=aV;sV.exports=LS});var cV=C((t$e,lV)=>{var mge=uV(),hge=500;function gge(e){var t=mge(e,function(r){return n.size===hge&&n.clear(),r}),n=t.cache;return t}lV.exports=gge});var fV=C((n$e,dV)=>{var yge=cV(),bge=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,vge=/\\(\\)?/g,wge=yge(function(e){var t=[];return e.charCodeAt(0)===46&&t.push(""),e.replace(bge,function(n,r,i,o){t.push(i?o.replace(vge,"$1"):r||n)}),t});dV.exports=wge});var mV=C((r$e,pV)=>{function Ege(e,t){for(var n=-1,r=e==null?0:e.length,i=Array(r);++n<r;)i[n]=t(e[n],n,e);return i}pV.exports=Ege});var wV=C((i$e,vV)=>{var hV=Hp(),Age=mV(),Cge=du(),Sge=ry(),Nge=1/0,gV=hV?hV.prototype:void 0,yV=gV?gV.toString:void 0;function bV(e){if(typeof e=="string")return e;if(Cge(e))return Age(e,bV)+"";if(Sge(e))return yV?yV.call(e):"";var t=e+"";return t=="0"&&1/e==-Nge?"-0":t}vV.exports=bV});var AV=C((o$e,EV)=>{var _ge=wV();function Ige(e){return e==null?"":_ge(e)}EV.exports=Ige});var SV=C((a$e,CV)=>{var Tge=du(),Oge=oV(),Dge=fV(),Pge=AV();function Rge(e,t){return Tge(e)?e:Oge(e,t)?[e]:Dge(Pge(e))}CV.exports=Rge});var _V=C((s$e,NV)=>{var kge=ry(),$ge=1/0;function Lge(e){if(typeof e=="string"||kge(e))return e;var t=e+"";return t=="0"&&1/e==-$ge?"-0":t}NV.exports=Lge});var OV=C((u$e,TV)=>{var Mge=CS(),xge=SV(),Fge=Q0(),IV=ds(),Uge=_V();function qge(e,t,n,r){if(!IV(e))return e;t=xge(t,e);for(var i=-1,o=t.length,a=o-1,s=e;s!=null&&++i<o;){var u=Uge(t[i]),l=n;if(u==="__proto__"||u==="constructor"||u==="prototype")return e;if(i!=a){var c=s[u];l=r?r(c,u,s):void 0,l===void 0&&(l=IV(c)?c:Fge(t[i+1])?[]:{})}Mge(s,u,l),s=s[u]}return e}TV.exports=qge});var PV=C((l$e,DV)=>{var Bge=OV();function Vge(e,t,n){return e==null?e:Bge(e,t,n)}DV.exports=Vge});function LV(e){let{query:t}=(0,$V.default)(window.location.href,!0);return jge(e,t),e}function jge(e,t){let n=Gge+e.clientName,r=Object.keys(t).filter(o=>o.startsWith(n));if(!r)return;let i={};r.forEach(o=>{let a=t[o];if(a)try{let s=JSON.parse(a),u=n+MV,l={};if(o===n)l=s;else if(o.startsWith(u)){let c=o.substring(u.length);(0,kV.default)(l,c,s)}(0,RV.default)(i,l)}catch{}}),Object.keys(i).length>0&&e.overrideClientConfig(i)}var RV,kV,$V,MV,Gge,xV=B(()=>{"use strict";RV=Xe(nV()),kV=Xe(PV()),$V=Xe(BC());MV=".",Gge="ecs"+MV});function oy(e,t,n){let r=LV(new ny(e,t,n));function i(o){(0,iy.useEffect)(()=>{r.init(o)},[])}return{featuresClient:r,createFeature:zge(r),useFeaturesClientInitParams:i,withFeatures:(o,a,s)=>ZB(r,o,a,s)}}function zge(e){let t=QB(e),n=eV(e);return function(i){let o=L1(i);return o.getConfig=()=>e.getConfig(o),o.isLoaded=()=>e.status===eo.ConfigsLoaded,jC.register(o,e.clientName),{useFeature:a=>t(o,a),withFeature:(a,s)=>n(o,a,s),feature:o}}}var Wge,iy,MS=B(()=>{"use strict";Wge=Xe(MB()),iy=Xe(PS());XC();DS();nm();$S();xV();WC();});var FV=B(()=>{"use strict";XC();DS();MS();nm();$S();V0();zC();});function ay(e){return{logEvent:(t,n,r)=>{switch(r){case"Error":(0,gd.trackErrorTrace)(e,{eventName:t,eventData:n});break;case"Warning":(0,gd.trackWarningTrace)(e,{eventName:t,eventData:n});break;default:(0,gd.trackInfoTrace)(e,{eventName:t,eventData:n});break}}}}var gd,xS=B(()=>{"use strict";gd=Xe(vl());});var O$e,D$e,P$e,UV=B(()=>{"use strict";FV();xS();({featuresClient:O$e,createFeature:D$e,useFeaturesClientInitParams:P$e}=oy("PowerApps-Shell-Test",ay("shell-features")))});var VV=C((k$e,BV)=>{var om=new Proxy(function(){return om},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:om},apply:function(){return om},construct:function(){return{}}}),qV=function(){return om};Object.setPrototypeOf(qV,om);BV.exports=qV});var Hge,Kge,GV=B(()=>{"use strict";Lp();Hge=Xe(VV()),Kge=Xe(vl());});var jV=B(()=>{"use strict";UV();xS();GV();});var V$e,yd,G$e,WV=B(()=>{"use strict";jV();MS();({featuresClient:V$e,createFeature:yd,useFeaturesClientInitParams:G$e}=oy("PowerApps-MakerPortal",ay("powerapps-features")))});var zV,HV,H$e,K$e,J$e,Y$e,FS=B(()=>{"use strict";$1();WV();({feature:zV}=yd({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:od.enableAutoInsertionOfCellInRow}})),{feature:HV}=yd({teamName:"MakerPortal",owners:["aansu"],description:"Enable the one grid events for form designer",createdOn:"08/21/2024",fallback:{enableOneGridEventsForFormDesigner:od.enableOneGridEvents}}),{feature:H$e}=yd({teamName:"MakerPortal",owners:["adekulkarni"],description:"Disables PBI components and cleans them up from the form",createdOn:"01/03/2023",fallback:{enableFallbackFormTemplate:od.disablePBIComponents}}),{feature:K$e}=yd({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:od.enableAgentResponse}}),{feature:J$e,useFeature:Y$e}=yd({teamName:"MakerPortal",owners:["aansu"],description:"Enables delayed localization of custom control",createdOn:"06/08/2025",fallback:{enableDelayedLocalizationForCustomControls:od.enableDelayedLocalizationForCustomControls}})});var YV=C((X$e,JV)=>{var am=new Proxy(function(){return am},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:am},apply:function(){return am},construct:function(){return{}}}),KV=function(){return am};Object.setPrototypeOf(KV,am);JV.exports=KV});var Nr,pu=B(()=>{"use strict";Dn();En();Sr();Bp();Re();Jn();Nr=class extends Se{static HighestUsedIndexByClass=new Map;get colspan(){let t=this.getProperty(A.colspan);return F.IsNullOrUndefined(t)?null:parseInt(t,10)}set colspan(t){F.IsNullOrUndefined(t)||this.setProperty(A.colspan,String(t))}constructor(t,n){super(t,n)}get id(){let t=this.getProperty(A.id);return t==null?null:t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"?new H(t.substr(1,t.length-2)):new H(t)}set id(t){this.setProperty(A.id,`{${t.ToString()}}`)}set labelId(t){this.setProperty(A.labelId,`{${t.ToString()}}`)}get labelId(){let t=this.getProperty(A.labelId);return t&&t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"?new H(t.substr(1,t.length-2)):new H(t)}get Name(){return this.getProperty(A.Name)}set Name(t){this.setProperty(A.Name,t)}setDisplayName(t,n){for(let i of this.getAllLabels())if(+i.getProperty(A.languagecode)===n){i.setProperty(A.description,t);return}let r=new Se(D.formLabel,null);r.setProperty(A.description,t),r.setProperty(A.languagecode,String(n)),this.addGrandChild("labels",r)}getDisplayName(t){for(let n of this.getAllLabels())if(+n.getProperty(A.languagecode)===t)return n.getProperty(A.description)}getAllLabels(){let t=this.getChildren("labels");return t.length!==1?[]:t[0].getChildren("label")}get isLocked(){return+this.getProperty(A.locklevel)==1}set isLocked(t){!this.IsUnboundControl&&this.setProperty(A.locklevel,t?"1":"0")}get availableforphone(){return this.getProcessedValue(A.availableforphone)}set availableforphone(t){F.IsNullOrUndefined(t)||!this.IsAllowedUBCForAvailableOnPhone()||this.setProperty(A.availableforphone,String(t))}get visible(){return this.getProcessedValue(A.visible)}set visible(t){F.IsNullOrUndefined(t)||!this.IsAllowedUBCForVisibleByDefault()||this.setProperty(A.visible,String(t))}isLockLevelSettable(){return!this.IsUnboundControl}get showlabel(){return this.getProcessedValue(A.showlabel)}set showlabel(t){F.IsNullOrUndefined(t)||this.setProperty(A.showlabel,String(t))}isAvailableForPhoneSettable(){return this.IsAllowedUBCForAvailableOnPhone()}isVisibleSettable(){return this.IsAllowedUBCForVisibleByDefault()}getProcessedValue(t){let n=this.getProperty(t);return F.IsNullOrUndefined(n)||this.getProperty(t)==="true"}get readonly(){let t=this.getFirstChild(D.formControl);return t?t.disabled:!1}set readonly(t){let n=this.getFirstChild(D.formControl);n&&(n.disabled=t)}get allowfilteroff(){let t=this.getFirstChild(D.formControl);if(t)return t.getParam(A.AllowFilterOff)==="true"}set allowfilteroff(t){let n=this.getFirstChild(D.formControl);n&&!this.IsUnboundControl&&n.setParameter(A.AllowFilterOff,t)}get autoresolve(){let t=this.getFirstChild(D.formControl);if(t)return t.getParam(A.AutoResolve)==="true"}set autoresolve(t){let n=this.getFirstChild(D.formControl);n&&!this.IsUnboundControl&&n.setParameter(A.AutoResolve,t)}get defaultviewid(){let t=this.getFirstChild(D.formControl);return t?t.getParam(A.DefaultViewId):Q.EmptyString}set defaultviewid(t){let n=this.getFirstChild(D.formControl);n&&!this.IsUnboundControl&&n.setParameter(A.DefaultViewId,t)}get dependentattributename(){let t=this.getFirstChild(D.formControl);return t?t.getParam(A.DependentAttributeName):Q.EmptyString}set dependentattributename(t){let n=this.getFirstChild(D.formControl);n&&!this.IsUnboundControl&&n.setParameter(A.DependentAttributeName,t)}get dependentattributetype(){let t=this.getFirstChild(D.formControl);return t?t.getParam(A.DependentAttributeType):Q.EmptyString}set dependentattributetype(t){let n=this.getFirstChild(D.formControl);n&&!this.IsUnboundControl&&n.setParameter(A.DependentAttributeType,t)}get disablequickfind(){let t=this.getFirstChild(D.formControl);if(t)return t.getParam(A.DisableQuickFind)==="true"}set disablequickfind(t){let n=this.getFirstChild(D.formControl);n&&!this.IsUnboundControl&&n.setParameter(A.DisableQuickFind,t)}get disableviewpicker(){let t=this.getFirstChild(D.formControl);if(t)return t.getParam(A.DisableViewPicker)==="true"}set disableviewpicker(t){let n=this.getFirstChild(D.formControl);n&&!this.IsUnboundControl&&n.setParameter(A.DisableViewPicker,t)}get filterrelationshipname(){let t=this.getFirstChild(D.formControl);return t?t.getParam(A.FilterRelationshipName):Q.EmptyString}set filterrelationshipname(t){let n=this.getFirstChild(D.formControl);n&&!this.IsUnboundControl&&n.setParameter(A.FilterRelationshipName,t)}get availableviewids(){let t=this.getFirstChild(D.formControl);return t?t.getParam(A.AvailableViewIds):Q.EmptyString}set availableviewids(t){let n=this.getFirstChild(D.formControl);n&&!this.IsUnboundControl&&n.setParameter(A.AvailableViewIds,t)}get IsUnboundControl(){let t=this.getFirstChild(D.formControl);if(t&&t.ClassId){let n=An.getUniqueIdentifierForControl(t);return!F.IsNullOrUndefined(n)&&An.isUnboundFormControlByIdentifier(n)}else return!1}IsAllowedUBCForAvailableOnPhone(){let t=this.getFirstChild(D.formControl);if(t){let r=An.getUniqueIdentifierForControl(t).guidString,i=r===te.GridControl||r===te.TimeLineControl||r===te.TimeLineControlUC;return this.IsUnboundControl?i:!0}return this.NodeName===D.formSection||this.NodeName===D.formTab}IsAllowedUBCForVisibleByDefault(){let t=this.getFirstChild(D.formControl);if(t){let r=An.getUniqueIdentifierForControl(t).guidString,i=r===te.MapsControl||r===te.WebResourceHtmlControl||r===te.WebResourceImageControl||r===te.IframeControl||r===te.SocialInsightControl;return this.IsUnboundControl?i:!0}else return!0}get events(){let t=this.getChildren(D.formEvents);return t.length===1?t[0].getAllChildren():[]}addEvent(t){this.addGrandChild(D.formEvents,t)}getUsedNodeNameSet(t){return null}getHighestIndexById(t,n){return null}}});var bd,US=B(()=>{"use strict";Sr();Re();Jn();bd=class extends Se{constructor(t,n){super(D.dependency,t),Q.IsNullOrEmpty(n)||this.setDefaultProperties(n)}set id(t){this.setProperty(A.id,t)}get id(){return this.getProperty(A.id)}setDefaultProperties(t){this.id=t}}});var QV,vd,qS=B(()=>{"use strict";En();US();Re();Jn();pu();(function(e){e[e.Form=0]="Form",e[e.Cell=1]="Cell",e[e.Tab=2]="Tab",e[e.Control=3]="Control"})(QV||(QV={}));vd=class extends Nr{constructor(t,n){super(D.formEvent,t),n&&(this.eventName=n,this.application="false",this.active="false")}set eventName(t){this.setProperty(A.Name,t)}get eventName(){return this.getProperty(A.Name)}set application(t){this.setProperty(A.application,t)}get application(){return this.getProperty(A.application)}set attribute(t){this.setProperty(A.EventAttribute,t)}get attribute(){return this.getProperty(A.EventAttribute)}set relationship(t){this.setProperty(A.Relationship,t)}get relationship(){return this.getProperty(A.Relationship)}set control(t){this.setProperty(A.Control,t)}get control(){return this.getProperty(A.Control)}set active(t){this.setProperty(A.EventActive,t)}get active(){return this.getProperty(A.EventActive)}getAllHandlers(){let t=this.getChildren(D.EventHandlers);return t&&t.length?t[0].getChildren(D.handler):[]}getAllDependencies(){let t=this.getChildren(D.formDependencies);return t.length===0?[]:t[0].getAllChildren()}setDependencies(t){let n=this.getFirstChild(D.formDependencies);if(F.IsNullOrUndefined(n)){if(t.length===0)return;this.addChild(new Se(D.formDependencies,this)),n=this.getFirstChild(D.formDependencies)}if(t.length===0)n.getParentNode().deleteChild(n);else{n.deleteAllChildren();for(let r of t)n.addChild(new bd(n,r.toString()))}}}});var Do,sm=B(()=>{"use strict";Dn();bp();En();bl();Re();Jn();Io();Do=class extends Se{previewVersion;constructor(t){super(D.formControl,t)}updatePreview(){this.previewVersion=Date.now()}get ClassId(){let t=this.getProperty(A.classid);return t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"&&(t=t.substr(1,t.length-2)),new H(t)}set ClassId(t){this.setProperty(A.classid,`{${t.ToString()}}`)}get dataFieldName(){return this.getProperty(A.datafieldname)}set dataFieldName(t){this.setProperty(A.datafieldname,t)}set id(t){this.setProperty(A.id,t)}get id(){return this.getProperty(A.id)}get UniqueId(){let t=this.getProperty(A.uniqueid);return F.IsNullOrUndefined(t)?null:(t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"&&(t=t.substr(1,t.length-2)),new H(t))}set UniqueId(t){this.setProperty(A.uniqueid,`{${t.ToString()}}`)}get isRequired(){return this.getProperty(A.isRequired)==="true"}set isRequired(t){F.IsNullOrUndefined(t)||this.setProperty(A.isRequired,String(t))}get disableMru(){return this.getParam(A.DisableMru)==="true"}set disableMru(t){F.IsNullOrUndefined(t)||this.setParameter(A.DisableMru,t)}get useMFDForCreate(){return this.getParam(A.UseMFDForCreate)==="true"}set useMFDForCreate(t){F.IsNullOrUndefined(t)||this.setParameter(A.UseMFDForCreate,t)}get useMFDForEdit(){return this.getParam(A.UseMFDForEdit)==="true"}set useMFDForEdit(t){F.IsNullOrUndefined(t)||this.setParameter(A.UseMFDForEdit,t)}get disabled(){return this.getProperty(A.disabled)==="true"}set disabled(t){F.IsNullOrUndefined(t)||this.setProperty(A.disabled,String(t))}get indicationOfSubgrid(){return this.getProperty(A.indicationOfSubgrid)==="true"}set indicationOfSubgrid(t){this.setProperty(A.indicationOfSubgrid,String(t))}getAllParameters(){let t=new qr,n=this.getFirstChild(A.parameters);return n&&n.getAllChildren().forEach(r=>{if(r){let i=r.getAllChildren(),o=i&&i.length>0&&i[0];o&&t.add(r.getNodeName(),o.getNodeName())}}),t}setParameter(t,n){let r=!1;n===null&&(r=!0);let i=(cs.StartTag+n).toString(),o=this.parametersNode;if(o){let a=o.findFirst(s=>s&&s.getNodeName()===t);if(a)if(r){this.deleteFirstGrandChildOfName(D.controlParameters,a);return}else{let s=a.getAllChildren();s&&s.length>0&&s[0]?s[0].setNodeName(i):a.addChild(new Se(i,a))}else r||(a=new Se(t,o),a.addChild(new Se(i,a)),o.addChild(a))}else if(!r){o=new Se("parameters",this);let a=new Se(t,o);a.addChild(new Se(i,a)),o.addChild(a),this.addChild(o)}}getParam(t){if(this.parametersNode){let n=this.parametersNode.findFirst(r=>r&&r.getNodeName()===t);if(n){let r=n.getAllChildren(),i=r&&r.length>0&&r[0];if(i){let o=i.getNodeName();return o.charAt(0)===cs.StartTag?o.substring(1):o}}}return null}get parametersNode(){let t=this.getChildren(A.parameters);return t.length===0?null:t[0]}async serializeParameters(t,n){let r=new qr;switch(this.ClassId.guidString.toUpperCase()){case k.LookupControl:if(t&&t.getKeys())if(t.getKeys().forEach(a=>{r.add(a,this.getParam(a))}),t&&t.containsKey("DefaultViewId")){let a=this.getParam("DefaultViewId").replace("{","").replace("}","");r.upsert("DefaultViewId",a)}else{let a=this.getParent(),s=await n.formModelService.lookupControlService.populateDefaultView(this,a.getParentForm().entityName);s&&s.id&&r.upsert("DefaultViewId",s.id.replace("{","").replace("}",""))}break;default:t&&t.getKeys()&&t.getKeys().forEach(a=>{r.add(a,this.getParam(a))});break}let i=r.getInternalObject(),o=[];for(let a in i)i.hasOwnProperty(a)&&o.push({Name:a,Value:i[a]});return o}getIsUnbound(){return this.getProperty(A.isUnbound)==="true"}getAttributeTypeFromClassId(t){if(t)switch(t.toUpperCase()){case k.BooleanControl:case k.CheckboxControl:return 0;case k.DateTimeControl:return 2;case k.DecimalControl:return 3;case k.FloatingNumberControl:return 4;case k.IntegerControl:case k.DurationControl:case k.LanguageControl:case k.TimezoneControl:return 5;case k.LookupControl:return 6;case k.CurrencyControl:return 8;case k.PartyListControl:return 10;case k.ChoiceControl:case k.RelationshipRoleChoiceControl:return 11;case k.ChoiceStatusControl:return 13;case k.TextAreaControl:case k.TextboxControl:case k.LabelControl:case k.EmailAddressControl:case k.UrlControl:case k.TickerControl:case k.ButtonControl:case k.PhoneNumberControl:return 14;case k.ChoicesControl:return 24;default:return}return 14}async toJSON(t){let n=this.getParent(),r=t&&t.formModelService&&t.formModelService.getFormType()===Pn.QuickViewForm?!0:this.disabled,i=await this.serializeParameters(this.getAllParameters(),t);return{ClassId:this.ClassId&&this.ClassId.guidString,Parameters:i,Disabled:r,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:n.getDisplayName(t.langCode),LabelId:n.labelId&&n.labelId.guidString,Name:null,ShowLabel:n.showlabel,PreviewId:n&&n.id.guidString,Visible:n.visible||t.formModelService.showHiddenElements}}}});var wd,BS=B(()=>{"use strict";Sr();cl();sm();Re();Jn();wd=class extends Do{constructor(t){super(t)}get targetEntityType(){return this.getParam(A.targetEntityType)||Q.EmptyString}set targetEntityType(t){this.setParameter(A.targetEntityType,t)}get viewId(){return Q.StripBraces(this.getParam(A.viewId))||Q.EmptyString}set viewId(t){this.setParameter(A.viewId,Q.AddBraces(t))}get viewIds(){return this.getParam(A.viewIds)||Q.EmptyString}set viewIds(t){this.setParameter(A.viewIds,t)}get relationshipName(){return this.getParam(A.RelationshipName)||Q.EmptyString}set relationshipName(t){this.setParameter(A.RelationshipName,t)}get isUserView(){return Q.IsStrictTrue(this.getParam(A.isUserView))}set isUserView(t){this.setParameter(A.isUserView,t.toString())}get enableViewPicker(){return Q.IsStrictTrue(this.getParam(A.enableViewPicker))}set enableViewPicker(t){this.setParameter(A.enableViewPicker,t)}get autoExpand(){return this.getParent().autoexpand&&this.getParam(A.autoExpand)===A.Auto}set autoExpand(t){let n=this.getParent();this.setParameter(A.autoExpand,t?A.Auto:A.Fixed),n.autoexpand=t}get recordsPerPage(){return this.getParam(A.recordsPerPage)?Number(this.getParam(A.recordsPerPage)):Number(A.RecordsPerPageRAControlDefault)}set recordsPerPage(t){this.setParameter(A.recordsPerPage,String(t))}get enableQuickFind(){return Q.IsStrictTrue(this.getParam(A.enableQuickFind))}set enableQuickFind(t){this.setParameter(A.enableQuickFind,t)}get teamTemplateId(){return Q.StripBraces(this.getParam(A.teamTemplateId))||Q.EmptyString}set teamTemplateId(t){this.setParameter(A.teamTemplateId,Q.AddBraces(t))}get chartId(){return this.getParam(A.visualizationId)||Q.EmptyString}set chartId(t){this.setParameter(A.visualizationId,t)}get enableChartPicker(){return Q.IsStrictTrue(this.getParam(A.enableChartPicker))}set enableChartPicker(t){this.setParameter(A.enableChartPicker,t)}get chartGridMode(){switch(this.getParam(A.chartGridMode)){case Zi.Chart:return Zi.Chart;case Zi.Grid:return Zi.Grid;default:return Zi.All}}set chartGridMode(t){this.setParameter(A.chartGridMode,t)}updateChartGridMode(t){t?this.chartGridMode=Zi.Chart:this.chartGridMode=this.enableChartPicker?Zi.All:Zi.Grid}updateDefaultProperties(t,n){for(let r of t)switch(r.getNodeName()){case A.targetEntityType:r.getAllChildren()[0].setNodeName("<"+n.targetEntityType);break;case A.viewId:r.getAllChildren()[0].setNodeName("<"+Q.AddBraces(n.viewId));break;case A.isUserView:r.getAllChildren()[0].setNodeName("<"+n.isUserView);break;case A.enableViewPicker:r.getAllChildren()[0].setNodeName("<"+n.enableViewPicker);break;case A.RelationshipName:let i=r.getAllChildren(),o="<"+n.relationshipName;i.length?r.getAllChildren()[0].setNodeName(o):r.addChild(new Se(o,r));break;default:break}}updateControlDescription(t){let n=t.getControlDescriptionByForControl(this.UniqueId);if(n){let r=n.customControls;for(let i=0;i<r.length;i++){let o=r[i].getParameters().get(vr.dataset)?r[i].getParameters().get(vr.dataset)[0]:null;if(o){let a=o.getAllChildren();this.updateDefaultProperties(a,this)}else{let a=r[i].getAllChildren()[0].getAllChildren();this.updateDefaultProperties(a,this)}}}}}});var Ed,VS=B(()=>{"use strict";Sr();cl();sm();Re();Ed=class extends Do{constructor(t){super(t)}get defaultViewId(){return Q.StripBraces(this.getParam(A.DefaultViewId))||Q.EmptyString}set defaultViewId(t){this.setParameter(A.DefaultViewId,Q.AddBraces(t))}get autoResolve(){return Q.IsStrictTrue(this.getParam(A.AutoResolve))}set autoResolve(t){this.setParameter(A.AutoResolve,t)}get disableQuickFind(){return Q.IsStrictTrue(this.getParam(A.DisableQuickFind))}set disableQuickFind(t){this.setParameter(A.DisableQuickFind,t)}get disableViewPicker(){return Q.IsStrictTrue(this.getParam(A.DisableViewPicker))}set disableViewPicker(t){this.setParameter(A.DisableViewPicker,t)}get allowFilterOff(){return Q.IsStrictTrue(this.getParam(A.AllowFilterOff))}set allowFilterOff(t){this.setParameter(A.AllowFilterOff,t)}get disableMru(){return Q.IsStrictTrue(this.getParam(A.DisableMru))}set disableMru(t){this.setParameter(A.DisableMru,t)}get dependentAttributeName(){return this.getParam(A.DependentAttributeName)||Q.EmptyString}set dependentAttributeName(t){this.setParameter(A.DependentAttributeName,t)}get dependentAttributeType(){return this.getParam(A.DependentAttributeType)||Q.EmptyString}set dependentAttributeType(t){this.setParameter(A.DependentAttributeType,t)}get filterRelationshipName(){return this.getParam(A.FilterRelationshipName)||Q.EmptyString}set filterRelationshipName(t){this.setParameter(A.FilterRelationshipName,t)}get availableViewIds(){return this.getParam(A.AvailableViewIds)||Q.EmptyString}set availableViewIds(t){this.setParameter(A.AvailableViewIds,t)}updateDefaultProperties(t,n){for(let r of t)switch(r.getNodeName()){case A.datafieldname:case A.bindAttribute:r.getAllChildren()[0].setNodeName("<"+n.dataFieldName);break;case A.DefaultViewId:r.getAllChildren()[0].setNodeName("<"+Q.AddBraces(n.defaultViewId));break;case A.AllowFilterOff:r.getAllChildren()[0].setNodeName("<"+n.allowFilterOff);break;case A.DisableQuickFind:r.getAllChildren()[0].setNodeName("<"+n.disableQuickFind);break;case A.DisableViewPicker:r.getAllChildren()[0].setNodeName("<"+n.disableViewPicker);break;case A.FilterRelationshipName:r.getAllChildren()[0].setNodeName("<"+n.filterRelationshipName);break;case A.DependentAttributeName:r.getAllChildren()[0].setNodeName("<"+n.dependentAttributeName);break;case A.DependentAttributeType:r.getAllChildren()[0].setNodeName("<"+n.dependentAttributeType);break;case A.AvailableViewIds:r.getAllChildren()[0].setNodeName("<"+n.availableViewIds);break;case A.DisableMru:r.getAllChildren()[0].setNodeName("<"+n.disableMru);break;case A.AutoResolve:r.getAllChildren()[0].setNodeName("<"+n.autoResolve);break;default:break}}updateControlDescription(t){let n=t.getControlDescriptionByForControl(this.UniqueId);if(n){let r=n.customControls;for(let i=0;i<r.length;i++){let o=r[i].getParameters().get(vr.value)?r[i].getParameters().get(vr.value)[0]:null;if(o){let a=o.getAllChildren();this.updateDefaultProperties(a,this)}else{let a=r[i].getAllChildren()[0].getAllChildren();this.updateDefaultProperties(a,this)}}}}}});var XV,GS,gi,um=B(()=>{"use strict";XV=Xe(YV());pu();Re();En();Dn();qS();sm();Bp();YC();PC();Io();bl();td();BS();VS();jS();xc();GS="_",gi=class e extends Nr{fieldPlaceholder;fieldRequiredLevel;isNewField;cellColType;dependentFields=[];constructor(t){super(D.formCell,t),this.isNewField=!1}get cellType(){return this.cellColType}set cellType(t){this.cellColType=t}setDefaultProperties(t){this.showlabel=t,this.isLocked=!1,F.IsNullOrUndefined(this.getProperty(A.id))&&(this.id=new H(H.NewGuid()))}addControl(t,n,r,i,o,a,s){r instanceof Do?this.addChild(r):r instanceof H&&this.addChild(this.getControlWithControlSpecificProperties(t,n,r,i,o,a,s))}removeControl(){return this.deleteChild(this.control)>=0}get isIndependent(){if(!F.IsNullOrUndefined(this.control))return F.IsNullOrUndefined(this.control.dataFieldName)?F.IsNullOrUndefined(this.control.id)?!0:!wl.dependencyFieldCount.containsKey(this.control.id):!wl.dependencyFieldCount.containsKey(this.control.dataFieldName)}createOnLoadEvent(){this.addEvent(new vd(this,kp.onLoad))}get dependencies(){let t=this.getChildren(D.formEvents);for(let n of t){let r=n.getChildren(D.formEvent);for(let i of r)this.buildDependencyList(i,this.dependentFields)}return this.dependentFields}getNextAvailableControlName(t,n,r,i){let o;if(i&&k0[i])o=k0[i].replace(/ /g,GS)+GS;else{o="Control_";let l=new Error("Control class id does not exist or is undefined");(0,XV.trackErrorTrace)(Vr,{eventName:`${Y2}/getNextAvailableControlName`},l)}let a="new_",s=this.getHighestIndexById(t,i)+1,u=`${o}${a}${s}`;for(;r.has(u);)s++,u=`${o}${a}${s}`;return u}getUnboundControlProperties(t){e.prototype.setProperty.call(t,A.isUnbound,"true"),e.prototype.setProperty.call(t,A.isRequired,"false")}getControlWithControlSpecificProperties(t,n,r,i,o,a,s){let u;o===to.Grid?(u=new wd(this),u.indicationOfSubgrid=!0):o===to.Lookup?u=new Ed(this):u=new Do(this);let l=r.guidString,c=a||this.getNextAvailableControlName(t,i,this.getUsedNodeNameSet(t),l);if(e.prototype.setProperty.call(u,A.id,c),u.ClassId=r,!F.IsNullOrUndefined(s)&&(u.UniqueId=s),!a&&n)this.getUnboundControlProperties(u);else{let d=An.getUniqueIdentifierForControl(u);F.IsNullOrUndefined(d)||(An.getControlDataTypeByControlOrUniqueId(d)===be.QuickFormCollectionControl||!An.isUnboundFormControlByIdentifier(d)?o!==to.Grid&&a&&l!==k.IframeControl&&l!==k.SubgridControl&&l!==k.ReferencePanelSubgridControl&&(u.dataFieldName=a,e.prototype.setProperty.call(u,A.disabled,"false")):(this.rowspan=An.GetRowSpan(u),(An.getControlDataTypeByControlOrUniqueId(d)===be.NotesControl||An.getControlDataTypeByControlOrUniqueId(d)===be.TimeLineControl)&&(e.prototype.setProperty.call(u,A.disabled,"false"),u.id=be.NotesControl)),(An.getUnboundControlNameFromIdentifier(r)===be.SubGridControl||An.getUnboundControlNameFromIdentifier(r)===be.NotesControl||An.getUnboundControlNameFromIdentifier(r)===be.TimeLineControl)&&(this.availableforphone=!0))}return u}buildDependencyList(t,n){if(F.IsNullOrUndefined(t))return;let r=t.getAllChildren();for(let i of r){let o=i.getAllChildren();for(let a of o){let s=a.GetPropertyByParameter(A.id);a.getNodeName()===D.dependency&&s?n.push(s):this.buildDependencyList(a,n)}}}get control(){return this.getFirstChild(D.formControl)}set rowspan(t){this.setProperty(A.rowspan,String(t))}get rowspan(){let t=this.getProperty(A.rowspan);return F.IsNullOrUndefined(t)?1:parseInt(t,10)}set autoexpand(t){this.setProperty(A.auto,String(t))}get autoexpand(){return this.getProperty(A.auto)==="true"}set colspan(t){let n=Number(KC.ONE_COLUMN),r=Number(KC.FOUR_COLUMN);F.IsNullOrUndefined(t)||t>r||t<n||this.setProperty(A.colspan,String(t))}get colspan(){let t=this.getProperty(A.colspan);return F.IsNullOrUndefined(t)?1:parseInt(t,10)}getParentRow(){return this.getAncestor(D.formRow)}getParentSection(){return this.getAncestor(D.formSection)}getParentTab(){return this.getAncestor(D.formTab)}getParentForm(){return this.getAncestor(D.form)}isInHeader(){let t=this.getAncestor(D.formHeader);return!F.IsNullOrUndefined(t)}isInFooter(){let t=this.getAncestor(D.formFooter);return!F.IsNullOrUndefined(t)}isEmpty(){return F.IsNullOrUndefined(this.control)&&!this.IsUserSpacer}getHeaderFooter(){return this.isInHeader()?this.getAncestor(D.formHeader):this.isInFooter()?this.getAncestor(D.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(A.userspacer);return F.IsNullOrUndefined(t)?!1:t==="true"}SetUserSpacer(){this.setProperty(A.userspacer,"true")}ClearUserSpacer(){this.setProperty(A.userspacer,"false")}get columns(){let t=this.getProperty(A.columnName);return F.IsNullOrUndefined(t)?null:parseInt(t,10)}getColumnLayoutValue(t){let n;switch(t){case Vt.TWO_COLUMN:n="11";break;case Vt.THREE_COLUMN:n="111";break;case Vt.FOUR_COLUMN:n="1111";break;default:n="1"}return n}findRowIndexByCellId(t){let n=this.getParentRow().cells.indexOf(this);for(let r=0;r<t.rows.length;r++)if(!F.IsNullOrUndefined(t.rows[r].cells[n])&&this.id.ToString()===t.rows[r].cells[n].id.ToString())return r;return-1}setAutoExpandDetailsForTab(){let t=this.getParentTab();F.IsNullOrUndefined(t)||(t.autoExpandCell=this,t.tabContainsAutoExpandControl=!0)}isCellRequiredOrLocked(t,n,r){let i=this.getParentForm();if(this?.control){if(this.IsUserSpacer)return!1;{if(this.isLocked||n().has(this.control.dataFieldName))return!0;let o=i.isDuplicateCell(this,r),a=this.getRequiredLevel(t);if((a===tu.ApplicationRequired||a===tu.SystemRequired)&&!o||this.isCellLockedByExternal(t)&&!o)return!0}}return!1}getRequiredLevel(t){return!this.control?.dataFieldName||!this.control?.id||this.IsNewField||!this.control?.ClassId?tu.None:t.getEntityAttributeByName(this.control.dataFieldName)?.requiredLevel?.toString()??tu.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 n=new Set;return t&&t.visit(r=>{if(r.getNodeName()===D.formCell){let i=r;i.control&&i!==this&&n.add(r.control.id)}return!1}),n}getHighestIndexById(t,n){let r=t.findAll(o=>o.getNodeName()===D.formCell&&o.control&&o.control.ClassId.guidString===n),i=0;return r.forEach(o=>{i=Math.max(this.parseControlNameIndex(o.control.id),i)}),i}parseControlNameIndex(t){let n=t.length-1,r=0;for(;n>0&&parseInt(t.charAt(n),10);)n--;return n>0&&n!==t.length-1&&t.charAt(n)===GS&&(n++,r=parseInt(t.substr(n,t.length-n),10)),r}}});var Ad,WS=B(()=>{"use strict";Sr();Re();Jn();Ad=class extends Se{isInternal;constructor(t,n,r,i){super(D.library,t),this.isInternal=!!i,Q.IsNullOrEmpty(r)||(this.name=n,this.libraryUniqueId=r)}get libraryUniqueId(){let t=this.getProperty(A.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(A.libraryUniqueId,t)}get name(){return this.getProperty(A.libraryName)}set name(t){this.setProperty(A.libraryName,t)}get displayName(){return this.getProperty(A.displayName)}set displayName(t){this.setProperty(A.displayName,t)}get description(){return this.getProperty(A.description)}set description(t){this.setProperty(A.description,t)}}});var _l,zS=B(()=>{"use strict";En();um();Re();Jn();_l=class extends Se{isRowAddedOnDragOver;constructor(t){super(D.formRow,t)}addCell(t){this.addChild(t)}appendCells(t){for(let n of t)this.addChild(n)}updateCell(t,n){return this.updateChild(t,n)}removeCell(t){return F.IsNullOrUndefined(t)?!1:this.deleteChild(t)>=0}insertCellAtIndex(t,n){return F.IsNullOrUndefined(t)?!1:(this.insertChildAtIndex(t,n),!0)}isEmpty(){return!this.cells||this.cells.every(t=>t.isEmpty())}getParentSection(){return this.getAncestor(D.formSection)}insertPaddingCellAtIndex(t){let n=new gi(this);n.setDefaultProperties(),this.insertCellAtIndex(n,t)}get firstCell(){let t=this.cells;return t.length>0?t[0]:null}get cells(){return this.getChildren(D.formCell)}get rowColspan(){return this.cells.reduce((t,n)=>t+n.colspan,0)}set IsRowAddedOnDragOver(t){this.isRowAddedOnDragOver=t}get IsRowAddedOnDragOver(){return this.isRowAddedOnDragOver}async getCellsJSON(t){let n=[],r=[];if(this.cells){for(let i of this.cells)r.push(i.toJSON(t));for(let i of r)n.push(await i)}return n}async toJSON(t){return{Cells:await this.getCellsJSON(t),Visible:!0,Height:"0"}}}});function Jge(e){switch(e){case El.Left:return Cl.Left;case El.Right:return Cl.Right;case El.Center:return Cl.Center;default:return Cl.Left}}function Yge(e){switch(e){case rd.Left:return id.Left;case rd.Top:return id.Top;default:return id.Left}}function ZV(e){switch(e){case 1:return 1;case 2:return 11;case 3:return 111;case 4:return 1111;default:return 1}}var Qge,ga,lm=B(()=>{"use strict";QC();Dn();En();Sr();FS();um();Re();Io();pu();zS();Qge=115,ga=class e extends Nr{colSpan=1;constructor(t,n){super(t,n)}getSectionType(){let t;switch(this.columns){case 1:t=Vt.ONE_COLUMN;break;case 11:t=Vt.TWO_COLUMN;break;case 111:t=Vt.THREE_COLUMN;break;case 1111:t=Vt.FOUR_COLUMN;break;default:t=this.colSpan-1}return t}setUniqueName(){let t=this.getParentTab(),n=xt.namePrefix;if(t){let r=t.Name,i=t.TotalSectionsCount+1;n=r+xt.namePrefix+i.toString()}else n+=Math.floor(Math.random()*1e3);this.setProperty(A.Name,n)}initializeDefaultProperties(t,n,r){if(r===Vt.REFERENCE_PANEL){this.addProperty(A.rowheight,"25");let i=`${xt.referencePanelNamePrefix}${H.NewGuid()}${xt.namePrefix}`;this.addProperty(A.Name,i)}else this.setUniqueName();if(this.addProperty(A.id,new H(H.NewGuid()).guidString),this.addProperty(A.IsUserDefined,xt.IsUserDefined),this.addProperty(A.locklevel,xt.LockLevel),this.addProperty(A.showlabel,xt.ShowLabel),this.addProperty(A.showbar,xt.ShowBar),this.addProperty(A.layout,xt.Layout),this.addProperty(A.Fieldlabelalignment,xt.labelAlignment),this.addProperty(A.Fieldlabelposition,xt.labelPosition),F.IsNullOrUndefined(r))this.addProperty(A.columnName,xt.columns);else{let i=this.getColumnLayoutValue(r);this.addProperty(A.columnName,i)}this.addProperty(A.LabelWidth,xt.LabelWidth),this.setDisplayName(n,t)}getColumnLayoutValue(t){let n;switch(t){case Vt.TWO_COLUMN:n="11";break;case Vt.THREE_COLUMN:n="111";break;case Vt.FOUR_COLUMN:n="1111";break;default:n="1"}return n}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 F.IsNullOrUndefined(this.columns)?t=this.ColSpan:this.columns.toString().split(Q.EmptyString).forEach(n=>{t+=parseInt(n,10)}),t}get ColSpan(){return this.colSpan}initializeRow(t){if(t>0&&t<5){let n=new _l(null);if(this.addGrandChild(D.formRows,n),zV.getConfig().enableAutoInsertionOfCellInRow)for(let r=0;r<t;r++){let i=new gi(n);i.setDefaultProperties(!1),n.addCell(i)}}}initialize(t,n,r){this.initializeDefaultProperties(t,n,r),r===Vt.REFERENCE_PANEL&&(r=Vt.ONE_COLUMN),this.initializeRow(r+1)}setColSpan(t){this.colSpan=t}appendRow(t){this.addGrandChild(D.formRows,t)}insertRowAtIndex(t,n){this.addGrandChildAtIndex(D.formRows,t,n)}insertRowsAtIndex(t,n){if(t&&t.length>0)for(let r=0;r<t.length;r++)this.addGrandChildAtIndex(D.formRows,t[r],n+r)}indexOfRow(t){return this.rows.indexOf(t)}deleteRow(t){return this.deleteFirstGrandChildOfName(D.formRows,t)}deleteRows(t,n){this.deleteGrandChildren(D.formRows,t,n)}get rows(){return this.getRows()}getRows(){let t=this.getChildren(D.formRows);return t.length===0?[]:t[0].getChildren(D.formRow)}get columns(){let t=this.getProperty(A.columnName),n=F.IsNullOrUndefined(t)?NaN:parseInt(t,10);if(isNaN(n)){let r=1;for(let i of this.rows)r=Math.max(r,i.cells.length);return ZV(r)}return n}set columns(t){F.IsNullOrUndefined(t)||this.setProperty(A.columnName,String(t))}get rowHeight(){let t=this.getProperty(A.rowheight);return F.IsNullOrUndefined(t)?null:parseInt(t,10)}set rowHeight(t){this.setProperty(A.rowheight,String(t))}set autoexpand(t){this.setProperty(A.autoExpand.toLowerCase(),String(t))}get autoexpand(){return this.getProperty(A.autoExpand.toLowerCase())==="true"}get isUserDefined(){return+this.getProperty(A.IsUserDefined)!=0}set isUserDefined(t){t?this.setProperty(A.IsUserDefined,"1"):this.setProperty(A.IsUserDefined,"0")}getParentColumn(){return this.getAncestor(D.formColumn)}getParentTab(){return this.getAncestor(D.formTab)}get hasMultiColumnRow(){return this.getColumnCountValue()>1}get showlabel(){return this.getProperty(A.showlabel)==="true"}set showlabel(t){F.IsNullOrUndefined(t)||this.setProperty(A.showlabel,String(t))}get fieldLabelAlignment(){let t=xt.labelAlignment,n=this.getProperty(A.Fieldlabelalignment);return F.IsNullOrUndefined(n)?t:n}set fieldLabelAlignment(t){F.IsNullOrUndefined(t)||this.setProperty(A.Fieldlabelalignment,t)}get fieldLabelPosition(){let t=this.getProperty(A.Fieldlabelposition);return F.IsNullOrUndefined(t)?xt.labelPosition:t}set fieldLabelPosition(t){F.IsNullOrUndefined(t)||this.setProperty(A.Fieldlabelposition,String(t))}get showbar(){return this.getProperty(A.showbar)==="true"}set showbar(t){F.IsNullOrUndefined(t)||this.setProperty(A.showbar,String(t))}get labelwidth(){let t=+this.getProperty(A.LabelWidth);return t===0?Qge:t}set labelwidth(t){F.IsNullOrUndefined(t)||t>283&&t<57||this.setProperty(A.LabelWidth,t.toString())}async getRowsJSON(t){let n=[],r=[];if(this.rows){for(let i of this.rows)r.push(i.toJSON(t));for(let i of r)n.push(await i)}return n}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:Jge(this.fieldLabelAlignment),Position:Yge(this.fieldLabelPosition)},Columns:ZV(this.getColumnCountValue()),AvailableForPhone:this.availableforphone,Height:this.rowHeight&&this.rowHeight.toString()}}getUsedNodeNameSet(t){let n=new Set;return t&&t.visit(r=>{if(r.getNodeName()===D.formSection){let i=r;i.Name&&!Q.GuidStringEquals(i.id.guidString,this.id.guidString)&&n.add(r.Name)}return!1}),n}isReferencePanelSection(){return!F.IsNullOrUndefined(this)&&!F.IsNullOrUndefined(this.Name)&&this.Name.indexOf(xt.referencePanelNamePrefix)===0}getAllMultiRowCells(){return this.findAll(t=>{if(t.getNodeName()===D.formCell){let n=t;return!n.isEmpty()&&n.rowspan>1}return!1})}isHeaderOrFooterSection(){return this.NodeName===D.formFooter||this.NodeName===D.formHeader}}});var mu,sy=B(()=>{"use strict";Re();Jn();lm();mu=class e extends Se{constructor(t){super(D.formColumn,t)}initializeDefaultProperties(t){this.addProperty(A.width,t.toString()+"%")}insertSectionAtIndex(t,n){this.addGrandChildAtIndex(D.formSections,t,n)}static createAndInitNewSection(t,n,r){let i=new ga(D.formSection,null);return i.initialize(t,n,r),i}addSectionAtIndex(t,n){this.addGrandChildAtIndex(D.formSections,t,n)}initialize(t,n,r,i=Vt.ONE_COLUMN){this.initializeDefaultProperties(t);let o=e.createAndInitNewSection(n,r,i);this.addSectionAtIndex(o,this.sections.length),o.setUniqueName()}get parentTab(){return this.getAncestor(D.formTab)}get sections(){let t=this.getChildren("sections");return t.length!==1?[]:t[0].getChildren(D.formSection)}get width(){return this.getProperty(A.width)}set width(t){this.setProperty(A.width,t)}deleteSection(t){return this.deleteFirstGrandChildOfName(D.formSections,t)}async getSectionsJSON(t){let n=[];if(this.sections)for(let r of this.sections)n.push(await r.toJSON(t));return n}async toJSON(t){return{Name:this.getProperty(A.Name),Id:this.getProperty(A.id),Label:null,ShowLabel:!1,Visible:!0,LabelId:null,PreviewId:this.getProperty(A.id),Sections:await this.getSectionsJSON(t),Width:this.width}}}});var uy,eG=B(()=>{"use strict";Dn();Re();Io();lm();uy=class extends ga{initializeNavArea(t,n,r){this.initializeNavAreaProps(t,n,r)}get AreaName(){return this.Name}initializeNavAreaProps(t,n,r){this.addProperty(A.Name,r),this.addProperty(A.id,new H(H.NewGuid()).guidString),this.addProperty(A.columnName,xt.columns),this.setDisplayName(n,t)}}});var ly,tG=B(()=>{"use strict";sy();Re();eG();ly=class extends mu{addAndIntializeNavBarSection(t,n,r,i){let o=new uy(D.formSection,null);return o.initializeNavArea(t,n,i),this.addGrandChildAtIndex(D.formSections,o,r),o}}});var fs,cy=B(()=>{"use strict";Dn();En();Sr();sy();Re();Jn();pu();fs=class extends Nr{tabContainsAutoExpandControl;autoExpandCell;constructor(t,n){super(D.formTab,t),this.tabContainsAutoExpandControl=!1}getParentForm(){return this.getAncestor(D.form)}getTabLayoutType(){let t;switch(this.columns.length){case 1:t=Bt.ONE_COLUMN;break;case 2:if(parseInt(this.columns[0].width,10)===50&&parseInt(this.columns[1].width,10)===50){t=Bt.TWO_COLUMN_EQUAL;break}if(parseInt(this.columns[0].width,10)===67&&parseInt(this.columns[1].width,10)===33){t=Bt.TWO_COLUMN_WIDER_LEFT;break}if(parseInt(this.columns[0].width,10)===34&&parseInt(this.columns[1].width,10)===66){t=Bt.TWO_COLUMN_WIDER_RIGHT;break}t=Bt.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=Bt.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=Bt.THREE_COLUMN_WIDER_MID;break}t=Bt.THREE_COLUMN_CUSTOM_LAYOUT;break;default:}return t}initializeProperties(t,n,r){this.addProperty(A.Name,uu.namePrefix+t.toString()),this.addProperty(A.id,new H(H.NewGuid()).guidString),this.addProperty(A.IsUserDefined,uu.IsUserDefined),this.addProperty(A.locklevel,uu.LockLevel),this.addProperty(A.showlabel,uu.ShowLabel),this.setDisplayName(r,n)}get TotalSectionsCount(){let t=0;for(let n of this.columns)t+=n.sections.length;return t}initializeColumns(t,n,r,i=Vt.ONE_COLUMN,o=!0,a){let s=this.getChildren(D.formColumns)[0],u=[];switch(t){case Bt.ONE_COLUMN:u.push(100);break;case Bt.TWO_COLUMN_EQUAL:u.push(50),u.push(50);break;case Bt.TWO_COLUMN_WIDER_LEFT:u.push(67),u.push(33);break;case Bt.TWO_COLUMN_WIDER_RIGHT:u.push(34),u.push(66);break;case Bt.THREE_COLUMN_EQUAL:u.push(34),u.push(33),u.push(33);break;case Bt.THREE_COLUMN_WIDER_MID:u.push(28),u.push(44),u.push(28);break;default:}for(let l of u){let c=new mu(s);c.initialize(l,n,r,i),this.addGrandChild(D.formColumns,c)}}initialize(t,n,r,i,o,a=Vt.ONE_COLUMN,s=!0,u){this.addChild(new Se(D.formColumns,this)),this.initializeProperties(n,r,i),this.initializeColumns(t,r,o,a,s,u)}get columns(){let t=this.getChildren(D.formColumns);return t.length!==1?[]:t[0].getChildren(D.formColumn)}get expanded(){return this.getProcessedValue(A.expanded)}set expanded(t){F.IsNullOrUndefined(t)||this.setProperty(A.expanded,String(t))}get groupName(){return this.getProperty(A.groupName)}get contentType(){return this.getProperty(A.contentType)}set contentType(t){this.setProperty(A.contentType,t)}insertNewColumnAtIndex(t,n,r,i,o){t.initialize(r,i,o),this.addGrandChildAtIndex(D.formColumns,t,n)}insertColumnAtIndex(t,n){this.addGrandChildAtIndex(D.formColumns,t,n)}deleteColumn(t){return this.deleteFirstGrandChildOfName(D.formColumns,t)}async getColumnsJSON(t){let n=[],r=[];if(this.columns){for(let i of this.columns)r.push(i.toJSON(t));for(let i of r)n.push(await i)}return n}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 n=new Set;return t&&t.visit(r=>{if(r.getNodeName()===D.formTab){let i=r;i.Name&&!Q.GuidStringEquals(i.id.guidString,this.id.guidString)&&n.add(r.Name)}return!1}),n}}});var Il,HS=B(()=>{"use strict";Dn();Re();Jn();Io();tG();cy();Il=class extends fs{constructor(t,n,r){super(t,Bt.THREE_COLUMN_EQUAL),this.setDisplayName(n,r),this.id=new H(H.NewGuid())}initializeDefaultProps(){this.addChild(new Se(D.formColumns,this)),this.initializeFiveColumns()}get columns(){let t=this.getChildren("columns");return t.length!==1?[]:t[0].getChildren(D.formColumn)}getNavSectionForArea(t){for(let n of this.columns)for(let r of n.sections)if(r.AreaName===t)return r;return null}getNavCellFromNavId(t){for(let n of this.columns)for(let r of n.sections)for(let i of r.rows)for(let o of i.cells)if(o.NavId===t)return o;return null}initializeFiveColumns(){for(let t=0;t<G0.FIVE_COLUMN;t++){let n=new ly(this.getChildren(D.formColumns)[0]);n.initializeDefaultProperties(E1.FiveEqColumn),this.addGrandChild(D.formColumns,n)}}}});function Zge(e){switch(e){case Pn.Main:return lu.Main;case Pn.QuickCreate:return lu.QuickCreate;case Pn.QuickViewForm:return lu.Quick;case Pn.Dialog:return lu.Dialog;default:return lu.None}}function e0e(e,t){if(t===Pn.Main){if(e)switch(e.toLowerCase()){case"low":return su.Low;case"highreadonlyvalues":return su.HighReadOnlyValues;default:return su.HighWithControls}return su.Low}}var fy,Xge,dy,nG=B(()=>{"use strict";O1();fy=Xe(vl());QC();En();Sr();td();FS();Re();cl();bC();bl();um();Re();pu();WS();HS();cy();Xge="1920";dy=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,n,r,i,o,a,s,u,l){super(D.form,null),this._formUniqueName=o,this._formId=t,this._entityName=n,this._status=r,this._formName=i,this._description=u,this._formType=a,this._formPresentation=s,this._formactivationstate=l,this._changeTracker=new O0,this._metadataChangeEvent=new W0}get FormLibraries(){let t=this.getFirstChild(D.formLibraries),n=t?t.getAllChildren():[],r=this._getInternalLibraries();return n.concat(r)}getAllEvents(){let t=[],n=this.events;n&&(t=t.concat(n));for(let r of this.tabs){let i=r.events;i&&(t=t.concat(i)),r.findAll(o=>o instanceof gi).forEach(o=>{let a=o.events;a&&(t=t.concat(a))})}return t}getEventsForNode(t){if(t instanceof e){let n=t.events;return n?n.filter(r=>!r.control&&!r.attribute):null}else if(t instanceof gi){if(t.control?.dataFieldName){let n=this.events;return n?n.filter(r=>r.attribute&&t.control.dataFieldName===r.attribute):null}else if(this.isCellEditableGridControl(t)){let n=this.events;return n?n.filter(r=>r.control&&t.control.id===r.control):null}}return t?.events}_getInternalLibraries(){let t=this.findAll(i=>i.getNodeName()===D.internalLibraries),n=[],r="src";return t.length>0&&(n=t.map(i=>{let o=i.GetPropertyByParameter(r).replace("$webresource:",""),a=new Ad(void 0,void 0,"",!0);return a.name=o,a.displayName=o,a})),n}getDependentFields(){let t=this.getAllEvents(),n=new Set;return t.forEach(r=>{try{r.getAllDependencies().forEach(o=>{n.add(o.id)})}catch(i){throw(0,fy.trackErrorTrace)(Q2,{eventName:"GetDependentFields_MissingDependencies",eventData:{Message:`Failed get dependencies for form event in form ${this.formId.guidString}.`,Attribute:r.attribute,EventName:r.eventName}}),i}}),n}get Parameters(){return this.parameters}set Parameters(t){this.parameters=t}get ShowImagecheck(){return Q.IsNullOrEmpty(this.getProperty(A.ShowImage))?!0:this.getProperty(A.ShowImage)!=="false"}set ShowImagecheck(t){t?this.setProperty(A.ShowImage,String(t)):this.setProperty(A.ShowImage,"false")}get ShowNavigation(){return Q.IsNullOrEmpty(this.getProperty(A.ShowNavigationbar))?!0:this.getProperty(A.ShowNavigationbar)!=="false"}set ShowNavigation(t){t?this.setProperty(A.ShowNavigationbar,String(t)):this.setProperty(A.ShowNavigationbar,"false")}get MaxWidth(){return Q.IsNullOrEmpty(this.getProperty(A.MaxWidth))?Xge:this.getProperty(A.MaxWidth)}set MaxWidth(t){this.setProperty(A.MaxWidth,t)}get headerDensityType(){return this.getProperty(A.HeaderDensityType)}set headerDensityType(t){t&&this.formType===Pn.Main?this.setProperty(A.HeaderDensityType,t):this.formType!==Pn.Main&&this.headerDensityType&&this.removeProperty(A.HeaderDensityType)}IsMainOrQuickCreateForm(){return this.formType===Pn.Main||this.formType===Pn.QuickCreate}get FormPresentation(){return this._formPresentation}get LanguageCode(){return this._langCode}set LanguageCode(t){this._langCode=t}get header(){let t=this.getChildren(D.formHeader);return t.length!==1?null:t[0]}set header(t){F.IsNullOrUndefined(t)||(this.deleteChild(this.header),this.addChild(t))}getAllDependencies(){return this.getChildren(D.quickFormDependencies).length===0?[]:this.ConvertModelToArray(this.getChildren(D.quickFormDependencies)[0].getAllChildren())}ConvertModelToArray(t){let n=[];return F.IsNullOrUndefined(t)||t.forEach(r=>{n.push(r.id)}),n}get footer(){let t=this.getChildren(D.formFooter);return t.length!==1?null:t[0]}set footer(t){F.IsNullOrUndefined(t)||(this.deleteChild(this.footer),this.addChild(t))}createAndInitNewTab(t,n,r){let i=new fs(null,t),o=this.getNextTabCounter(this.tabs.length+1);return i.initialize(t,o,this.LanguageCode,n,r),i}addTabAtIndex(t,n){this.addGrandChildAtIndex(D.formTabs,t,n)}createAndInitNewTabWithMarginalControl(t,n,r,i,o){let a=new fs(null,Bt.ONE_COLUMN),s=this.getNextTabCounter(this.tabs.length+1);a.initialize(Bt.ONE_COLUMN,s,this.LanguageCode,n,r,o,!1),this.addGrandChildAtIndex(D.formTabs,a,i);let u=a.columns[0].sections[0];for(let l=0;l<t.rows.length;l++)u.appendRow(t.rows[l])}getNextTabCounter(t){for(let n=0;n<this.tabs.length;n++)if(this.tabs[n].Name===uu.namePrefix+t.toString())return this.getNextTabCounter(t+1);return t}get allTabs(){let t=this.getChildren(D.formTabs);return t.length!==1?[]:t[0].getChildren(D.formTab)}get CanvasNavigationTab(){if(this.tabs.length>0){let t=this.tabs[this.tabs.length-1];if(t instanceof Il)return t}return null}get NavigationNode(){let t=this.getChildren(D.formNavigation);return t.length!==1?null:t[0]}set NavigationNode(t){let r=this.getAllChildren().indexOf(this.NavigationNode);r>=0&&(this.deleteChild(this.NavigationNode),this.insertChildAtIndex(t,r))}addNavigatioNode(t){this.addChild(t)}get tabs(){return this.allTabs}deleteTab(t){return this.deleteFirstGrandChildOfName(D.formTabs,t)}insertTabAtIndex(t,n){this.addGrandChildAtIndex(D.formTabs,t,n)}insertRelatedTab(t){let n=this.getAllGrandChildren(D.formTabs);if(!F.IsNullOrUndefined(n)){let r=n.length;this.insertTabAtIndex(t,r)}}get isfooterPresent(){return this.getChildren(D.formFooter).length>0}get displayCondition(){let t=this.getChildren(D.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(D.formTabs).indexOf(t)}get ControlDescriptions(){return this.getAllGrandChildren(D.controlDescriptions)}addControlDescriptionNode(t){this.addGrandChild(D.controlDescriptions,t)}deleteControlDescByForControlId(t){let n=this.getControlDescriptionByForControl(t);F.IsNullOrUndefined(n)||this.deleteFirstGrandChildOfName(D.controlDescriptions,n)}getControlDescriptionByForControl(t){if(!t)return null;for(let n of this.ControlDescriptions)if(n.forControl.guidString===t.guidString)return n;return null}cellHasCustomControlWithName(t,n){if(!t?.control||!n)return!1;let r=this.getControlDescriptionByForControl(t.control.UniqueId);return r?!!r.customControls.find(i=>i.name===n):!1}isDuplicateCell(t,n){return!!this.findFirst(i=>{if(!(i instanceof gi))return!1;let o=!0;return n==="Tab"?o=i.getParentTab()!==t.getParentTab():n==="Section"?o=i.getParentSection()!==t.getParentSection():o=i!==t,i instanceof gi&&i.control&&t.control&&o&&i.control.dataFieldName===t.control.dataFieldName})}isCellEditableGridControl(t){return!t?.control?.indicationOfSubgrid||t.control.ClassId.guidString.toUpperCase()!==k.CustomControl?!1:this.cellHasCustomControlWithName(t,is.EditableGridControl)||HV.getConfig()?.enableOneGridEventsForFormDesigner&&this.cellHasCustomControlWithName(t,is.PowerAppsOneGrid)}isCellCanvasAppControl(t){return t?.control?.ClassId.guidString.toUpperCase()===k.CustomControl&&this.cellHasCustomControlWithName(t,is.CanvasAppControl)}findFormNodeById(t,n=this){return n===null?null:n.findFirst(r=>{if(r===this&&t===this.formId.ToString()||r.id?.ToString?.()===t)return!0})}findFormCellByClassId(t,n=this){return n?n.findFirst(r=>{if(r.getNodeName()===D.formCell){let i=r;return i&&i.control&&i.control.ClassId.guidString===t}return!1}):null}async getTabsJSON(t){let n=this.tabs,r=[],i=[];if(n){for(let o of n)if(!(o instanceof Il)){let a=o.toJSON(t);r.push(a)}for(let o of r)i.push(await o)}return i}async getControlDescriptionsToJSON(t){let n=[];for(let r of this.ControlDescriptions){let i=await r.toJSON(t);i&&n.push(i)}return n}async toJSON(t){let n=[];n=await this.getControlDescriptionsToJSON(t);let r=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,fy.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===Pn.Main?{HeaderDensity:e0e(this.headerDensityType,this.formType)}:{},InlineEditGridRow:[],InlineQuickForms:[],QuickFormEntities:[],EventHandlers:[],LinkControlSections:[],FormType:Zge(this.formType),SubGrids:[],Views:void 0,Charts:void 0,CustomControlConfigurations:n,BusinessLogic:void 0,FormLibraries:[],Navigation:r,ShowNavigationBar:this.ShowNavigation||t.formModelService.showHiddenElements,ClientResources:[]}}changeTracker(){return this._changeTracker}onMetadataChange=t=>this._metadataChangeEvent.on(t);raiseMetadataChange(t){this._metadataChangeEvent.emit(t)}}});var py,KS,rG=B(()=>{"use strict";Dn();En();Re();Jn();pu();py=class extends Nr{constructor(t){super(D.formDisplayConditions,t)}get Order(){let t=this.getProperty(A.Order);return F.IsNullOrUndefined(t)?null:parseInt(t,10)}set Order(t){this.setProperty(A.Order,t.toString())}get FallbackForm(){return this.getProperty(A.FallbackForm)==="true"}set FallbackForm(t){this.setProperty(A.FallbackForm,t.toString())}addRoles(t){this.deleteAllChildren();for(let n=0;n<t.length;n++)this.addChild(t[n])}isRoleEveryone(){return!!(this.getChildren(D.formEveryOne)&&this.getChildren(D.formEveryOne)[0])}setRoleEveryone(){this.deleteAllChildren(),this.addChild(new KS(this))}},KS=class extends Se{constructor(t){super(D.formEveryOne,t)}}});var my,iG=B(()=>{"use strict";Re();Jn();my=class extends Se{constructor(t,n){super(D.Handler,n),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(A.HandlerUniqueId)}set HandlerUniqueID(t){this.setProperty(A.HandlerUniqueId,t)}get FunctionName(){return this.getProperty(A.functionName)}set FunctionName(t){this.setProperty(A.functionName,t)}get LibraryName(){return this.getProperty(A.libraryNameEventHandler)}set LibraryName(t){this.setProperty(A.libraryNameEventHandler,t)}get Enabled(){return this.getProperty(A.enabledForField)}set Enabled(t){this.setProperty(A.enabledForField,t)}get PassExecutionContext(){return this.getProperty(A.passExecutionContext)}set PassExecutionContext(t){this.setProperty(A.passExecutionContext,t)}get Parameters(){return this.getProperty(A.parameters)}set Parameters(t){this.setProperty(A.parameters,t)}}});var Cd,JS=B(()=>{"use strict";Re();lm();Cd=class extends ga{constructor(t,n){super(t,n)}get cells(){let t=this.getRows(),n=[];if(this.rows&&t.length){for(let r of this.rows)if(r.cells){let i=r.getChildren(D.formCell);for(let o of i)n.push(o)}}return n}get occupiedCells(){return this.cells.filter(t=>!t.isEmpty())}get maxColumns(){return super.getColumnCountValue()}}});var cm,oG=B(()=>{"use strict";Re();JS();cm=class extends Cd{_customFooter;constructor(t,n){super(D.formFooter,t),this._customFooter=n}get customFooter(){return this._customFooter}set customFooter(t){this._customFooter=t}async getControls(t){let n=[];if(this.rows){for(let r of this.rows)if(r.cells)for(let i of r.cells)i.control&&n.push(await i.control.toJSON(t))}return n}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 dm,aG=B(()=>{"use strict";Re();JS();dm=class extends Cd{_customHeader;constructor(t,n){super(D.formHeader,t),this._customHeader=n}get customHeader(){return this._customHeader}set customHeader(t){this._customHeader=t}get showCommandBar(){return this.getProcessedValue(A.showCommandBar)}set showCommandBar(t){t!=null&&this.setProperty(A.showCommandBar,String(t))}get showBody(){return this.getProcessedValue(A.showBody)}set showBody(t){t!=null&&this.setProperty(A.showBody,String(t))}get showTabNavigator(){return this.getProcessedValue(A.showTabNavigator)}set showTabNavigator(t){t!=null&&this.setProperty(A.showTabNavigator,String(t))}async getControls(t){let n=[];if(this.rows){for(let r of this.rows)if(r.cells)for(let i of r.cells)i.control&&n.push(await i.control.toJSON(t))}return n}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 yi,Tl=B(()=>{"use strict";Dn();Sr();Re();pu();yi=class e extends Nr{constructor(t,n){super(t,n)}getTitle(t){for(let n of this.getAllTitles())if(+n.getProperty(A.LCID)===t)return n.getProperty(A.text);return null}getAllTitles(){let t=this.getChildren(D.Titles);return t.length===0?[]:t[0].getChildren(D.Title)}setTitle(t,n){for(let i of this.getAllTitles())if(+i.getProperty(A.LCID)===n){i.setProperty(A.text,t);return}let r=new e(D.Title,null);r.setProperty(A.text,t),r.setProperty(A.LCID,String(n)),this.addGrandChild(D.Titles,r)}get Sequence(){return+this.getProperty(A.Sequence)}set Sequence(t){this.setProperty(A.Sequence,t.toString())}get Area(){return this.getProperty(A.Area)}set Area(t){this.setProperty(A.Area,t)}set Id(t){this.setProperty(A.Id,t)}get Id(){return this.getProperty(A.Id)}get id(){return new H(this.Id??"",!0)}set id(t){this.Id=t.guidString}get Show(){return!0}get Icon(){return this.getProperty(A.icon)}set Icon(t){t=t||Q.EmptyString,this.setProperty(A.icon,t)}updateCommonProperties(t,n){this.Area=t.Area,this.Sequence=t.Sequence,this.setTitle(t.getDisplayName(n),n)}}});var fm,sG=B(()=>{"use strict";(function(e){e[e.NavLinkNotAvailable=-1]="NavLinkNotAvailable",e[e.NavLinkIdConflict=-2]="NavLinkIdConflict",e[e.NavBarNotAvailable=-3]="NavBarNotAvailable"})(fm||(fm={}))});var hy,uG=B(()=>{"use strict";En();Re();Tl();sG();hy=class extends yi{constructor(t){super(D.formNavBar,t)}addChildElement(t){this.addChild(t)}getAllActiveNavBarChildren(){return this.getAllChildren().filter(r=>r.Show)}getAllInActiveActiveNavBarChildren(){return this.getAllChildren().filter(r=>!r.Show)}get AllRelationShipItems(){return this.getChildren("NavBarByRelationshipItem")}get AllNavLinkItems(){return this.getChildren("NavBarItem")}removeNavLink(t){let n=this.getNavBarLinkItemById(t);return F.IsNullOrUndefined(n)?fm.NavLinkNotAvailable:n.length===1?this.deleteChild(n[0]):fm.NavLinkIdConflict}getRelationShipItemsByArea(t){let n=this.AllRelationShipItems,r=[];for(let i of n)i.Area===t&&i.Show===!0&&r.push(i);return r}getNavBarRelationShipItemsByNavId(t){return this.AllRelationShipItems.filter(r=>r.Id===t)}getNavBarLinkItemById(t){let n=this.AllNavLinkItems.filter(r=>r.Id===t);return n.length>0?n:null}getAllActiveChildrenForGivenArea(t){let n=this.getAllChildren(),r=[];for(let i of n)i.Area===t&&i.Show&&r.push(i);return r}}});var Tt,t0e,lG,B2e,Sd,YS=B(()=>{"use strict";Dn();Re();Tl();(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"})(Tt||(Tt={}));t0e=new Map([[Tt.Info,"Info"],[Tt.Sales,"Sales"],[Tt.Service,"Service"],[Tt.Marketing,"Marketing"],[Tt.ProcessCenter,"ProcessCenter"]]),lG=new Map([["Info",Tt.Info],["Sales",Tt.Sales],["Service",Tt.Service],["Marketing",Tt.Marketing],["ProcessCenter",Tt.ProcessCenter]]),B2e=new Map([[Tt.Info,9e3],[Tt.Sales,9200],[Tt.Service,9400],[Tt.Marketing,9600],[Tt.ProcessCenter,9800],[Tt.InternetMarketing,1e4],[Tt.Async,10200]]),Sd=class extends yi{constructor(t,n){super(D.formNavBarArea,n)}setDefaultPropertiesByType(t,n,r){this.AreaId=t0e.get(t);let i=r?.(`navBarArea.title.${this.AreaId}`)??this.AreaId;this.setTitle(i,n)}get ParentNavigation(){return this.getAncestor(D.formNavigation)}get AreaId(){return this.getProperty(A.Id)}set AreaId(t){this.setProperty(A.Id,t)}get id(){return new H(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 Nd,QS=B(()=>{"use strict";Re();Tl();Nd=class extends yi{constructor(t,n){super(D.formNavBarAreas,n)}get AllNavBarAreaItems(){return this.getChildren(D.formNavBarArea)}get ParentNavigation(){return this.getAncestor(D.formNavigation)}addNavBarArea(t){this.addChild(t)}}});var gy,cG=B(()=>{"use strict";En();Re();Tl();gy=class extends yi{RelationshipNameUCIRuntime;constructor(t){super(D.formNavBarByRelationshipItem,t)}get RelationshipName(){return this.getProperty(A.RelationshipName)}set RelationshipName(t){this.setProperty(A.RelationshipName,t)}set Show(t){this.setProperty(A.Show,String(t))}get Show(){let t=this.getProperty(A.Show);return F.IsNullOrUndefined(t)||t==="true"}get TitleResourceId(){return this.getProperty(A.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 yy,dG=B(()=>{"use strict";Re();Tl();yy=class extends yi{constructor(t){super(D.formNavBarItem,t)}get Url(){return this.getProperty(A.url)}set Url(t){this.setProperty(A.url,t)}}});var by,fG=B(()=>{"use strict";Dn();Re();YS();QS();Tl();by=class extends yi{constructor(t,n){super(t,n)}getNavBarAreaByAreaName(t){let n=this.navBarAreas.AllNavBarAreaItems.filter(r=>r.AreaId===t);return n.length===0?null:n[0]}get navBarAreas(){return this.getFirstChild(D.formNavBarAreas)}setDefaultNavBarAreas(t,n){let r=[Tt.Info,Tt.Sales,Tt.Service,Tt.Marketing,Tt.ProcessCenter];if(this.navBarAreas){let i=this.navBarAreas?.AllNavBarAreaItems;if(i&&i.length>0){let o=new Set(i.map(a=>lG.get(a.AreaId)));r=r.filter(a=>!o.has(a))}}else{let i=new Nd(D.formNavBarAreas,this);i.isTransient=!0,this.addChild(i)}return r.length>0?(r.forEach(i=>{let o=new Sd(D.formNavBarArea,this.navBarAreas);o.setDefaultPropertiesByType(i,t,n),this.navBarAreas.addNavBarArea(o)}),!0):!1}get navBar(){return this.getFirstChild(D.formNavBar)}get id(){return new H(DC,!0)}replaceNavAreaToGivenIndex(t,n){this.navBarAreas?.AllNavBarAreaItems.indexOf(n)!==-1&&(this.deleteFirstGrandChildOfName(D.formNavBarAreas,n),this.addGrandChildAtIndex(D.formNavBarAreas,n,t))}async getNavBarAreasJSON(t){let n=[],r=[];if(this.navBarAreas?.AllNavBarAreaItems){for(let o of this.navBarAreas.AllNavBarAreaItems)r.push(o.toJSON(t));n=await Promise.all(r)}return n}async getNavBarRelationshipItemsJSON(t){let n=[],r=[];if(this.navBar?.AllRelationShipItems){for(let i of this.navBar.AllRelationShipItems)r.push(i.toJSON(t));n=await Promise.all(r)}return n}async toJSON(t){let n=await this.getNavBarAreasJSON(t),r=await this.getNavBarRelationshipItemsJSON(t);return{NavBarAreas:{NavBarAreas:n},NavBarByRelationshipItems:r,NavBarItems:[],NavPaneIsvItems:{NavBarIsvItems:[]},ShowEmptyNavBarAreas:t.formModelService.showHiddenElements}}}});var pG={};Fi(pG,{ControlType:()=>to,DeserializationService:()=>eN,DeserializationServiceScope:()=>ZS,DeserializedFormElementNode:()=>bi});var XS,bi,ZS,to,eN,jS=B(()=>{"use strict";XS=Xe(vl());Dn();En();Sr();td();PC();bl();X2();I1();Bp();nG();um();sy();sm();US();Re();Re();rG();Jn();Io();qS();iG();oG();BS();VS();aG();WS();zS();lm();cy();uG();YS();QS();cG();dG();fG();bi=class extends Se{constructor(t,n){super(t,n)}insertProperty(t,n){this.addProperty(t,n)}insertChild(t){this.addChild(t)}},ZS="DeserializationService";(function(e){e.Grid="Grid",e.Lookup="Lookup",e.Base="Base"})(to||(to={}));eN=class{lcid;constructor(t){this.lcid=t}deSerializeFormXml(t,n,r,i,o,a,s,u,l,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,XS.trackErrorTrace)(Vr,{eventName:ZS,eventData:{error:p}}),new Error(p)}let f=this.createFormModel(d.item(0),n,r,i,o,a,s,u,l,c);return F.IsNullOrUndefined(f.displayCondition)&&s!==Pn.Dialog&&this.appendDefaultDisplayCondition(f),f}upsertFieldCount(t,n){let r=wl.getNecessaryLookUpTable(n),i=1;r.containsKey(t)&&(i+=r.getValue(t)),r.upsert(t,i)}appendDefaultDisplayCondition(t){let n='<DisplayConditions Order="0" FallbackForm="true"><Everyone/></DisplayConditions>';if(!F.IsNullOrUndefined(t)){let r=F.ParseXml(n);r!==null&&this.populateElementChildren(t,r.childNodes)}}createFormModel(t,n,r,i,o,a,s,u,l,c){let d=new dy(n,r,i,o,a,s,u,l,c);return this.populateElementProperties(d,t.attributes),this.populateElementChildren(d,t.childNodes),s===Pn.Main&&(this.insertHeaderFooterElementProperties(D.formHeader,d,d.header),this.insertHeaderFooterElementProperties(D.formFooter,d,d.footer)),d}insertHeaderFooterElementProperties(t,n,r){if(F.IsNullOrUndefined(r)){let i=t===D.formHeader?new dm(n,!0):new cm(n,!0);bi.prototype.insertProperty.call(i,A.id,"{"+H.NewGuid()+"}"),bi.prototype.insertProperty.call(i,A.Fieldlabelposition,"Top"),bi.prototype.insertProperty.call(i,A.columnName,xt.MarginalControlColumns),bi.prototype.insertProperty.call(i,A.LabelWidth,xt.LabelWidth),bi.prototype.insertProperty.call(i,A.Fieldlabelalignment,"Left");let o=null,a=new _l(o);for(let s=0;s<i.maxColumns;s++){let u=new gi(a);bi.prototype.insertProperty.call(u,A.id,"{"+H.NewGuid()+"}"),u.setDisplayName(Q.EmptyString,this.lcid),bi.prototype.insertProperty.call(u,A.showlabel,"false"),a.addCell(u)}i.appendRow(a),t===D.formHeader?n.header=i:n.footer=i}}deSerializeFormXmlNode(t,n){if(t&&t.nodeValue&&(t.nodeType===Node.TEXT_NODE||t.nodeType===Node.CDATA_SECTION_NODE))return new bi(`<${t.nodeValue}`,n);if(t.nodeType===Node.COMMENT_NODE)return;let r=this.createModelNode(t,n);return this.populateElementProperties(r,t.attributes),this.populateElementChildren(r,t.childNodes),r}populateElementProperties(t,n){if(!n){let r="attributes is undefined for element: "+t.getNodeName();throw(0,XS.trackErrorTrace)(Vr,{eventName:ZS,eventData:{error:r}}),new Error(r)}for(let r=0;r<n.length;r++){let i=n.item(r);i&&(bi.prototype.insertProperty.call(t,i.name,i.value),t.getNodeName()===D.formCell&&i.name===A.auto&&i.value==="true"&&t.setAutoExpandDetailsForTab())}}populateElementChildren(t,n){for(let r=0;r<n.length;r++){let i=n.item(r),o=this.deSerializeFormXmlNode(i,t);o&&bi.prototype.insertChild.call(t,o)}}createModelNode(t,n){switch(t.nodeName){case D.form:throw new Error("Form node shouldn't be created using this method");case D.formTab:return new fs(n);case D.formColumn:return new mu(n);case D.formHeader:return new dm(n,!1);case D.formFooter:return new cm(n,!1);case D.formSection:return new ga(D.formSection,n);case D.formRow:return new _l(n);case D.formCell:return new gi(n);case D.formControl:let r=t.attributes,i=t.childNodes.length>0?t.childNodes[0].childNodes:null,o;for(let s=0;s<r.length;s++){let u=r.item(s);if(u.name===A.indicationOfSubgrid&&u.value==="true"||u.name===A.classid&&(u.value?.toLocaleUpperCase()===`{${k.SubgridControl}}`||u.value?.toLocaleUpperCase()===`{${k.ReferencePanelSubgridControl}}`))o=to.Grid;else if(u.name===A.classid&&u.value?.toLocaleUpperCase()===`{${k.LookupControl}}`)o=to.Lookup;else if(u.name===A.classid&&u.value?.toLocaleUpperCase()===`{${k.CustomControl}}`)for(let l=0;l<i?.length;l++)i[l].nodeName===A.DefaultViewId&&(o=to.Lookup)}return o===to.Grid?new wd(n):o===to.Lookup?new Ed(n):new Do(n);case D.formEvent:return new vd(n,Q.EmptyString);case D.dependency:return this.populateDependencyTable(t),new bd(n,Q.EmptyString);case D.Handler:let a=[];return new my(a,n);case D.formNavigation:return new by(t.nodeName,n);case D.formNavBarArea:return new Sd(t.nodeName,n);case D.formNavBarAreas:return new Nd(t.nodeName,n);case D.formNavBar:return new hy(n);case D.formNavBarByRelationshipItem:return new gy(n);case D.formNavBarItem:return new yy(n);case D.formDisplayConditions:return new py(n);case D.library:return new Ad(n,Q.EmptyString,Q.EmptyString);case D.controlDescription:return new $0(n);case D.customControl:return this.populateCustomControlConfigurationId(t),new j0(n);default:return new bi(t.nodeName,n)}}populateDependencyTable(t){let n=t.attributes;for(let r=0;r<n.length;r++){let i=n.item(r);i.name===A.id&&this.upsertFieldCount(i.value,fa.DependencyFieldTable)}}populateCustomControlConfigurationId(t){let n=t.attributes;for(let r=0;r<n.length;r++){let i=n.item(r);if(i.name===A.id){let o=new H(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===A.ForControl){let u=s.value.substr(1,i.value.length-2);An.CustomControlIdMap.upsert(u,o);break}}break}}}}});var mG={};Fi(mG,{SerializationService:()=>tN,SerializationServiceScope:()=>n0e,SerializedFormElementNode:()=>_d});var n0e,_d,tN,hG=B(()=>{"use strict";Sr();Jn();Io();HS();n0e="SerializationService",_d=class extends Se{fetchNodeName(){return this.getNodeName()}enumerateProperties(){return this.getAllProperties()}enumerateChildren(){return this.getAllChildren()}},tN=class{langCode;constructor(t){this.langCode=t}serializeFormXmlNode(t){let n=_d.prototype.fetchNodeName.call(t);if(n.charAt(0)===cs.StartTag)return Q.EscapeXml(n.substr(1),!1);if(t.isTransient&&!t.isDirty())return Q.EmptyString;let r=_d.prototype.enumerateProperties.call(t),i=_d.prototype.enumerateChildren.call(t);if(!(t instanceof Il)){let o=`<${n}`;if(r.length!==0&&(o+=` ${this.getPropertiesString(r)}`),i.length===0)o+=" />";else{let a=Q.EmptyString;for(let s of i)a+=this.serializeFormXmlNode(s);o+=`>${a}</${n}>`}return o}return Q.EmptyString}getPropertiesString(t){let n=Q.EmptyString;return t.forEach((r,i)=>{i!==0&&(n+=" "),n+=`${r.key}="${Q.EscapeXml(r.value,!0)}"`}),n}}});var vy=C(Id=>{"use strict";Object.defineProperty(Id,"__esModule",{value:!0});Id.completeRecordAsStored=Id.completeLabelsAsStored=void 0;var nN=ja(),r0e="E7A81278-8635-4D9E-8D4D-59480B391C5B",i0e=new Set(["tab","section","cell"]);function Po(e){let t=[];for(let n=e.firstChild;n;n=n.nextSibling)n.nodeType===1&&t.push(n);return t}function hu(e,t){return Po(e).find(n=>n.tagName===t)}function bG(e,t){return e.length===t.length&&e.every((n,r)=>n.tagName===t[r].tagName)}function rN(e){let t=hu(e,"control");return t?(t.getAttribute("datafieldname")||"")!==""?!0:(t.getAttribute("classid")||"").replace(/[{}]/g,"").toUpperCase()===r0e:!1}function iN(e,t){var n,r;let i=((n=hu(e,"control"))===null||n===void 0?void 0:n.getAttribute("id"))||"";return i!==""&&i===(((r=hu(t,"control"))===null||r===void 0?void 0:r.getAttribute("id"))||"")}function o0e(e,t,n){if(hu(e,"labels"))return;let r=Po(e),i=Po(t),o=i[0];if(!o||o.tagName!=="labels"||i.length!==r.length+1||!bG(r,i.slice(1)))return;let a=Po(o);if(!(a.length===0||a.some(u=>u.tagName!=="label"||!u.hasAttribute("description")||!u.hasAttribute("languagecode"))||!(!n&&e.tagName==="cell"&&rN(e)&&iN(e,t))&&a.some(u=>u.getAttribute("description")!=="")))return o}function a0e(e,t){let n=s0e(e.ownerDocument,t),r=Po(e)[0];r?e.insertBefore(n,r):e.appendChild(n)}function s0e(e,t){let n=e.createElement("labels");for(let r of Po(t))n.appendChild(vG(e,r));return n}function vG(e,t){let n=e.createElement("label");for(let r=0;r<t.attributes.length;r+=1){let{name:i,value:o}=t.attributes[r];(i==="description"||i==="languagecode")&&n.setAttribute(i,o)}return n}function gG(e,t){let n=hu(e,"labels");return n?Po(n).find(r=>r.tagName==="label"&&r.getAttribute("languagecode")===String(t)):void 0}function u0e(e,t,n){if(e.tagName!=="cell"||!rN(e)||!iN(e,t))return!1;let r=gG(e,n),i=gG(t,n),o=i?.getAttribute("description")||"";return!r||!r.hasAttribute("description")||(r.getAttribute("description")||"")!==""||o===""?!1:(r.setAttribute("description",o),!0)}function l0e(e,t){if(e.tagName!=="cell"||!rN(e)||!iN(e,t))return;let n=hu(e,"labels"),r=hu(t,"labels");if(!n||!r)return;let i=Po(n),o=Po(r),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 u=new Set,l=0,c=[],d=[];for(let f of o){let p=f.getAttribute("languagecode")||"";if(u.has(p))return;u.add(p);let m=s.get(p);if(!m){d.push(f);continue}if((m.getAttribute("description")||"")!==(f.getAttribute("description")||""))return;l+=1,c.push(...d.map(h=>({label:h,before:m}))),d=[]}return c.push(...d.map(f=>({label:f}))),l===i.length?c:void 0}function wG(e,t,n,r,i){if(e.tagName===t.tagName){if(i0e.has(e.tagName)){let o=o0e(e,t,i);if(o&&(a0e(e,o),r.changed=!0),i){yG(e,t,n,r,i);return}u0e(e,t,n)&&(r.changed=!0);let a=l0e(e,t),s=hu(e,"labels");if(a&&s){for(let{label:u,before:l}of a){let c=vG(e.ownerDocument,u);l?s.insertBefore(c,l):s.appendChild(c)}r.changed=!0}}yG(e,t,n,r,i)}}function yG(e,t,n,r,i){let o=Po(e),a=Po(t);bG(o,a)&&o.forEach((s,u)=>wG(s,a[u],n,r,i))}function EG(e,t,n,r={}){if(e===t)return e;let i,o;try{i=(0,nN.parseXmlRoot)(e,""),o=(0,nN.parseXmlRoot)(t,"")}catch{return e}let a={changed:!1};return wG(i,o,n,a,r.emptyInsertionsOnly===!0),a.changed?(0,nN.serializeNode)(i):e}Id.completeLabelsAsStored=EG;function c0e(e,t,n){let r=e?.formxml,i=t?.formxml;if(typeof r!="string"||typeof i!="string")return e;let o=EG(r,i,n);return o===r?e:{...e,formxml:o}}Id.completeRecordAsStored=c0e});var BG=C(ke=>{"use strict";Object.defineProperty(ke,"__esModule",{value:!0});ke.pcfReadIssues=ke.pcfBindingIssues=ke.commitPcfState=ke.mayCommitPcfState=ke.reconcilePcfDescriptions=ke.customControlNeeds=ke.mintPcfIdentity=ke.planPcfBinding=ke.projectPcfBindings=ke.supportsPcfFormType=ke.storedBindingOf=ke.hasCustomControl=ke.sameAsStored=ke.readPcfDescription=ke.newPcfDescription=ke.editorText=ke.nativeClassFor=ke.pcfEntryLayout=void 0;var d0e=(Bp(),_i(T1)),f0e=Y(),AG=ft(),ee=dg(),p0e=kA(),Ye=Vi(),hs=["web","phone","tablet"],pm={web:"2",phone:"0",tablet:"1"},IG=new Map([["2","web"],["0","phone"],["1","tablet"]]),m0e=["phone","web","tablet"];function Ey(e){let t=new Set(e),n=m0e.filter(r=>!t.has(r));return{defaults:n.length===0?[null]:n,named:hs.filter(r=>t.has(r))}}ke.pcfEntryLayout=Ey;function Gr(e){return Array.isArray(e)?e:[]}function Cn(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function mm(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function aN(e){return{n:`<${e}`,a:[],c:[]}}function TG(e){return typeof e?.n=="string"&&e.n.startsWith("<")}function CG(e){let t=Gr(e.c);return t.length===1&&TG(t[0])&&(0,ee.rawText)(e)!==""?(0,ee.rawText)(e):void 0}function ro(e,t){return JSON.stringify(e)===JSON.stringify(t)}function OG(e){return`{${e.replace(/^\{|\}$/g,"").toUpperCase()}}`}function sN(e){try{let t=(0,d0e.mapFieldTypeToControl)(e.attributeTypeName,e.format);return t?OG(String(t)):void 0}catch{return}}ke.nativeClassFor=sN;var uN=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}]]),DG=new Set(["TwoOptions","Boolean"]),PG=new Set(["SingleLine.Text","SingleLine.TextArea","SingleLine.Email","SingleLine.Phone","SingleLine.URL","SingleLine.Ticker","Multiple"]),h0e=new Map([...[...PG].map(e=>[e,100]),["SingleLine.TextArea",2e3],["Multiple",1048576]]),g0e=/^[A-Za-z_][A-Za-z0-9_.-]*$/;function RG(e){return g0e.test(e)&&e!=="__proto__"}function lN(e){return e!==void 0&&(e==="Enum"||uN.has(e)||DG.has(e)||PG.has(e))}function kG(e){return typeof e=="number"?e:e!==""&&!Number.isNaN(Number(e))?Number(e):void 0}function hm(e,t){let n=e!==void 0?uN.get(e):void 0;if(n&&typeof t!="boolean"){let r=kG(t);if(r!==void 0)return r.toFixed(n.digits)}return typeof t=="boolean"?t?"true":"false":String(t)}ke.editorText=hm;function y0e(e,t,n){var r;let i=[];for(let o of e.properties){let a=o.name,s;if(o.isPrimary?s=t:o.usage==="input"&&mm(n,a)?s=hm(o.defaultType,n[a]):s=(r=o.defaultValue)!==null&&r!==void 0?r:"",s==="")continue;let u=[];o.defaultType&&u.push(["type",o.defaultType]),!o.isPrimary&&(o.defaultType==="Enum"||o.usage==="input")&&u.push(["static","true"]),i.push({n:a,a:u,c:[aN(s)]})}return i}function $G(e,t,n,r,i){var o,a;let s=(o=r.formFactors)!==null&&o!==void 0?o:hs.filter(d=>cN(i).has(d)),u=Ey(s),l=y0e(i,t,(a=r.parameters)!==null&&a!==void 0?a:{}),c=d=>JSON.parse(JSON.stringify(d));return{n:"controlDescription",a:[["forControl",e]],c:[...u.defaults.map(d=>({n:"customControl",a:d===null?[["id",n]]:[["id",n],["formFactor",pm[d]]],c:[{n:"parameters",a:[],c:[{n:"datafieldname",a:[],c:[aN(t)]}]}]})),...u.named.map(d=>({n:"customControl",a:[["name",r.name],["formFactor",pm[d]]],c:[{n:"parameters",a:[],c:c(l)}]}))]}}ke.newPcfDescription=$G;function cN(e){return new Set(hs.filter(t=>e.availableOn[t]))}function wy(e){var t;let n=Gr(e.c);if(n.length!==1||((t=n[0])===null||t===void 0?void 0:t.n)!=="parameters"||Gr(n[0].a).length>0)return;let r=Gr(n[0].c);return r.every(i=>Cn(i)&&!TG(i))?r:void 0}function Ol(e){let t=Gr(e?.c);if(t.length===0||!t.every(m=>Cn(m)&&m.n==="customControl"))return;let n=t.findIndex(m=>(0,ee.rawAttr)(m,"name")!==void 0);if(n<=0)return;let r=t.slice(n),i=(0,ee.rawAttr)(r[0],"name"),o=[];for(let m of r){let h=Gr(m.a),g=h.length===2?IG.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=Ey(o);if(!ro(a.named,o)||i==="")return;let s=wy(r[0]);if(!s||!r.every(m=>ro(wy(m),s)))return;let u=t.slice(0,n);if(u.length!==a.defaults.length)return;let l=(0,ee.rawAttr)(u[0],"id"),c;for(let m=0;m<u.length;m+=1){let h=a.defaults[m],g=h===null?[["id",l??""]]:[["id",l??""],["formFactor",pm[h]]],y=wy(u[m]),b=y?.length===1&&y[0].n==="datafieldname"&&Gr(y[0].a).length===0?CG(y[0]):void 0;if(!l||!ro(Gr(u[m].a),g)||b===void 0||c!==void 0&&b!==c)return;c=b}let d={},f={},p;for(let m of s){let h=Gr(m.a),g=CG(m),y=h.map(b=>b[0]);if(g===void 0||!RG(m.n)||mm(d,m.n)||m.n===p)return;if((0,ee.rawAttr)(m,"static")===void 0){if(p!==void 0||g!==c||!(y.length===0||ro(y,["type"])))return;p=m.n;continue}if((0,ee.rawAttr)(m,"static")!=="true"||!(ro(y,["static"])||ro(y,["type","static"])))return;d[m.n]=g,f[m.n]=(0,ee.rawAttr)(m,"type")}if(!(p===void 0||c===void 0||l===void 0))return{binding:{name:i,...Object.keys(d).length>0?{parameters:d}:{},...o.length===hs.length?{}:{formFactors:o}},fieldName:c,nativeClass:l,parameterTypes:f,boundProperty:p}}ke.readPcfDescription=Ol;function LG(e,t,n){return e===t?!0:typeof e!="string"&&(t===String(e)||t===hm(n,e))}function MG(e){let t=e.formFactors;return t===void 0?[...hs]:Array.isArray(t)?hs.filter(n=>t.includes(n)):[]}function oN(e,t){var n,r,i;if(e.name!==t.binding.name||!ro(MG(e),(n=t.binding.formFactors)!==null&&n!==void 0?n:hs))return!1;let o=(r=e.parameters)!==null&&r!==void 0?r:{},a=(i=t.binding.parameters)!==null&&i!==void 0?i:{},s=Object.keys(o);return s.length!==Object.keys(a).length?!1:s.every(u=>mm(a,u)&&LG(o[u],a[u],t.parameterTypes[u]))}ke.sameAsStored=oN;function Rn(e){return Cn(e)&&e.customControl!==void 0}ke.hasCustomControl=Rn;function ms(e,t){var n;return t?Gr((n=(0,ee.descriptionsRegion)(e))===null||n===void 0?void 0:n.node.c).filter(r=>r?.n==="controlDescription"&&(0,ee.normGuid)((0,ee.rawAttr)(r,"forControl"))===t):[]}function dN(e,t){let n=ms(e.bag,(0,ee.controlUniqueId)(t));return n.length===1?Ol(n[0]):void 0}ke.storedBindingOf=dN;function fN(e){let t=(0,ee.effectiveFormType)(e);return t==="Main"||t==="QuickCreate"}ke.supportsPcfFormType=fN;function b0e(e){if(!fN(e))return;let t=(0,ee.controlUniqueIds)(e);for(let{cell:n}of(0,ee.typedCellSites)(e)){let r=n.control;if(!Cn(r)||!r.fieldName||!ps(r.classId)||t.get((0,ee.controlUniqueId)(r))!==1)continue;let i=dN(e,r);i&&i.fieldName===r.fieldName&&(r.customControl=JSON.parse(JSON.stringify(i.binding)))}}ke.projectPcfBindings=b0e;function ps(e){return typeof e=="string"&&e.replace(/^\{|\}$/g,"").toUpperCase()===ee.CUSTOM_CONTROL_CLASS_ID}var no=(e,t)=>({kind:"refused",rule:e,message:t});function v0e(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)&&!ps(e)}function SG(e,t,n){var r,i;let o=Ol(n);if(!o)return no("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 no("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 no("pcf-binding-control-swap",`the binding uses "${o.binding.name}": to use another control, remove customControl, push, then add it`);let a=Cn(t.parameters)?t.parameters:{},s=(r=o.binding.parameters)!==null&&r!==void 0?r:{},u=Object.keys(a).sort();if(!ro(u,Object.keys(s).sort()))return no("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 l=u.filter(g=>!LG(a[g],s[g],o.parameterTypes[g])),c=l.find(g=>hm(o.parameterTypes[g],a[g]).trim()==="");if(c!==void 0)return no("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=MG(t),f=(i=o.binding.formFactors)!==null&&i!==void 0?i:[...hs],p=d.filter(g=>!f.includes(g)),m=f.filter(g=>!d.includes(g));if(l.length===0&&p.length===0&&m.length===0)return{kind:"unchanged"};let h=l.find(g=>!lN(o.parameterTypes[g]));if(h!==void 0){let g=o.parameterTypes[h];return no("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)&&!v0e(o.nativeClass)?no("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:n,stored:o,changed:l,factors:d,added:p,removed:m}}function w0e(e,t){return t&&(0,ee.typedCellSites)(e).find(({cell:r})=>Rn(r.control)&&(0,ee.controlUniqueId)(r.control)===t)?{descriptions:ms(e.bag,t)}:void 0}function xG(e,t){let n=new Map,r=E0e(e),i=new Set,o=new Map,a=l=>{let c=o.get(l);return c||(c={before:[],now:[]},o.set(l,c)),c},s=(l,c)=>({cell:S0e(l),uid:(0,ee.controlUniqueId)(c),bound:Rn(c)});for(let{cell:l}of(0,ee.typedCellSites)(e)){let c=l.control;Cn(c)&&typeof c.id=="string"&&c.id&&a(c.id).now.push({...s(l,c),control:c})}for(let{cell:l}of(0,ee.typedCellSites)(t)){let c=l.control;if(!Cn(c))continue;let d=s(l,c);d.bound&&d.uid&&i.add(d.uid),typeof c.id=="string"&&c.id&&a(c.id).before.push(d)}let u=(l,c)=>{let d=l.filter(f=>f.cell===c);return d.length===1?d[0]:void 0};for(let[l,{before:c,now:d}]of o){let f=c.filter(O=>O.bound&&O.uid!==""&&!r.has(O.uid));if(f.length===0||d.length===0)continue;let p=[...c],m=O=>{let v=p.findIndex(O);return v<0?void 0:p.splice(v,1)[0]},g=d.filter(O=>!O.bound||O.uid===""?!0:m(v=>v.bound&&v.uid===O.uid)!==void 0?!1:!i.has(O.uid)).filter(O=>{let v=O.cell?u(c,O.cell):void 0;return!v||!u(d,O.cell)||!p.includes(v)?!0:(p.splice(p.indexOf(v),1),f.includes(v)&&O.uid!==v.uid&&NG(O.control)&&n.set(O.control,_G(v.uid)),!1)}),y=[],b=(O,v)=>{let N=O.uid===""?void 0:m(S=>S.uid===O.uid&&(!v||S.bound===O.bound));return N&&f.includes(N)&&y.push(N),N!==void 0},w=g.filter(O=>!b(O,!0)).filter(O=>!b(O,!1)&&NG(O.control)),_=f.filter(O=>p.includes(O));if(w.length===0||_.length===0&&y.length===0)continue;let I=[..._,...y],T=_.length===1&&w.length===1&&p.length===1?_G(_[0].uid):`the controls with id "${l}" cannot all be matched to those last synced \u2014 their cells do not tell them apart \u2014 and ${I.map(O=>`{${O.uid}}`).join(", ")} no longer ${I.length===1?"names":"name"} a control: which control held ${I.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 O of w)n.set(O.control,T)}return n}function E0e(e){let t=(0,ee.controlUniqueIds)(e),n=new Map;for(let{cell:i}of(0,ee.typedCellSites)(e)){let o=Cn(i.control)?(0,ee.controlUniqueId)(i.control):"";o&&!n.has(o)&&n.set(o,i.control)}let r=new Set;for(let[i,o]of t){let a=n.get(i);(a===void 0||Rn(a)||o>1)&&r.add(i)}return r}function NG(e){return Rn(e)||e.genPage===void 0&&ps((0,ee.effectiveClassId)(e))}function A0e(e,t){let n=o=>(0,ee.typedCellSites)(o).flatMap(({cell:a,pointer:s})=>{let u=a.control;if(!Cn(u)||Rn(u)||u.genPage!==void 0||!ps((0,ee.effectiveClassId)(u)))return[];let l=(0,ee.controlUniqueId)(u);return l===""||ms(o.bag,l).length===0?[{control:u,pointer:`${s}/control`}]:[]}),r=o=>`${String(o.id)}\0${(0,ee.controlUniqueId)(o)}`,i=n(t).map(({control:o})=>r(o));return n(e).filter(({control:o})=>{let a=i.indexOf(r(o));return a<0?!0:(i.splice(a,1),!1)})}var C0e="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 _G(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 S0e(e){let t=typeof e.id=="string"?e.id.trim():"";return(0,ee.normGuid)(t)||t.toLowerCase()}function gm(e,t,n,r){let i=t.customControl,o=(0,ee.controlUniqueId)(t),a=ms(e.bag,o),s=n?xG(e,n).get(t):void 0;if(s!==void 0)return no("pcf-binding-unique-id",s);let u=n?w0e(n,o):void 0;if(u){let c=u.descriptions,d=c.length===1?Ol(c[0]):void 0;if(d&&d.fieldName!==t.fieldName)return no("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&&ro(c[0],a[0]))return SG(t,i,a[0]);let f=a.length===1?Ol(a[0]):void 0;return d&&f&&f.fieldName===t.fieldName&&oN(i,d)&&oN(i,f)?{kind:"unchanged"}:no("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 no("pcf-binding-other-control","the control already has a description the SDK cannot read as a binding; adding would replace it");let l=SG(t,i,a[0]);return r&&(l.kind==="edit"||l.kind==="unchanged")?l.kind==="unchanged"?l:no("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"):l}ke.planPcfBinding=gm;function FG(e){return e.kind==="edit"&&(e.changed.length>0||e.added.length>0)}function N0e(e){let t=r=>Rn(r.control)&&(!r.control.id||!r.id||(0,ee.authoredUniqueId)(r.control)===void 0);if(!(0,ee.typedCellSites)(e).some(({cell:r})=>t(r)))return e;let n=JSON.parse(JSON.stringify(e));for(let{cell:r}of(0,ee.typedCellSites)(n)){if(!t(r))continue;let i=r.control;i.id||(i.id=(0,AG.newId)()),r.id||(r.id=(0,AG.newId)()),(0,ee.authoredUniqueId)(i)===void 0&&(0,ee.setUniqueId)(i)}return n}ke.mintPcfIdentity=N0e;function _0e(e,t){let n=new Set,r=new Set;for(let{cell:i}of(0,ee.typedCellSites)(e)){let o=i.control;if(!Rn(o)||!Cn(o.customControl))continue;let a=o.customControl.name;if(typeof a!="string"||a===""||typeof o.fieldName!="string"||!o.fieldName)continue;let s=gm(e,o,t,!0);s.kind==="new"?(n.add(a),r.add(o.fieldName)):FG(s)&&n.add(a)}return{controls:[...n],columns:[...r],...r.size>0&&(0,ee.effectiveFormType)(e)==="QuickCreate"?{requireCreateEligibility:!0}:{}}}ke.customControlNeeds=_0e;function I0e(e,t,n){var r,i,o,a,s,u;let l=e.bag,c=new Map;for(let{cell:f,pointer:p}of(0,ee.typedCellSites)(e)){let m=f.control;if(!Rn(m)||!Cn(m.customControl))continue;let h=(0,ee.controlUniqueId)(m);h&&ms(l,h).length>0&&c.set(m,{plan:gm(e,m,t,!0),pointer:`${p}/control/customControl`})}let d=(0,ee.descriptionsRegion)(l);if(d&&t){let f=(0,ee.controlUniqueIds)(e),p=new Set,m=new Map;for(let{cell:h}of(0,ee.typedCellSites)(e)){let g=Cn(h.control)?(0,ee.controlUniqueId)(h.control):"";g&&!m.has(g)&&m.set(g,h.control)}for(let{cell:h}of(0,ee.typedCellSites)(t)){let g=h.control;if(!Rn(g))continue;let y=(0,ee.controlUniqueId)(g),b=ms(t.bag,y),E=ms(l,y);if(b.length!==1||E.length!==1||!ro(b[0],E[0])||!Ol(E[0]))continue;let w=m.get(y);if(w&&!Rn(w)){if(((r=f.get(y))!==null&&r!==void 0?r:0)>1)continue;let _=(o=(i=Ol(E[0]))===null||i===void 0?void 0:i.nativeClass)!==null&&o!==void 0?o:"";w.classId=_.replace(/^\{|\}$/g,"").toUpperCase(),T0e(w,"uniqueid"),p.add(y)}else!w&&!f.has(y)&&p.add(y)}p.size>0&&(d.node.c=Gr(d.node.c).filter(h=>!(h?.n==="controlDescription"&&p.has((0,ee.normGuid)((0,ee.rawAttr)(h,"forControl"))))))}for(let{cell:f}of(0,ee.typedCellSites)(e)){let p=f.control;if(!Rn(p)||!Cn(p.customControl))continue;ps(p.classId)||(p.classId=ee.CUSTOM_CONTROL_CLASS_ID);let m=(0,ee.controlUniqueId)(p);if(!m){if((0,ee.authoredUniqueId)(p)!==void 0)continue;m=(0,ee.setUniqueId)(p)}let h=c.get(p);if(h){if(h.plan.kind==="refused")throw new f0e.ValidationError("form",e.id,[(0,Ye.issue)(h.pointer,h.plan.rule,h.plan.message)]);h.plan.kind==="edit"&&O0e(h.plan,p.customControl);continue}let g=n?.control(p.customControl.name),y=n?.column(e.entityLogicalName,p.fieldName),b=y?.kind==="found"?sN(y.value):void 0;if(g?.kind!=="found"||!b)continue;d||(d={i:(0,ee.embedAppendIndex)(l),node:{n:"controlDescriptions",a:[],c:[]}},l.c.push(d));let E=((u=(s=Gr((a=p.bag)===null||a===void 0?void 0:a.a).find(_=>_[0]==="uniqueid"))===null||s===void 0?void 0:s[1])!==null&&u!==void 0?u:"").trim(),w=E.startsWith("{")?E:`{${m}}`;d.node.c.push($G(w,p.fieldName,b,p.customControl,g.value))}}ke.reconcilePcfDescriptions=I0e;function T0e(e,t){Cn(e.bag)&&(e.bag.a=Gr(e.bag.a).filter(n=>n[0]!==t))}function O0e(e,t){var n,r;let i=Gr(e.description.c),o=i.findIndex(g=>(0,ee.rawAttr)(g,"name")!==void 0),a=i.slice(0,o),s=i.slice(o),u=(n=t.parameters)!==null&&n!==void 0?n:{};for(let g of s)for(let y of(r=wy(g))!==null&&r!==void 0?r:[])e.changed.includes(y.n)&&(y.c=[aN(hm(e.stored.parameterTypes[y.n],u[y.n]))]);if(e.added.length===0&&e.removed.length===0)return;let l=g=>JSON.parse(JSON.stringify(g)),c=g=>{var y;let b=(0,ee.rawAttr)(g,"formFactor");return b===void 0?null:(y=IG.get(b))!==null&&y!==void 0?y:null},d=(0,ee.rawAttr)(a[0],"id"),f=(0,ee.rawAttr)(s[0],"name"),p=Ey(e.factors),m=p.defaults.map(g=>{let y=a.find(E=>c(E)===g);if(y)return y;let b=l(a[0]);return b.a=g===null?[["id",d]]:[["id",d],["formFactor",pm[g]]],b}),h=p.named.map(g=>{let y=s.find(E=>c(E)===g);if(y)return y;let b=l(s[0]);return b.a=[["name",f],["formFactor",pm[g]]],b});e.description.c=[...m,...h]}function D0e(e){return(0,ee.typedCellSites)(e).some(({cell:t})=>Rn(t.control))}ke.mayCommitPcfState=D0e;function P0e(e,t){var n;let r=JSON.parse(JSON.stringify(e)),i=!1;for(let{cell:o}of(0,ee.typedCellSites)(r)){let a=o.control;if(!Rn(a))continue;let s=dN(r,a);if(!s||s.fieldName!==a.fieldName)continue;let u=t(ee.CUSTOM_CONTROL_CLASS_ID),l=Gr((n=a.bag)===null||n===void 0?void 0:n.a).find(c=>c[0]==="classid");(!ps(a.classId)||a.type!==u||l!==void 0&&!ps(l[1])||!ro(a.customControl,s.binding))&&(ps(a.classId)||(a.classId=ee.CUSTOM_CONTROL_CLASS_ID),a.type=u,l&&!ps(l[1])&&(l[1]=OG(ee.CUSTOM_CONTROL_CLASS_ID)),a.customControl=JSON.parse(JSON.stringify(s.binding)),i=!0)}return i?r:e}ke.commitPcfState=P0e;var R0e=new Set(["name","parameters","formFactors"]);function k0e(e,t,n){let r=[],i=(0,ee.controlUniqueIds)(e);for(let{cell:o,pointer:a}of(0,ee.typedCellSites)(e)){let s=o.control;Rn(s)&&L0e(e,s,`${a}/control`,i,r,t,n?.atPush===!0)}return t&&M0e(e,t,r),r}ke.pcfBindingIssues=k0e;function $0e(e,t,n){let r=n.length;if(!Cn(e))return n.push((0,Ye.issue)(t,"pcf-binding-shape","customControl must be an object")),!1;for(let i of Object.keys(e))R0e.has(i)||n.push((0,Ye.issue)(`${t}/${i}`,"pcf-binding-unknown-key",`customControl has no "${i}"`));if((typeof e.name!="string"||e.name.trim()==="")&&n.push((0,Ye.issue)(`${t}/name`,"pcf-binding-shape","name must be the control's non-empty customcontrols name")),e.parameters!==void 0)if(!Cn(e.parameters))n.push((0,Ye.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)||n.push((0,Ye.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"&&hs.includes(a))&&new Set(i).size===i.length||n.push((0,Ye.issue)(`${t}/formFactors`,"pcf-binding-shape","formFactors must be distinct 'web', 'phone' and 'tablet', at least one"))}return n.length===r}function L0e(e,t,n,r,i,o,a){var s;let u=`${n}/customControl`,l=$0e(t.customControl,u,i);t.fieldName||i.push((0,Ye.issue)(u,"pcf-binding-unbound","a PCF binding needs a control bound to a column (fieldName)")),t.genPage!==void 0&&i.push((0,Ye.issue)(u,"pcf-binding-with-genpage","a control cannot embed a page and bind a PCF control")),fN(e)||i.push((0,Ye.issue)(u,"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,Ye.issue)(`${n}/classId`,"pcf-binding-class-id","classId must be a string"));let c=(0,ee.authoredUniqueId)(t),d=(0,ee.controlUniqueId)(t);if(c!==void 0&&!d?i.push((0,Ye.issue)(`${n}/bag`,"pcf-binding-unique-id","the control's uniqueid must be a GUID")):d&&((s=r.get(d))!==null&&s!==void 0?s:0)>1&&i.push((0,Ye.issue)(`${n}/bag`,"pcf-binding-unique-id","another control carries the same uniqueid")),!l)return;let f=gm(e,t,o,a);f.kind==="refused"&&i.push((0,Ye.issue)(u,f.rule,f.message))}function M0e(e,t,n){var r;let i=new Map,o=xG(e,t);for(let{cell:u,pointer:l}of(0,ee.typedCellSites)(e)){let c=Cn(u.control)?(0,ee.controlUniqueId)(u.control):"";if(c&&!i.has(c)&&i.set(c,{control:u.control,pointer:`${l}/control`}),Cn(u.control)&&!Rn(u.control)){let d=o.get(u.control);d!==void 0&&n.push((0,Ye.issue)(`${l}/control`,"pcf-binding-unique-id",d))}}let a=(0,ee.controlUniqueIds)(e);for(let{cell:u}of(0,ee.typedCellSites)(t)){if(!Rn(u.control))continue;let l=(0,ee.controlUniqueId)(u.control),c=i.get(l);!c||Rn(c.control)||(((r=a.get(l))!==null&&r!==void 0?r:0)>1?n.push((0,Ye.issue)(c.pointer,"pcf-binding-unique-id","another control carries this binding\u2019s uniqueid; removing the binding would delete its description too")):ro(ms(t.bag,l),ms(e.bag,l))?c.control.fieldName!==u.control.fieldName&&n.push((0,Ye.issue)(c.pointer,"pcf-binding-rebind","remove the binding, push, then bind the new column")):n.push((0,Ye.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(n.map(u=>u.pointer));for(let{pointer:u}of A0e(e,t))s.has(u)||n.push((0,Ye.issue)(u,"pcf-binding-unique-id",C0e))}var x0e=new Set(["Form.Card"]),F0e="MscrmControls.ModelForm.ModelFormControl";function UG(e,t){var n;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 r=e.properties;if(r.filter(s=>s.usage==="bound").length!==1)return"it has more than one bound property";let i=r.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=>!RG(s));if(o!==void 0)return`the property name "${o}" cannot be written as an element`;if(t===F0e||r.some(s=>s.defaultType!==void 0&&x0e.has(s.defaultType)))return"a property needs a special encoding";if(r.some(s=>s.usage==="output"&&s.defaultValue!==null&&s.defaultValue!==""))return"an output property has a default";let a=r.find(s=>s.usage==="input"&&!lN(s.defaultType));return a?`input "${a.name}" has a type the property editor does not write as text (${(n=a.defaultType)!==null&&n!==void 0?n:"none"})`:void 0}function U0e(e){return e.ofType!==null?[e.ofType]:e.ofTypeGroup}function qG(e,t,n=e.defaultType){if(n==="Enum")return e.enumValues.some(o=>o.value===String(t))?void 0:`must be one of ${e.enumValues.map(o=>`"${o.value}"`).join(", ")}`;let r=n!==void 0?uN.get(n):void 0;if(r){let o=typeof t=="boolean"?void 0:kG(t);return o===void 0||o<r.min||o>r.max?`must be a number from ${r.min.toFixed(r.digits)} through ${r.max.toFixed(r.digits)}`:void 0}if(n!==void 0&&DG.has(n))return t===!0||t===!1||t==="true"||t==="false"?void 0:"must be true or false";let i=n!==void 0?h0e.get(n):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 q0e(e,t,n){var r,i,o,a;let s={issues:[]},u=s.issues;for(let{cell:l,pointer:c}of(0,ee.typedCellSites)(e)){let d=l.control;if(!Rn(d)||!d.fieldName)continue;let f=d.customControl;if(!Cn(f)||typeof f.name!="string")continue;let p=`${c}/control/customControl`,m=gm(e,d,n,!0);if(m.kind==="edit"){FG(m)&&G0e(m,f,p,t,s);continue}if(m.kind!=="new")continue;let h=t?.control(f.name),g=t?.column((r=e.entityLogicalName)!==null&&r!==void 0?r:"",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"){u.push((0,Ye.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 y=UG(h.value,f.name);if(y){u.push((0,Ye.issue)(`${p}/name`,"pcf-binding-unsupported-control",`"${f.name}" is not supported: ${y}`));continue}let b=h.value.properties.find(N=>N.isPrimary),E=g.kind==="found"?g.value:void 0,w=E?(a=(0,p0e.manifestTypesForColumn)(E.attributeTypeName,E.format,E.formatName))!==null&&a!==void 0?a:[]:[];E!==void 0&&!E.isPrimaryId&&E.isValidForForm&&sN(E)!==void 0&&U0e(b).some(N=>w.includes(N))?(0,ee.effectiveFormType)(e)==="QuickCreate"&&E?.isValidForCreate!==!0&&u.push((0,Ye.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`)):u.push((0,Ye.issue)(p,"pcf-binding-incompatible-column",`"${f.name}" cannot be bound to "${d.fieldName}"`));let I=new Map(h.value.properties.filter(N=>N.usage==="input").map(N=>[N.name,N])),T=Cn(f.parameters)?f.parameters:{};for(let[N,S]of Object.entries(T)){let R=I.get(N);if(!R){u.push((0,Ye.issue)(`${p}/parameters/${N}`,"pcf-binding-unknown-parameter",`"${f.name}" has no input "${N}"`));continue}let x=qG(R,S);x&&u.push((0,Ye.issue)(`${p}/parameters/${N}`,"pcf-binding-parameter-value",`"${N}" ${x}`))}for(let N of I.values())N.required&&!mm(T,N.name)&&!N.defaultValue&&u.push((0,Ye.issue)(`${p}/parameters`,"pcf-binding-missing-parameter",`"${N.name}" is required`));let O=cN(h.value),v=Array.isArray(f.formFactors)?f.formFactors:void 0;(v?v.some(N=>!O.has(N)):O.size===0)&&u.push((0,Ye.issue)(`${p}/formFactors`,"pcf-binding-form-factor",`"${f.name}" is available on ${O.size===0?"no form factor":[...O].join(", ")}`))}return s}ke.pcfReadIssues=q0e;function B0e(e,t){return t===void 0||!lN(t)?!1:e.ofType!==null?e.ofType===t:e.ofTypeGroup.includes(t)}function V0e(e,t,n){var r,i;let o=UG(e,t);if(o)return`it is no longer supported (${o})`;let a=e.properties.find(d=>d.isPrimary);if(a?.name!==n.boundProperty)return`its bound property is now "${(r=a?.name)!==null&&r!==void 0?r:"none"}", not "${n.boundProperty}"`;let s=(i=n.binding.parameters)!==null&&i!==void 0?i:{},u=new Set(e.properties.filter(d=>d.usage==="input").map(d=>d.name)),l=Object.keys(s).find(d=>!u.has(d));if(l!==void 0)return`"${l}" is no longer one of its inputs`;let c=e.properties.find(d=>d.usage==="input"&&d.required&&!d.defaultValue&&!mm(s,d.name));return c?`it now requires "${c.name}", which the binding does not store`:void 0}function G0e(e,t,n,r,i){var o,a,s;let u=i.issues,l=r?.control(t.name);if(!l||l.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`,...l?.kind==="unavailable"?{cause:l.error}:{}});return}if(l.kind!=="found"){u.push((0,Ye.issue)(`${n}/name`,"PCF_CONTROL_NOT_FOUND",`no single installed control is named "${t.name}" (${l.kind})`));return}let c=V0e(l.value,t.name,e.stored);if(c){u.push((0,Ye.issue)(n,"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(l.value.properties.filter(h=>h.usage==="input").map(h=>[h.name,h])),f=u.length;for(let h of Object.keys((a=e.stored.binding.parameters)!==null&&a!==void 0?a:{})){let g=e.stored.parameterTypes[h];B0e(d.get(h),g)||u.push((0,Ye.issue)(`${n}/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(u.length>f)return;let p=(s=t.parameters)!==null&&s!==void 0?s:{};for(let h of e.changed){let g=qG(d.get(h),p[h],e.stored.parameterTypes[h]);g&&u.push((0,Ye.issue)(`${n}/parameters/${h}`,"pcf-binding-parameter-value",`"${h}" ${g}`))}let m=cN(l.value);e.added.some(h=>!m.has(h))&&u.push((0,Ye.issue)(`${n}/formFactors`,"pcf-binding-form-factor",`"${t.name}" is available on ${m.size===0?"no form factor":[...m].join(", ")}`))}});var r4=C(wi=>{"use strict";Object.defineProperty(wi,"__esModule",{value:!0});wi.classIdForAttributeType=wi.QUICK_VIEW_CLASS_ID=wi.NOTES_CLASS_ID=wi.SUBGRID_CLASS_ID=wi.formRegistration=wi.FormAdapter=void 0;var gs=(Dn(),_i(G2)),VG=(En(),_i(j2)),j0e=(Jn(),_i(z2)),kn=(Re(),_i(W2)),cn=(bl(),_i(H2)),W0e=(jS(),_i(pG)),z0e=(hG(),_i(mG)),$n=Us(),GG=mo(),vi=Vi(),H0e=mg(),Od=ft(),K0e=vy(),_r=dg(),ya=BG(),Td=Y(),bN=ae(),pN=Ga(),JG=fl(),J0e={[kn.FormType.Main]:"Main",[kn.FormType.QuickCreate]:"QuickCreate",[kn.FormType.QuickViewForm]:"QuickView",[kn.FormType.Card]:"Card"},Ay={Main:kn.FormType.Main,QuickCreate:kn.FormType.QuickCreate,QuickView:kn.FormType.QuickViewForm,Card:kn.FormType.Card},Y0e=new Map(Object.entries(cn.ControlClassId).map(([e,t])=>[String(t).toUpperCase(),e]));function vN(e){var t;return e&&(t=Y0e.get(e.toUpperCase()))!==null&&t!==void 0?t:"Unknown"}function ym(e){return e.getAllProperties().map(t=>[t.key,t.value])}function Dl(e){let t=new Map;for(let n of e.getAllProperties())t.has(n.key)||t.set(n.key,n.value);return t}function YG(e,t){return e.getAllChildren().find(n=>n.getNodeName()===t)}function wN(e,t){var n,r;let i=YG(e,"labels");if(!i)return"";let o=i.getAllChildren().filter(s=>s.getNodeName()==="label"),a=(n=o.find(s=>Dl(s).get("languagecode")===String(t)))!==null&&n!==void 0?n:o[0];return a&&(r=Dl(a).get("description"))!==null&&r!==void 0?r:""}function Q0e(e){let t=YG(e,"parameters"),n={};if(!t)return n;for(let r of t.getAllChildren()){let i=r.getNodeName();if(i.charAt(0)==="<"||i.charAt(0)==="#")continue;let o=r.getAllChildren()[0],a=o?o.getNodeName():"";a.charAt(0)==="<"&&(a=a.substring(1)),n[i]=a}return n}function QG(e){return/^1+$/.test(e)&&e.length>=1&&e.length<=4?e.length:1}function mN(e){let t=Math.min(Math.max(Math.trunc(e),1),4);return"1".repeat(t)}function bm(e){return String(e??"").replace(/[{}]/g,"")}function hN(e){return`{${bm(e)}}`}function gN(e,t){if(e===void 0||e==="")return t;let n=Number(e);return Number.isNaN(n)?t:n}function Sy(e,t,n){let r=e.getAllChildren(),i=r.findIndex(l=>l.getNodeName()===t),o=[];if(r.forEach((l,c)=>{c!==i&&o.push({i:c,node:(0,$n.rawFromNode)(l)})}),i<0)return{modeled:[],bag:{a:ym(e),c:o}};let a=r[i],s=[],u=[];return a.getAllChildren().forEach((l,c)=>{l.getNodeName()===n?s.push(l):u.push({i:c,node:(0,$n.rawFromNode)(l)})}),{modeled:s,bag:{a:ym(e),c:o,w:{n:a.getNodeName(),a:ym(a),c:u}}}}function XG(e,t,n){let r=[],i=[];return e.getAllChildren().forEach((o,a)=>{o.getNodeName()===t&&(!n||r.length===0)?r.push(o):i.push({i:a,node:(0,$n.rawFromNode)(o)})}),{modeled:r,bag:{a:ym(e),c:i}}}function jG(e,t){let{modeled:n,bag:r}=Sy(e,"tabs","tab");return{tabs:n.map(i=>X0e(i,t)),bag:r}}function X0e(e,t){var n,r;let i=Dl(e),{modeled:o,bag:a}=Sy(e,"columns","column");return{id:(n=i.get("id"))!==null&&n!==void 0?n:"",name:(r=i.get("name"))!==null&&r!==void 0?r:"",label:wN(e,t),expanded:i.get("expanded")==="true",visible:i.has("visible")?i.get("visible")==="true":!0,columns:o.map(s=>Z0e(s,t)),bag:a}}function Z0e(e,t){let n=Dl(e),{modeled:r,bag:i}=Sy(e,"sections","section");return{width:n.get("width"),sections:r.map(o=>eye(o,t)),bag:i}}function eye(e,t){var n,r,i;let o=Dl(e),{modeled:a,bag:s}=Sy(e,"rows","row");return{id:(n=o.get("id"))!==null&&n!==void 0?n:"",name:(r=o.get("name"))!==null&&r!==void 0?r:"",label:wN(e,t),visible:o.has("visible")?o.get("visible")==="true":!0,showLabel:o.get("showlabel")==="true",columns:QG((i=o.get("columns"))!==null&&i!==void 0?i:"1"),rows:a.map(u=>tye(u,t)),bag:s}}function tye(e,t){let{modeled:n,bag:r}=XG(e,"cell",!1);return{cells:n.map(i=>nye(i,t)),bag:r}}function nye(e,t){var n;let r=Dl(e),{modeled:i,bag:o}=XG(e,"control",!0),a=wN(e,t),s=r.get("showlabel")==="true",u=i[0]?rye(i[0],a,s):null;return{id:(n=r.get("id"))!==null&&n!==void 0?n:"",visible:r.has("visible")?r.get("visible")==="true":!0,colspan:gN(r.get("colspan"),1),rowspan:gN(r.get("rowspan"),1),control:u,bag:o}}function rye(e,t,n){var r,i;let o=Dl(e),a=bm((r=o.get("classid"))!==null&&r!==void 0?r:""),s=o.get("datafieldname");return{id:(i=o.get("id"))!==null&&i!==void 0?i:"",classId:a,fieldName:s||null,type:vN(a),isRequired:o.get("isrequired")==="true",isReadOnly:o.get("disabled")==="true",label:t,showLabel:n,parameters:Q0e(e),bag:{a:ym(e),c:e.getAllChildren().map((u,l)=>({i:l,node:(0,$n.rawFromNode)(u)}))}}}function bu(e){return e.a.length===0&&e.c.length===0&&!e.w}function ZG(e,t){let n=e.a.find(r=>r[0]===t);return n?n[1]:void 0}function Pl(e,t){var n;let r=new Set(e.a.map(a=>a[0])),i=bu(e),o=[];for(let a of t)if(r.has(a.key)){let s=(n=ZG(e,a.key))!==null&&n!==void 0?n:"";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,$n.mergeAttrs)(e.a,o)}var gu=(e,t)=>({key:e,matches:n=>n===t,render:()=>t,absentDefault:""}),yu=(e,t,n=!1)=>({key:e,matches:r=>r==="true"===t,render:()=>String(t),absentDefault:String(n)}),WG=(e,t,n=1)=>({key:e,matches:r=>gN(r,n)===t,render:()=>String(t),absentDefault:String(n)});function EN(e,t){return{n:"labels",a:[],c:[{n:"label",a:[["description",e],["languagecode",String(t)]],c:[]}]}}function yN(e){return{n:"parameters",a:[],c:Object.keys(e).map(t=>{var n;return{n:(0,bN.assertXmlName)(t,"Form control parameter name"),a:[],c:[{n:`<${(n=e[t])!==null&&n!==void 0?n:""}`,a:[],c:[]}]}})}}function iye(e,t){var n,r;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(r=(n=o?.a.find(a=>a[0]==="description"))===null||n===void 0?void 0:n[1])!==null&&r!==void 0?r:""}function oye(e,t,n){let r=!1,i=e.c.map(o=>o.n!=="label"||!o.a.some(s=>s[0]==="languagecode"&&s[1]===String(n))?o:(r=!0,{...o,a:o.a.map(s=>s[0]==="description"?["description",t]:s)}));return r||i.push({n:"label",a:[["description",t],["languagecode",String(n)]],c:[]}),{...e,c:i}}function AN(e,t,n){let r=e.c.findIndex(o=>o.node.n==="labels");if(r<0){if(!t||bu(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:EN(t,n)},...a]}}if(iye(e.c[r].node,n)===t)return e;let i=oye(e.c[r].node,t,n);return{...e,c:e.c.map((o,a)=>a===r?{...o,node:i}:o)}}function aye(e){let t={};for(let n of e.c){let r=n.n;if(r.charAt(0)==="<"||r.charAt(0)==="#")continue;let i=n.c[0],o=i?i.n:"";o.charAt(0)==="<"&&(o=o.substring(1)),t[r]=o}return t}function sye(e,t){let n=Object.keys(e),r=Object.keys(t);return n.length===r.length&&n.every(i=>e[i]===t[i])}function uye(e,t){return e.a.some(n=>n[0]===t)?{...e,a:e.a.filter(n=>n[0]!==t)}:e}function lye(e,t){let n=e.c.findIndex(i=>i.node.n==="parameters");if(n<0){if(Object.keys(t).length===0||bu(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:yN(t)}]}}if(sye(aye(e.c[n].node),t))return e;let r=yN(t);return{...e,c:e.c.map((i,o)=>o===n?{...i,node:r}:i)}}function Ny(e,t,n,r){if(e.w){let a={n:e.w.n,a:e.w.a.map(s=>[s[0],s[1]]),c:(0,$n.spliceChildren)(e.w.c,n)};return(0,$n.spliceChildren)(e.c,[a])}let i=r(),o={n:t,a:[],c:n};return e.c.length===0?[...i,o]:(0,$n.spliceChildren)(e.c,[...i,o])}function cye(e,t){let n=e.tabs.map(r=>dye(r,t));return{n:"form",a:Pl(e.bag,[]),c:e.tabs.length===0&&bu(e.bag)?[]:Ny(e.bag,"tabs",n,()=>[])}}function e4(e,t,n){return t&&!e.c.some(r=>r.node.n==="labels")?[EN(t,n)]:[]}function dye(e,t){let n=[gu("id",e.id),gu("name",e.name),yu("expanded",e.expanded),yu("visible",e.visible,!0)],r=e.columns.map(o=>fye(o,t)),i=AN(e.bag,e.label,t);return{n:"tab",a:Pl(i,n),c:Ny(i,"columns",r,()=>e4(i,e.label,t))}}function fye(e,t){let n=e.width!==void 0?[gu("width",e.width)]:[],r=e.sections.map(i=>pye(i,t));return{n:"column",a:Pl(e.bag,n),c:Ny(e.bag,"sections",r,()=>[])}}function pye(e,t){let n=[gu("id",e.id),gu("name",e.name),yu("showlabel",e.showLabel),yu("visible",e.visible,!0),{key:"columns",matches:o=>QG(o)===e.columns,render:()=>mN(e.columns),absentDefault:mN(1)}],r=e.rows.map(o=>mye(o,t)),i=AN(e.bag,e.label,t);return{n:"section",a:Pl(i,n),c:Ny(i,"rows",r,()=>e4(i,e.label,t))}}function mye(e,t){let n=e.cells.map(r=>hye(r,t));return{n:"row",a:Pl(e.bag,[]),c:bu(e.bag)?n:(0,$n.assembleChildren)(e.bag,n)}}function hye(e,t){let n=e.control?e.control.showLabel:ZG(e.bag,"showlabel")==="true",r=[gu("id",e.id),yu("showlabel",n),yu("visible",e.visible,!0),WG("colspan",e.colspan),WG("rowspan",e.rowspan)],i=e.control?[gye(e.control)]:[],o;if(bu(e.bag))o=[...e.control&&e.control.label?[EN(e.control.label,t)]:[],...i];else{let a=e.control?AN(e.bag,e.control.label,t):e.bag;o=(0,$n.assembleChildren)(a,i)}return{n:"cell",a:Pl(e.bag,r),c:o}}function gye(e){let t=[gu("id",e.id),{key:"classid",matches:i=>bm(i)===e.classId,render:()=>hN(e.classId||String(cn.ControlClassId.TextboxControl)),absentDefault:""}];e.fieldName!==null&&t.push(gu("datafieldname",e.fieldName)),t.push(yu("disabled",e.isReadOnly)),t.push(yu("isrequired",e.isRequired));let n=e.fieldName===null?uye(e.bag,"datafieldname"):e.bag,r;return bu(n)?r=Object.keys(e.parameters).length>0?[yN(e.parameters)]:[]:r=(0,$n.assembleChildren)(lye(n,e.parameters),[]),{n:"control",a:Pl(n,t),c:r}}var yye={make:(e,t)=>new j0e.FormElementNode(e,t),setProp:(e,t,n)=>e.setProperty(t,n),addChild:(e,t)=>e.addChild(t)};function zG(e,t,n,r){(0,pN.installDomShim)();let i=vye(e,n);(0,_r.reconcileEmbedDescriptions)(i,r),(0,ya.reconcilePcfDescriptions)(i,r,n?.pcf);let o=(0,$n.rebuildRaw)(cye(i,t),yye,null);return new z0e.SerializationService(t).serializeFormXmlNode(o)}function bye(e){return JSON.parse(JSON.stringify(e))}function vye(e,t){let n=bye(e);n.bag||(n.bag=(0,$n.emptyBag)()),n.tabs||(n.tabs=[]),Iye(n.bag),t&&wye(n,t);for(let r of n.tabs)Eye(r);return n}function wye(e,t){var n;let r=(n=e.entityLogicalName)!==null&&n!==void 0?n:"";CN(e,i=>{let o=i.fieldName,a=i;if(!o||a.label!==void 0&&a.classId!==void 0)return;let s=t.resolveField(r,o);s&&(a.label===void 0&&s.displayName&&(a.label=s.displayName),a.classId===void 0&&s.attributeType&&(a.classId=n4(s.attributeType)))})}function HG(e){let t=[];return CN(e,n=>t.push(n)),t}function CN(e,t){var n,r,i,o,a;for(let s of(n=e.tabs)!==null&&n!==void 0?n:[])for(let u of(r=s.columns)!==null&&r!==void 0?r:[])for(let l of(i=u.sections)!==null&&i!==void 0?i:[])for(let c of(o=l.rows)!==null&&o!==void 0?o:[])for(let d of(a=c.cells)!==null&&a!==void 0?a:[])d.control&&t(d.control)}function Eye(e){e.id||(e.id=gs.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)Aye(t);e.bag||(e.bag=(0,$n.emptyBag)())}function Aye(e){e.sections||(e.sections=[]);for(let t of e.sections)Cye(t);e.bag||(e.bag=(0,$n.emptyBag)()),e.width===void 0&&bu(e.bag)&&(e.width="100%")}function Cye(e){e.id||(e.id=gs.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)Sye(t);e.bag||(e.bag=(0,$n.emptyBag)())}function Sye(e){e.cells||(e.cells=[]);for(let t of e.cells)Nye(t);e.bag||(e.bag=(0,$n.emptyBag)())}function Nye(e){(0,_r.hasGenPage)(e.control)&&(0,_r.applyEmbedCellDefaults)(e),e.id||(e.id=gs.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&&_ye(e.control),e.bag||(e.bag=(0,$n.emptyBag)())}function _ye(e){var t;(0,_r.hasGenPage)(e)&&(0,_r.applyEmbedControlDefaults)(e),e.id||(e.id=gs.Guid.NewGuid()),(e.classId===void 0||e.classId===null)&&(e.classId=String(cn.ControlClassId.TextboxControl)),e.fieldName===void 0&&(e.fieldName=null),e.type===void 0&&(e.type=e.fieldName?"Field":vN(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 n of Object.keys(e.parameters))(0,bN.assertXmlName)(n,"Form control parameter name");e.bag||(e.bag=(0,$n.emptyBag)())}function Iye(e){for(let t of e.c){let n=t.node;if(n.n==="events"){for(let r of n.c)if(r.n==="event"){for(let i of r.c)if(i.n==="Handlers")for(let o of i.c)o.n==="Handler"&&!KG(o,"handlerUniqueId")&&o.a.push(["handlerUniqueId",hN(gs.Guid.NewGuid())])}}else if(n.n==="formLibraries")for(let r of n.c)r.n==="Library"&&!KG(r,"libraryUniqueId")&&r.a.push(["libraryUniqueId",hN(gs.Guid.NewGuid())])}}var Cy=class{constructor(t=JG.DEFAULT_LCID){this.lcid=t}toArtifact(t,n){var r,i,o;let{tabs:a,bag:s}=jG(t,this.lcid),u={id:t.formId?t.formId.guidString:"",name:(r=t.formName)!==null&&r!==void 0?r:"",entityLogicalName:(i=t.entityName)!==null&&i!==void 0?i:"",formType:(o=J0e[t.formType])!==null&&o!==void 0?o:"Main",status:this.readActivationStatus(t),...n!==void 0&&n!==""?{description:n}:{},tabs:a,bag:s};return(0,_r.projectGenPageEmbeds)(u),(0,ya.projectPcfBindings)(u),u}fromArtifact(t){var n;return this.deserialize({formxml:zG(t,this.lcid),formid:t.id||(0,Od.newId)(),objecttypecode:t.entityLogicalName,type:Ay[t.formType],name:t.name,uniquename:t.name,description:(n=t.description)!==null&&n!==void 0?n:"",formpresentation:kn.FormPresentation.AirForm,formactivationstate:t.status==="Active"?kn.FormActivationState.Active:kn.FormActivationState.InActive})}fromApiResponse(t){var n,r,i,o,a,s,u;let l=t,c=(n=l.formxml)!==null&&n!==void 0?n:"",d={formxml:c,formid:(r=l.formid)!==null&&r!==void 0?r:(0,Od.newId)(),objecttypecode:(i=l.objecttypecode)!==null&&i!==void 0?i:"",type:l.type,name:(o=l.name)!==null&&o!==void 0?o:"",uniquename:(a=l.uniquename)!==null&&a!==void 0?a:"",description:(s=l.description)!==null&&s!==void 0?s:"",formpresentation:l.formpresentation,formactivationstate:l.formactivationstate};(0,pN.installDomShim)();let f=VG.ScriptUtilities.ParseXml(c),p=Tye(f),m=this.deserializeDocument(d,f);return Oye(this.toArtifact(m,(u=l.description)!==null&&u!==void 0?u:void 0),p)}toApiPayload(t,n,r){let i=(0,_r.genPageEmbedIssues)(t);if(i.length>0)throw new Td.ValidationError("form",t.id,i);let o=(0,ya.pcfBindingIssues)(t,n,{atPush:!0});if(o.length>0)throw new Td.ValidationError("form",t.id,o);let a=(0,ya.pcfReadIssues)(t,r?.pcf,n);if(a.unavailable)throw(0,Td.attachCause)(new Td.SdkError(a.unavailable.code,a.unavailable.message),a.unavailable.cause);if(a.issues.length>0)throw new Td.ValidationError("form",t.id,a.issues);return{formxml:zG(t,this.lcid,r,n),name:t.name,type:Ay[t.formType],objecttypecode:t.entityLogicalName,...t.description!==void 0?{description:t.description}:{}}}metadataNeeds(t){let n=t.entityLogicalName;if(!n)return[];let r=new Map;return CN(t,i=>{var o;let a=i.fieldName,s=i;if(!a||s.label!==void 0&&s.classId!==void 0)return;let u=(o=r.get(a))!==null&&o!==void 0?o:{entityLogicalName:n,fieldName:a};s.label===void 0&&(u.needsLabel=!0),r.set(a,u)}),[...r.values()]}customControlNeeds(t,n){var r;return{entityLogicalName:(r=t.entityLogicalName)!==null&&r!==void 0?r:"",...(0,ya.customControlNeeds)(t,n)}}createDefault(t){var n,r,i,o,a,s,u,l,c,d,f,p;let m=[...(0,_r.genPageEmbedIssues)(t),...(0,ya.pcfBindingIssues)(t)];if(m.length>0)throw new Td.ValidationError("form",t.id||"(new)",m);let h=t.tabs&&t.tabs.length>0?void 0:Uye(this.lcid),g=h!==void 0?h:t.tabs.map(E=>Dye(E,this.lcid)).join(""),y=this.deserialize({formxml:`<form><tabs>${g}</tabs></form>`,formid:t.id||(0,Od.newId)(),objecttypecode:(n=t.entityLogicalName)!==null&&n!==void 0?n:"",type:Ay[(r=t.formType)!==null&&r!==void 0?r:"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:kn.FormPresentation.AirForm,formactivationstate:((s=t.status)!==null&&s!==void 0?s:"Active")==="Active"?kn.FormActivationState.Active:kn.FormActivationState.InActive});(u=y.displayCondition)===null||u===void 0||u.removeProperty(kn.ElementProperties.Order);let b=this.toArtifact(y,t.description);if(t.tabs&&t.tabs.length>0){let E=HG(t);HG(b).forEach((w,_)=>{E[_]&&E[_].label===void 0&&delete w.label,E[_]&&E[_].genPage!==void 0&&(w.genPage=JSON.parse(JSON.stringify(E[_].genPage))),E[_]&&E[_].customControl!==void 0&&(w.customControl=JSON.parse(JSON.stringify(E[_].customControl)))})}return{id:(l=t.id)!==null&&l!==void 0?l:b.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:(p=t.status)!==null&&p!==void 0?p:"Active",...t.description!==void 0?{description:t.description}:{},tabs:b.tabs,bag:b.bag}}assignMissingIds(t){return(0,Od.assignMissingIds)(t)}completeAsStored(t,n){return(0,K0e.completeRecordAsStored)(t,n,this.lcid)}normalize(t){return(0,ya.mintPcfIdentity)((0,_r.mintEmbedIdentity)(t))}committed(t,n){var r,i,o,a,s,u;let l=n?.formxml;if(typeof l!="string"||!((0,_r.mayCommitEmbedState)(t)||(0,ya.mayCommitPcfState)(t)))return{artifact:t,baseline:t};let c=this.deserialize({formxml:l,formid:t.id||(0,Od.newId)(),objecttypecode:(r=t.entityLogicalName)!==null&&r!==void 0?r:"",type:Ay[(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:kn.FormPresentation.AirForm,formactivationstate:kn.FormActivationState.Active}),{bag:d}=jG(c,this.lcid),f=(0,ya.commitPcfState)((0,_r.commitEmbedState)(t,(u=(0,_r.descriptionsRegion)(d))===null||u===void 0?void 0:u.node),vN);return{artifact:f,baseline:f}}validate(t){return Kye(t)}deserialize(t){return(0,pN.installDomShim)(),this.deserializeDocument(t,VG.ScriptUtilities.ParseXml(t.formxml))}deserializeDocument(t,n){let r=new W0e.DeserializationService(this.lcid).deSerializeFormXml(n,new gs.Guid(t.formid),t.objecttypecode,kn.FormState.Draft,t.name,t.uniquename,t.type,t.formpresentation,t.description,t.formactivationstate);if(!r)throw new Error("FormXml could not be deserialized into a Form model.");return r}readActivationStatus(t){return t.formactivationstate===kn.FormActivationState.InActive?"Inactive":"Active"}};wi.FormAdapter=Cy;var t4=["header","footer","DisplayConditions"];function Tye(e){var t;let n=e?.getElementsByTagName("form")[0],r=new Set;for(let i=(t=n?.firstChild)!==null&&t!==void 0?t:null;i;i=i.nextSibling)i.nodeType===1&&t4.includes(i.nodeName)&&r.add(i.nodeName);return r}function Oye(e,t){var n;if(!(!((n=e.bag)===null||n===void 0)&&n.c))return e;let r=t4.filter(o=>!t.has(o)),i=e.bag.c.filter(o=>{var a;return r.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!r.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 Ro(e){return String(e??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function SN(e,t){return e?`<labels><label description="${Ro(e)}" languagecode="${t}" /></labels>`:""}function NN(e){return e&&e.length>0?bm(e):(0,Od.newId)()}function Dye(e,t){var n,r,i,o;let a=(n=e.columns)!==null&&n!==void 0?n:[],s=(a.length>0?a:[Fye()]).map(u=>Pye(u,t)).join("");return`<tab id="{${Ro(NN(e.id))}}" name="${Ro((r=e.name)!==null&&r!==void 0?r:"")}" expanded="${(i=e.expanded)!==null&&i!==void 0?i:!0}" visible="${(o=e.visible)!==null&&o!==void 0?o:!0}">${SN(e.label,t)}<columns>${s}</columns></tab>`}function Pye(e,t){var n,r;let i=((n=e.sections)!==null&&n!==void 0?n:[]).map(o=>Rye(o,t)).join("");return`<column width="${Ro((r=e.width)!==null&&r!==void 0?r:"100%")}"><sections>${i}</sections></column>`}function Rye(e,t){var n,r,i,o,a;let s=((n=e.rows)!==null&&n!==void 0?n:[]).map(u=>kye(u,t)).join("");return`<section id="{${Ro(NN(e.id))}}" name="${Ro((r=e.name)!==null&&r!==void 0?r:"")}" showlabel="${(i=e.showLabel)!==null&&i!==void 0?i:!1}" visible="${(o=e.visible)!==null&&o!==void 0?o:!0}" columns="${mN((a=e.columns)!==null&&a!==void 0?a:1)}">${SN(e.label,t)}<rows>${s}</rows></section>`}function kye(e,t){var n;return`<row>${((n=e.cells)!==null&&n!==void 0?n:[]).map(r=>$ye(r,t)).join("")}</row>`}function $ye(e,t){var n,r,i,o,a;let s=Lye(e),u=s.control,l=u?SN((n=u.label)!==null&&n!==void 0?n:"",t):"",c=u?Mye(u):"";return`<cell id="{${Ro(NN(s.id))}}" showlabel="${u?(r=u.showLabel)!==null&&r!==void 0?r:!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}">${l}${c}</cell>`}function Lye(e){if(!(0,_r.hasGenPage)(e.control))return e;let t={...e.control};(0,_r.applyEmbedControlDefaults)(t);let n={...e,control:t};return(0,_r.applyEmbedCellDefaults)(n),n}function Mye(e){var t,n,r;let i=e.fieldName?` datafieldname="${Ro(e.fieldName)}"`:"",o=xye(e.parameters),a=e.classId?bm(e.classId):String(cn.ControlClassId.TextboxControl);return`<control id="${Ro((t=e.id)!==null&&t!==void 0?t:"")}" classid="{${Ro(a)}}"${i} disabled="${(n=e.isReadOnly)!==null&&n!==void 0?n:!1}" isrequired="${(r=e.isRequired)!==null&&r!==void 0?r:!1}">${o}</control>`}function xye(e){let t=Object.keys(e??{});return t.length===0?"":(t.forEach(r=>(0,bN.assertXmlName)(r,"Form control parameter name")),`<parameters>${t.map(r=>`<${r}>${Ro(e[r])}</${r}>`).join("")}</parameters>`)}function Fye(){return{width:"100%",sections:[],bag:{a:[],c:[]}}}function Uye(e){return`<tab id="{${gs.Guid.NewGuid()}}" name="tab_general" expanded="true" visible="true"><labels><label description="General" languagecode="${e}" /></labels><columns><column width="100%"><sections><section id="{${gs.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 qye(e=JG.DEFAULT_LCID){return{adapter:new Cy(e),api:H0e.formApi,languageSensitive:!0,publish:(t,n,r)=>(0,GG.publishBoundEntity)(t,r),publishScope:(t,n)=>(0,GG.boundEntityPublishScope)(n),rebaselineAfterPublish:"bracket"}}wi.formRegistration=qye;var Bye=new Set(["id","name","label","expanded","visible","columns","bag"]),Vye=new Set(["id","width","sections","bag"]),Gye=new Set(["id","name","label","visible","showLabel","columns","rows","bag"]),jye=new Set(["id","cells","bag"]),Wye=new Set(["id","visible","colspan","rowspan","control","bag"]),zye=new Set(["id","classId","fieldName","type","isRequired","isReadOnly","label","showLabel","parameters","genPage","customControl","bag"]),Hye={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 Kye(e){let t=[];return(0,vi.childObjects)(e,"tabs","","tab",t).forEach(({node:r,index:i})=>{let o=`/tabs/${i}`;(0,vi.rejectUnknownKeys)(r,Bye,o,"tab",t),(0,vi.childObjects)(r,"columns",o,"column",t).forEach(({node:s,index:u})=>{let l=`${o}/columns/${u}`;(0,vi.rejectUnknownKeys)(s,Vye,l,"column",t),(0,vi.childObjects)(s,"sections",l,"section",t).forEach(({node:d,index:f})=>{let p=`${l}/sections/${f}`;(0,vi.rejectUnknownKeys)(d,Gye,p,"section",t),(0,vi.childObjects)(d,"rows",p,"row",t).forEach(({node:h,index:g})=>{let y=`${p}/rows/${g}`;(0,vi.rejectUnknownKeys)(h,jye,y,"row",t),(0,vi.childObjects)(h,"cells",y,"cell",t).forEach(({node:E,index:w})=>{let _=`${y}/cells/${w}`;(0,vi.rejectUnknownKeys)(E,Wye,_,"cell",t,Hye);let I=E.control;I!=null&&!(0,vi.isJsonObject)(I)?t.push((0,vi.issue)(`${_}/control`,"control-must-be-object-or-null",`a cell control must be a JSON object or null, got ${typeof I}`)):(0,vi.isJsonObject)(I)&&(0,vi.rejectUnknownKeys)(I,zye,`${_}/control`,"control",t)})})})})}),t.push(...(0,_r.genPageEmbedIssues)(e)),t.push(...(0,ya.pcfBindingIssues)(e)),t}wi.SUBGRID_CLASS_ID=cn.ControlClassId.SubgridControl;wi.NOTES_CLASS_ID=cn.ControlClassId.TimelineControl;wi.QUICK_VIEW_CLASS_ID=cn.ControlClassId.QuickViewControl;var Jye={Lookup:String(cn.ControlClassId.LookupControl),Customer:String(cn.ControlClassId.LookupControl),Owner:String(cn.ControlClassId.LookupControl),PartyList:String(cn.ControlClassId.PartyListControl),Boolean:String(cn.ControlClassId.BooleanControl),DateTime:String(cn.ControlClassId.DateTimeControl),Decimal:String(cn.ControlClassId.DecimalControl),Double:String(cn.ControlClassId.FloatingNumberControl),Money:String(cn.ControlClassId.CurrencyControl),Integer:String(cn.ControlClassId.IntegerControl),BigInt:String(cn.ControlClassId.IntegerControl),Memo:String(cn.ControlClassId.TextAreaControl),String:String(cn.ControlClassId.TextboxControl)},Yye="3EF39988-22BB-4F0B-BBBE-64B5A3748AEE";function n4(e){return e==="Picklist"||e==="State"||e==="Status"?Yye:e&&Jye[e]||String(cn.ControlClassId.TextboxControl)}wi.classIdForAttributeType=n4;function KG(e,t){let n=e.a.find(r=>r[0]===t);return n?n[1]:void 0}});var IN=C(Rl=>{"use strict";Object.defineProperty(Rl,"__esModule",{value:!0});Rl.viewApi=Rl.findDefaultViews=void 0;var s4=Ke(),_N=qi(),Ir=pe(),io=ae(),Qye=Ms(),i4="savedqueryid,name,description,fetchxml,layoutxml,querytype,returnedtypecode,isdefault",Xye="savedqueryid,name,returnedtypecode,querytype,isdefault",Zye=60*1e3;function _y(e){return(e.localName||e.nodeName).toLowerCase()}function vm(e,t){let n;for(let r=0;r<e.attributes.length;r+=1){let i=e.attributes[r];i.nodeName.toLowerCase()===t&&(n=n===void 0?i.value:null)}return n}function ebe(e){if(!e)return;let t=!0,n=()=>{t=!1},r=new Qye.DOMParser({errorHandler:{warning:n,error:n,fatalError:n}}).parseFromString(e,"text/xml").documentElement;return t&&r&&_y(r)==="fetch"?r:void 0}function tbe(e){for(let t=e.parentNode;t;t=t.parentNode)if(_y(t)==="link-entity")return!0;return!1}function o4(e,t){var n,r,i;if(((n=e.canbedeleted)===null||n===void 0?void 0:n.Value)!==!1)return!1;let o=ebe(e.fetchxml);if(!o)return!1;let a=Array.from(o.getElementsByTagName("*")),s=a.filter(l=>_y(l)==="condition"),u=s.length===1?s[0]:void 0;return u!==void 0&&a.filter(l=>_y(l)==="link-entity").every(l=>{var c;return((c=vm(l,"link-type"))===null||c===void 0?void 0:c.toLowerCase())==="outer"})&&!tbe(u)&&vm(u,"entityname")===void 0&&((r=vm(u,"attribute"))===null||r===void 0?void 0:r.toLowerCase())==="statecode"&&((i=vm(u,"operator"))===null||i===void 0?void 0:i.toLowerCase())==="eq"&&vm(u,"value")===String(t)}function nbe(e,t){let n=String(e??"").trim().toLowerCase().split(/\s+/).filter(i=>i!==""),r=String(t??"").trim().toLowerCase().split(/\s+/).filter(i=>i!=="");return n.length===r.length&&n.filter((i,o)=>i!==r[o]).length===1}function rbe(e){var t,n;let r=e.filter(a=>o4(a,0)),i=e.filter(a=>o4(a,1)),o=[];for(let a of r)for(let s of i)Math.abs(Date.parse(String((t=s.createdon)!==null&&t!==void 0?t:""))-Date.parse(String((n=a.createdon)!==null&&n!==void 0?n:"")))<=Zye&&nbe(a.name,s.name)&&o.push({active:a,inactive:s});return o.length===1?o[0]:void 0}async function ibe(e,t,n={}){var r;let i=new Set(((r=n.excludeViewIds)!==null&&r!==void 0?r:[]).filter(Boolean)),o=`returnedtypecode eq '${(0,io.odataLiteral)(t)}' and querytype eq 0`,a=`/savedqueries${(0,io.odataQuery)([["$select","savedqueryid,name,canbedeleted,fetchxml,createdon"],["$filter",o]])}`,s=await(0,s4.collectPages)(e,a,`findDefaultViews('${t}')`),u=rbe(s),l=new Set(u?[u.active,u.inactive]:[]);return s.filter(c=>c.savedqueryid&&!i.has(c.savedqueryid)&&l.has(c)).map(c=>{var d;return{id:String(c.savedqueryid),name:String((d=c.name)!==null&&d!==void 0?d:"")}})}Rl.findDefaultViews=ibe;async function obe(e,t){var n;let r=`/EntityDefinitions(LogicalName='${(0,io.odataPathLiteral)(t)}')${(0,io.odataQuery)([["$select","ObjectTypeCode"]])}`,i=await e.get(r);if(i.status>=200&&i.status<300){let o=(n=i.body)===null||n===void 0?void 0:n.ObjectTypeCode;return typeof o=="number"?o:void 0}}async function a4(e,t,n){if(!n||!/<grid\b/.test(t)||/<grid[^>]*\bobject=/.test(t))return t;let r=await obe(e,n);return r===void 0?t:t.replace(/<grid\b/,`<grid object="${r}"`)}Rl.viewApi={async get(e,t){let n=(0,io.normalizeGuid)(t,"id"),r=await(0,Ir.readRowEtag)(e,"savedqueries","savedqueryid",n),i=`/savedqueries(${n})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,io.odataQuery)([["$select",i4]]);return{raw:(0,Ir.ensureSuccess)(await e.get(i),e.apiUrl(i)).body,etag:r}},async readContentThenToken(e,t){let n=(0,io.normalizeGuid)(t,"id"),r=`/savedqueries(${n})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,io.odataQuery)([["$select",i4]]),i=(0,Ir.ensureSuccess)(await e.get(r),e.apiUrl(r)),o=await(0,Ir.readRowEtag)(e,"savedqueries","savedqueryid",n);return{raw:i.body,etag:o}},async list(e,t){let n=`/savedqueries${(0,io.odataQuery)([["$select",Xye],["$filter",t?.entityLogicalName?`returnedtypecode eq '${(0,io.odataLiteral)(t.entityLogicalName)}'`:void 0]])}`;return(await(0,s4.collectPages)(e,n,"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,queryType:i.querytype,isDefault:i.isdefault,isDirty:!1}})},async create(e,t,n,r=void 0){let i=t,o=(0,Ir.echoWrite)("savedqueryid"),a=`/savedqueries${o.query}`,s=await a4(e,i.layoutxml,i.returnedtypecode),u=Object.freeze((0,Ir.withClientMintedId)({name:i.name,description:i.description,fetchxml:i.fetchxml,layoutxml:s,returnedtypecode:i.returnedtypecode,querytype:i.querytype,isdefault:i.isdefault},"savedqueryid",n));if(r){let c=n?(0,io.normalizeGuid)(n,"savedqueryid"):void 0;return r.reached({effects:[{componentName:"SavedQuery",componentId:c,identity:"known",operation:"create"}],attemptsWrite:!0},c?()=>(0,_N.existsByKey)(e,r,{collection:"/savedqueries",key:"savedqueryid",id:c,componentName:"SavedQuery"}):void 0)}let l=(0,Ir.ensureSuccess)(await(0,Ir.resendDeadlockVictim)(()=>e.post(a,{...u},o.options)),e.apiUrl(a));return{id:(0,Ir.resolveCreatedId)(l,"savedqueryid","view",n),etag:(0,Ir.readEtag)(l)}},async update(e,t,n,r,i=void 0,o,a){let s=n,u=(0,io.normalizeGuid)(t,"id");a&&!(0,Ir.isVersionToken)(r)&&a.observe({guard:"ifMatch",componentName:"SavedQuery",componentId:u,held:r,status:"missingHeld"});let l=(0,Ir.echoWrite)("savedqueryid",{"If-Match":(0,Ir.requireEtag)(r,"view",u)}),c=`/savedqueries(${u})${l.query}`,d=await a4(e,s.layoutxml,s.returnedtypecode);if(a)return await(0,_N.observeIfMatch)(e,a,{entitySet:"savedqueries",idColumn:"savedqueryid",id:u,componentName:"SavedQuery",held:l.options.headers["If-Match"]}),a.reached({effects:[{componentName:"SavedQuery",componentId:u,identity:"known",operation:"update"}],attemptsWrite:!0});let f=typeof s.returnedtypecode=="string"&&s.returnedtypecode.trim()!==""?{returnedtypecode:s.returnedtypecode}:{},p=(0,Ir.ensureSuccess)(await e.patch(c,{name:s.name,description:s.description,fetchxml:s.fetchxml,layoutxml:d,...f},l.options),e.apiUrl(c));return{id:u,etag:(0,Ir.readEtag)(p)}},delete(e,t){return(0,Ir.deleteRecord)(e,"savedqueries",t)},planPush(e,t,n){return(0,_N.planPushThrough)(Rl.viewApi,e,t,n)}}});var c4=C(Pd=>{"use strict";Object.defineProperty(Pd,"__esModule",{value:!0});Pd.findColumnTemplate=Pd.classifyFindFilter=void 0;var Dd="isquickfindfields",u4=new Set(["attribute","operator","value"]),abe=/\{[0-4]\}/;function TN(e){let t=[];for(let n=0;n<e.childNodes.length;n+=1){let r=e.childNodes[n];r.nodeType===1&&t.push(r)}return t}function l4(e){var t;for(let n=0;n<e.childNodes.length;n+=1){let r=e.childNodes[n];if(r.nodeType!==1&&r.nodeType!==3||r.nodeType===3&&((t=r.nodeValue)!==null&&t!==void 0?t:"").trim()!=="")return!0}return!1}function sbe(e){var t,n;let i=Array.from(e.getElementsByTagName("*")).filter(c=>c.hasAttribute(Dd));if(i.length===0)return{state:"absent"};if(i.length>1)return{state:"unsupported",reason:`${i.length} elements carry ${Dd}`};let o=i[0],a=TN(e).find(c=>c.tagName==="entity");if(o.tagName!=="filter")return{state:"unsupported",reason:`${Dd} is on a <${o.tagName}>, not a <filter>`};if(o.getAttribute(Dd)!=="1")return{state:"unsupported",reason:`${Dd}="${o.getAttribute(Dd)}"`};if(!a||o.parentNode!==a)return{state:"unsupported",reason:"the find filter is not a direct child of the entity"};if(l4(o))return{state:"unsupported",reason:"the find filter holds text"};let s=TN(o),u=[],l=new Set;for(let c of s){if(c.tagName!=="condition"||TN(c).length>0||l4(c))return{state:"unsupported",reason:`the find filter holds a <${c.tagName}> that is not a plain condition`};let d=Array.from({length:c.attributes.length},(m,h)=>c.attributes[h].name);if(d.length!==u4.size||d.some(m=>!u4.has(m)))return{state:"unsupported",reason:`a find condition carries [${d.join(", ")}]`};let f=(t=c.getAttribute("attribute"))!==null&&t!==void 0?t:"";if(f===""||f.includes("."))return{state:"unsupported",reason:`a find condition names '${f}'`};if(!abe.test((n=c.getAttribute("value"))!==null&&n!==void 0?n:""))return{state:"unsupported",reason:`the condition on '${f}' is a literal constraint, not a find column`};let p=f.toLowerCase();if(l.has(p))return{state:"unsupported",reason:`'${f}' is a find column twice`};l.add(p),u.push(f)}return{state:"modelled",filter:o,columns:u,conditions:s}}Pd.classifyFindFilter=sbe;function ube(e){switch(e){case"String":case"Memo":case"Lookup":case"Customer":case"Owner":case"Picklist":case"State":case"Status":case"Boolean":return{operator:"like",value:"{0}"};case"Integer":return{operator:"eq",value:"{1}"};case"Double":return{operator:"eq",value:"{4}"};case"Money":return{operator:"eq",value:"{2}"};case"DateTime":return{operator:"on",value:"{3}"};default:return}}Pd.findColumnTemplate=ube});var _4=C($d=>{"use strict";Object.defineProperty($d,"__esModule",{value:!0});$d.viewRegistration=$d.ViewAdapter=void 0;var kl=Y(),dn=Vi(),ON=Us(),vu=ja(),d4=mo(),lbe=IN(),Rd=Ga(),cbe=ft(),kd=c4(),g4=100,Iy=class{toArtifact(t){var n,r,i,o,a,s,u,l;(0,Rd.installDomShim)();let c=(n=t.fetchxml)!==null&&n!==void 0?n:"",d=(r=t.layoutxml)!==null&&r!==void 0?r:"",f=(0,vu.parseXmlRoot)(c,"<fetch/>"),p=(0,vu.parseXmlRoot)(d,"<grid/>"),m=w4(f),h=(0,kd.classifyFindFilter)(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:hbe(f),queryType:(u=t.querytype)!==null&&u!==void 0?u:0,isDefault:(l=t.isdefault)!==null&&l!==void 0?l:!1,columns:v4(p,f),filters:A4(f),sort:E4(f),...m.length>0?{linkEntities:m}:{},...h.state==="modelled"?{findColumns:[...h.columns]}:{},fetchBag:c?(0,vu.projectElementBag)(f):void 0,layoutBag:d?(0,vu.projectElementBag)(p):void 0}}fromArtifact(t){(0,Rd.installDomShim)();let{fetchxml:n,layoutxml:r}=p4(t);return{savedqueryid:t.id,name:t.name,description:t.description,returnedtypecode:t.entityLogicalName,querytype:t.queryType,isdefault:t.isDefault,fetchxml:n,layoutxml:r}}fromApiResponse(t){return this.toArtifact(t??{})}toApiPayload(t,n,r){var i,o,a,s;(0,Rd.installDomShim)();let u=dbe(t,n),{fetchxml:l,layoutxml:c}=p4(f4(t,n),r,u);return{name:(i=t.name)!==null&&i!==void 0?i:"",description:(o=t.description)!==null&&o!==void 0?o:"",fetchxml:l,layoutxml:c,returnedtypecode:(a=t.entityLogicalName)!==null&&a!==void 0?a:"",querytype:u??0,isdefault:(s=t.isDefault)!==null&&s!==void 0?s:!1}}createDefault(t){var n,r,i,o,a,s,u,l;let c=(n=t.entityLogicalName)!==null&&n!==void 0?n:"";return{id:(r=t.id)!==null&&r!==void 0?r:(0,cbe.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:(u=t.filters)!==null&&u!==void 0?u:{type:"and",conditions:[],groups:[]},sort:(l=t.sort)!==null&&l!==void 0?l:[],...t.linkEntities&&t.linkEntities.length>0?{linkEntities:t.linkEntities}:{},...t.findColumns!==void 0?{findColumns:t.findColumns}:{}}}assignMissingIds(t){return t}committed(t,n){let r=n,i=t;typeof r?.querytype=="number"&&r.querytype!==t.queryType&&(i={...i,queryType:r.querytype});let o=r?.fetchxml;if(i.findColumns===void 0&&typeof o=="string"&&o.includes("isquickfindfields")){(0,Rd.installDomShim)();let a=(0,kd.classifyFindFilter)((0,vu.parseXmlRoot)(o,"<fetch/>"));a.state==="modelled"&&(i={...i,findColumns:[...a.columns]})}return{artifact:i,baseline:i}}validate(t){let n=[],r=t;(0,dn.childObjects)(r,"columns","","column",n),(0,dn.childObjects)(r,"sort","","sort",n),(0,dn.childObjects)(r,"linkEntities","","linkEntity",n),mbe(r.linkEntities,n),fbe(t,n);let i=r.filters;return i!=null&&((0,dn.isJsonObject)(i)?$N(i,"/filters",n):n.push((0,dn.issue)("/filters","filters-must-be-object",`filters must be a JSON object, got ${typeof i}`))),n}metadataNeeds(t,n){let r=f4(t,n);if(!Array.isArray(r.findColumns)||r.findColumns.length===0)return[];(0,Rd.installDomShim)();let i=RN(r);if(i.state==="unsupported")return[];let o=new Set(i.state==="modelled"?i.columns.map(s=>s.toLowerCase()):[]),a=new Set;for(let s of r.findColumns){let u=typeof s=="string"?s.toLowerCase():"";u!==""&&!o.has(u)&&a.add(u)}return[...a].map(s=>({entityLogicalName:r.entityLogicalName,fieldName:s}))}};$d.ViewAdapter=Iy;function f4(e,t){let n=t?.findColumns;return e.findColumns!==void 0||!Array.isArray(n)?e:{...e,findColumns:[...n]}}function dbe(e,t){return t!==void 0?t.queryType:e.queryType}function RN(e){if(!DN(e.fetchBag))return{state:"absent"};let t=new DOMParser().parseFromString("<root/>","text/xml");return(0,kd.classifyFindFilter)(PN(e.fetchBag,"fetch",t))}function fbe(e,t){let n=e.findColumns;if(n===void 0)return;if(!Array.isArray(n)){t.push((0,dn.issue)("/findColumns","view-find-columns-not-array",`findColumns must be an array of column logical names, got ${typeof n}`));return}let r=new Map;n.forEach((o,a)=>{if(typeof o!="string"||o.trim()===""||/\s/.test(o)||o.includes(".")){t.push((0,dn.issue)(`/findColumns/${a}`,"view-find-column-not-name",`a find column is a logical name of the view's own table (no spaces, no joined table), got ${JSON.stringify(o)}`));return}let s=o.toLowerCase();if(r.has(s)){t.push((0,dn.issue)(`/findColumns/${a}`,"view-find-column-duplicate",`'${o}' is already a find column (at /findColumns/${r.get(s)})`));return}r.set(s,a)}),(0,Rd.installDomShim)();let i=RN(e);i.state==="unsupported"?t.push(kN(i.reason)):i.state==="absent"&&e.queryType!==4&&t.push(y4(e.queryType))}function kN(e){return(0,dn.issue)("/findColumns","view-find-filter-unsupported",`this view's find filter cannot be represented as a list of find columns (${e}), so a typed write would discard what the list cannot show; it is left as it is. Remove findColumns to keep it.`)}function y4(e,t=e){return t!==e?(0,dn.issue)("/findColumns","view-find-columns-not-quick-find",`find columns can be added only to a Quick Find view (queryType 4); this view is saved with queryType ${e} and has no find filter. Its local queryType (${t}) is not saved by an update (a view's query type is set when it is created), so it cannot make the view a Quick Find view`):(0,dn.issue)("/findColumns","view-find-columns-not-quick-find",`find columns can be added only to a Quick Find view (queryType 4); this view's queryType is ${e} and it has no find filter`)}function pbe(e,t,n,r,i){var o,a;let s=new Map;for(let u of n){let l=(o=r?.resolveField(t.entityLogicalName,u))===null||o===void 0?void 0:o.attributeType,c=((a=t.findColumns)!==null&&a!==void 0?a:[]).findIndex(p=>String(p).toLowerCase()===u);if(!l||l==="Unknown"){i.push((0,dn.issue)(`/findColumns/${c}`,"view-find-column-unresolved",`the type of '${u}' on '${t.entityLogicalName}' could not be read (the column does not exist, or the read failed), so its search template cannot be chosen; nothing was written`));continue}let d=(0,kd.findColumnTemplate)(l);if(!d){i.push((0,dn.issue)(`/findColumns/${c}`,"view-find-column-type-unsupported",`'${u}' is a ${l} column, which cannot be added as a find column (the maker view designer offers text, choice, yes/no, lookup, whole number, floating point, currency and date columns)`));continue}let f=e.createElement("condition");f.setAttribute("attribute",u),f.setAttribute("operator",d.operator),f.setAttribute("value",d.value),s.set(u,f)}return s}function b4(e,t,n,r,i,o){var a,s;let u=((a=n.findColumns)!==null&&a!==void 0?a:[]).map(p=>String(p).toLowerCase());if(r.state==="unsupported")throw new kl.ValidationError("view",n.id,[kN(r.reason)]);if(r.state==="modelled"&&wm(u,r.columns.map(p=>p.toLowerCase())))return;if(r.state==="absent"&&o!==4)throw new kl.ValidationError("view",n.id,[y4(o,n.queryType)]);let l=new Map(r.state==="modelled"?r.conditions.map(p=>[String(p.getAttribute("attribute")).toLowerCase(),p]):[]),c=[],d=pbe(e,n,u.filter(p=>!l.has(p)),i,c);if(c.length>0)throw new kl.ValidationError("view",n.id,c);let f;if(r.state==="modelled")for(f=r.filter;f.firstChild;)f.removeChild(f.firstChild);else{f=e.createElement("filter"),f.setAttribute("type","or"),f.setAttribute("isquickfindfields","1");let p=t.getElementsByTagName("entity")[0];if(!p)throw new kl.ValidationError("view",n.id,"/findColumns","view-find-columns-no-entity");p.appendChild(f)}for(let p of u)f.appendChild((s=l.get(p))!==null&&s!==void 0?s:d.get(p))}function mbe(e,t){Array.isArray(e)&&e.forEach((n,r)=>{if(!(0,dn.isJsonObject)(n))return;for(let o of["name","from","to"]){let a=n[o];(typeof a!="string"||a.trim()==="")&&t.push((0,dn.issue)(`/linkEntities/${r}/${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=n.filters;i!=null&&((0,dn.isJsonObject)(i)?$N(i,`/linkEntities/${r}/filters`,t):t.push((0,dn.issue)(`/linkEntities/${r}/filters`,"filters-must-be-object",`filters must be a JSON object, got ${typeof i}`)))})}function $N(e,t,n){(0,dn.childObjects)(e,"conditions",t,"condition",n),(0,dn.childObjects)(e,"groups",t,"filterGroup",n).forEach(({node:i,index:o})=>$N(i,`${t}/groups/${o}`,n))}function hbe(e){var t;let n=e.getElementsByTagName("entity")[0];return(t=n?.getAttribute("name"))!==null&&t!==void 0?t:""}function v4(e,t){var n;let r=Ty(t),i=e.getElementsByTagName("cell"),o=[],a=0;for(let s=0;s<i.length;s+=1){let u=i[s];if(u.getAttribute("ishidden")==="1")continue;let l=u.getAttribute("name");if(!l)continue;let c=parseInt((n=u.getAttribute("width"))!==null&&n!==void 0?n:"",10),d={name:l,width:Number.isNaN(c)?g4:c,order:a},f=r.get(l);f&&(d.relatedEntity=f.linkKey,f.attributeName&&f.attributeName!==l&&(d.sourceAttribute=f.attributeName)),a+=1,o.push(d)}return o}function Ty(e){let t=new Map,n=e.getElementsByTagName("link-entity");for(let r=0;r<n.length;r+=1){let i=n[r],o=i.getAttribute("name");if(!o)continue;let a=i.getElementsByTagName("attribute");for(let s=0;s<a.length;s+=1){let u=a[s],l=u.getAttribute("name")||"",c=u.getAttribute("alias")||l;c&&t.set(c,{linkKey:i.getAttribute("alias")||o,linkName:o,attributeName:l,link:i})}}return t}function w4(e){let t=e.getElementsByTagName("entity")[0];if(!t)return[];let n=[];for(let r of jr(t,"link-entity")){let i=r.getAttribute("name"),o=r.getAttribute("from"),a=r.getAttribute("to");if(!i||!o||!a)continue;let s=r.getAttribute("alias"),u=r.getAttribute("link-type"),l=jr(r,"filter").find(c=>!Oy(c));n.push({name:i,from:o,to:a,...s?{alias:s}:{},...u==="inner"||u==="outer"?{linkType:u}:{},...l?{filters:LN(l)}:{}})}return n}function E4(e){var t;let n=e.getElementsByTagName("entity")[0];if(!n)return[];let r=[],i=n.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&&r.push({attribute:s,descending:((t=a.getAttribute("descending"))!==null&&t!==void 0?t:"").toLowerCase()==="true",entityname:a.getAttribute("entityname")||""})}}return r}function A4(e){let t=e.getElementsByTagName("entity")[0],n={type:"and",conditions:[],groups:[]};if(!t)return n;let r=jr(t,"filter").filter(i=>!Oy(i)).map(LN);return r.length===0?n:r.length===1?r[0]:{type:"and",conditions:[],groups:r}}function Oy(e){return e.getAttribute("isquickfindfields")==="1"||gbe(e)||C4(e)?!0:Array.from(e.getElementsByTagName("condition")).some(t=>t.getAttribute("isquickfindfields")==="1"||jr(t,"value").length>0||bbe(t))}function gbe(e){let t=e.getElementsByTagName("*");for(let n=0;n<t.length;n+=1)if(t[n].getAttribute("isquickfindfields")==="1")return!0;return!1}function C4(e){let t=e.childNodes;for(let n=0;n<t.length;n+=1){let r=t[n];if(r.nodeType===1&&(r.tagName==="filter"?C4(r):r.tagName!=="condition"))return!0}return!1}var ybe=new Set(["attribute","operator","value","entityname","uiname","uitype"]);function bbe(e){var t;let n=e.attributes;for(let r=0;r<n.length;r+=1){let i=(t=n[r])===null||t===void 0?void 0:t.name;if(i&&!ybe.has(i))return!0}return!1}function LN(e){var t,n;let r=((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 u=a[s];if(u.nodeType===1)if(u.tagName==="condition"){if(u.getAttribute("isquickfindfields")==="1")continue;let l=u.getAttribute("attribute");if(!l)continue;let c={attribute:l,operator:(n=u.getAttribute("operator"))!==null&&n!==void 0?n:""};u.hasAttribute("value")&&(c.value=u.getAttribute("value")||"");let d=u.getAttribute("entityname")||"";d&&(c.entityname=d),i.push(c)}else u.tagName==="filter"&&o.push(LN(u))}return{type:r,conditions:i,groups:o}}function jr(e,t){let n=[],r=e.childNodes;for(let i=0;i<r.length;i+=1){let o=r[i];o.nodeType===1&&o.tagName===t&&n.push(o)}return n}var MN=e=>{var t,n;return`${(t=e.relatedEntity)!==null&&t!==void 0?t:""}::${(n=e.sourceAttribute)!==null&&n!==void 0?n:e.name}`};function vbe(e,t){let n=Ty(e),r=new Map;for(let i of t){if(!i.relatedEntity)continue;let o=n.get(i.name);if(o){let a=MN(i),s=r.get(a);s?s.push(o.link):r.set(a,[o.link])}}return r}function wbe(e,t,n,r){if(!r||r.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=n.filter(s=>{if(!s.relatedEntity)return!1;let u=r.get(MN(s));return!!u&&u.some(l=>!i.has(l))});if(a.length!==0)throw new kl.ValidationError("view",e.id,a.map(s=>(0,dn.issue)(`/columns/${n.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 p4(e,t,n=e.queryType){var r,i;let o=Ebe(e.columns),a=(r=e.sort)!==null&&r!==void 0?r:[],s=(i=e.filters)!==null&&i!==void 0?i:{type:"and",conditions:[],groups:[]},u=e.findColumns!==void 0?RN(e):void 0;if(u?.state==="unsupported")throw new kl.ValidationError("view",e.id,[kN(u.reason)]);if(!DN(e.fetchBag)||!DN(e.layoutBag))return{fetchxml:$be({...e,columns:o,sort:a,filters:s},t,u,n),layoutxml:Lbe({...e,columns:o},`${e.entityLogicalName}id`)};let l=new DOMParser().parseFromString("<root/>","text/xml"),c=PN(e.fetchBag,"fetch",l),d=PN(e.layoutBag,"grid",l),f=e.findColumns!==void 0?(0,kd.classifyFindFilter)(c):void 0,p=v4(d,c),m=!wm(o,p),h=!wm(a,E4(c)),g=!wm(s,A4(c)),y=e.linkEntities,b=y!==void 0&&!wm(y,w4(c)),E=b?vbe(c,p):void 0;return b&&Pbe(l,c,y),b&&(kbe(e,c,o,E),wbe(e,c,o,E)),m?(m4(l,c,o,p),_be(l,d,o)):b&&m4(l,c,o,p),h&&Obe(l,c,a),g&&Dbe(l,c,s),f!==void 0&&b4(l,c,e,f,t,n),{fetchxml:(0,vu.serializeNode)(c),layoutxml:(0,vu.serializeNode)(d)}}function Ebe(e){return(e??[]).map((t,n)=>{var r,i;return{name:String(t.name).toLowerCase(),width:(r=t.width)!==null&&r!==void 0?r:g4,order:(i=t.order)!==null&&i!==void 0?i:n,...t.relatedEntity?{relatedEntity:t.relatedEntity}:{},...t.sourceAttribute?{sourceAttribute:String(t.sourceAttribute).toLowerCase()}:{}}})}function DN(e){return!!e&&(e.c.length>0||e.a.length>0)}function PN(e,t,n){let r={n:t,a:(0,ON.mergeAttrs)(e.a,[]),c:(0,ON.spliceChildren)(e.c,[])};return(0,ON.rebuildRaw)(r,(0,vu.domEngine)(n),null)}function m4(e,t,n,r){var i,o,a;let s=t.getElementsByTagName("entity")[0];if(!s)return;let u=m=>{var h,g;return`${(h=m.relatedEntity)!==null&&h!==void 0?h:""}:${m.name}:${(g=m.sourceAttribute)!==null&&g!==void 0?g:m.name}`},l=new Set(n.map(u)),c=new Set(n.map(m=>m.name)),d=Ty(t);for(let m of r)l.has(u(m))||(Cbe(s,m),m.relatedEntity&&c.has(m.name)&&Abe((i=d.get(m.name))===null||i===void 0?void 0:i.link,m.name));let f=Ty(t),p=new Set(jr(s,"attribute").map(m=>m.getAttribute("name")).filter(m=>!!m));for(let m of[...n].sort((h,g)=>h.order-g.order))if(m.relatedEntity){let h=f.get(m.name);if(h&&h.attributeName===((o=m.sourceAttribute)!==null&&o!==void 0?o:m.name)&&(h.linkKey===m.relatedEntity||h.linkName===m.relatedEntity||!N4(s,m.relatedEntity)))continue;let g=Sbe(e,s,m.relatedEntity),y=e.createElement("attribute");S4(y,m),g.appendChild(y),f.set(m.name,{linkKey:m.relatedEntity,linkName:g.getAttribute("name")||m.relatedEntity,attributeName:(a=m.sourceAttribute)!==null&&a!==void 0?a:m.name,link:g})}else{if(p.has(m.name))continue;let h=e.createElement("attribute");h.setAttribute("name",m.name),Nbe(s,h),p.add(m.name)}}function S4(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 Abe(e,t){if(e){for(let n of jr(e,"attribute"))if((n.getAttribute("alias")||n.getAttribute("name"))===t){e.removeChild(n);return}}}function Cbe(e,t){if(t.relatedEntity){for(let n of jr(e,"link-entity"))if(!(n.getAttribute("alias")!==t.relatedEntity&&n.getAttribute("name")!==t.relatedEntity)){for(let r of jr(n,"attribute"))if((r.getAttribute("alias")||r.getAttribute("name"))===t.name){n.removeChild(r);return}}return}for(let n of jr(e,"attribute"))if(n.getAttribute("name")===t.name){e.removeChild(n);return}}function N4(e,t,n=!1){let r=o=>o.getAttribute("alias")===t||o.getAttribute("name")===t;for(let o of jr(e,"link-entity"))if(r(o))return o;if(n)return;let i=e.getElementsByTagName("link-entity");for(let o=0;o<i.length;o+=1)if(r(i[o]))return i[o]}function Sbe(e,t,n){let r=N4(t,n);if(r)return r;let i=e.createElement("link-entity");return i.setAttribute("name",n),t.appendChild(i),i}function Nbe(e,t){let n=e.childNodes;for(let r=0;r<n.length;r+=1){let i=n[r];if(i.nodeType===1&&i.tagName!=="attribute"){e.insertBefore(t,i);return}}e.appendChild(t)}function _be(e,t,n){let r=t.getElementsByTagName("row")[0];if(!r)return;let i=[...n].sort((s,u)=>s.order-u.order),o=Ibe(r);if(Tbe(o,i)){for(let s=0;s<i.length;s+=1){let u=String(i[s].width);o[s].getAttribute("width")!==u&&o[s].setAttribute("width",u)}return}let a=new Map;for(let s of o){let u=s.getAttribute("name");u&&a.set(u,s),r.removeChild(s)}for(let s of i){let u=a.get(s.name);u||(u=e.createElement("cell"),u.setAttribute("name",s.name)),u.setAttribute("width",String(s.width)),r.appendChild(u)}}function Ibe(e){return jr(e,"cell").filter(t=>!!t.getAttribute("name")&&t.getAttribute("ishidden")!=="1")}function Tbe(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n].getAttribute("name")!==t[n].name)return!1;return!0}function Obe(e,t,n){let r=t.getElementsByTagName("entity")[0];if(!r)return;let i=(p,m)=>`${p.toLowerCase()}\0${m.toLowerCase()}`,o=new Map,a=new Map,s=(p,m,h)=>{let g=p.get(m);g?g.push(h):p.set(m,[h])},u=null;for(let p of jr(r,"order")){let m=p.getAttribute("attribute")||"";m&&(u||(u=e.createTextNode(""),r.insertBefore(u,p)),s(o,i(p.getAttribute("entityname")||"",m),p),s(a,m.toLowerCase(),p),r.removeChild(p))}let l=new Set,c=(p,m)=>{let h=p.get(m);for(;h&&h.length>0;){let g=h.shift();if(!l.has(g))return l.add(g),g}},d=p=>{var m;let h=a.get(p.toLowerCase());if(!h)return;let g=h.filter(b=>!l.has(b)),y=(m=g.find(b=>!b.getAttribute("entityname")))!==null&&m!==void 0?m:g[0];return y&&l.add(y),y},f=n.map(p=>{let m=String(p.attribute);return p.entityname===void 0?{expression:p,element:void 0}:{expression:p,element:c(o,i(p.entityname,m))}});for(let p of f)p.expression.entityname===void 0&&(p.element=d(String(p.expression.attribute)));for(let{expression:p,element:m}of f){let h=m??e.createElement("order");h.setAttribute("attribute",p.attribute),h.setAttribute("descending",String(p.descending)),p.entityname?h.setAttribute("entityname",p.entityname):p.entityname===""&&h.removeAttribute("entityname"),r.insertBefore(h,u)}u&&r.removeChild(u)}function Dbe(e,t,n){let r=t.getElementsByTagName("entity")[0];if(r){for(let i of jr(r,"filter"))Oy(i)||r.removeChild(i);(n.conditions.length>0||n.groups.length>0)&&r.appendChild(Em(e,n))}}function wm(e,t){return JSON.stringify(e)===JSON.stringify(t)}function Pbe(e,t,n){var r;let i=t.getElementsByTagName("entity")[0];if(!i)return;let o=jr(i,"link-entity").filter(m=>m.getAttribute("name")&&m.getAttribute("from")&&m.getAttribute("to")),a=(m,h)=>m.getAttribute(h)||"",s=new Array(n.length),u=new Set,l=m=>{n.forEach((h,g)=>{if(s[g])return;let y=o.filter(w=>!u.has(w)&&m(w,h));if(y.length!==1)return;let b=y[0];n.some((w,_)=>_!==g&&!s[_]&&m(b,w))||(s[g]=b,u.add(b))})};l((m,h)=>!!h.alias&&a(m,"name")===h.name&&a(m,"alias")===h.alias),l((m,h)=>a(m,"name")===h.name&&a(m,"from")===h.from&&a(m,"to")===h.to),l((m,h)=>a(m,"name")===h.name&&a(m,"from")===h.from),l((m,h)=>a(m,"name")===h.name&&a(m,"to")===h.to),l((m,h)=>a(m,"name")===h.name);let c=n.map((m,h)=>h).filter(m=>!s[m]),d=o.filter(m=>!u.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(n[m].name);h?h.push(m):p.set(n[m].name,[m])}for(let[m,h]of p){let g=(r=f.get(m))!==null&&r!==void 0?r:[];g.length===h.length&&h.forEach((y,b)=>{s[y]=g[b],u.add(g[b])})}n.forEach((m,h)=>{let g=s[h];if(g){h4(e,g,m);return}let y=e.createElement("link-entity");h4(e,y,m),i.appendChild(y)});for(let m of o)u.has(m)||i.removeChild(m)}var Rbe=new Set(["inner","outer"]);function kbe(e,t,n,r){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 u=c=>{let d=r?.get(MN(c));return!!d&&d.every(f=>s.has(f))},l=n.filter(c=>c.relatedEntity&&!o.has(c.relatedEntity)&&!u(c));if(l.length!==0)throw new kl.ValidationError("view",e.id,l.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,dn.issue)(`/columns/${n.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 h4(e,t,n){t.setAttribute("name",n.name),t.setAttribute("from",n.from),t.setAttribute("to",n.to),n.alias?t.setAttribute("alias",n.alias):t.removeAttribute("alias"),n.linkType?t.setAttribute("link-type",n.linkType):Rbe.has(t.getAttribute("link-type")||"")&&t.removeAttribute("link-type");let r=jr(t,"filter").find(o=>!Oy(o)),i=n.filters&&(n.filters.conditions.length>0||n.filters.groups.length>0)?Em(e,n.filters):null;r&&i?t.replaceChild(i,r):r?t.removeChild(r):i&&t.appendChild(i)}function $be(e,t,n,r=e.queryType){var i;let o=new DOMParser().parseFromString("<fetch/>","text/xml"),a=o.documentElement;a.setAttribute("version","1.0"),a.setAttribute("mapping","logical");let s=o.createElement("entity");s.setAttribute("name",e.entityLogicalName),a.appendChild(s);let u=new Map;for(let l of(i=e.linkEntities)!==null&&i!==void 0?i:[]){let c=o.createElement("link-entity");c.setAttribute("name",l.name),c.setAttribute("from",l.from),c.setAttribute("to",l.to),l.alias&&c.setAttribute("alias",l.alias),l.linkType&&c.setAttribute("link-type",l.linkType),l.filters&&(l.filters.conditions.length>0||l.filters.groups.length>0)&&c.appendChild(Em(o,l.filters)),s.appendChild(c);for(let d of[l.alias||l.name,l.name])u.has(d)||u.set(d,c)}for(let l of[...e.columns].sort((c,d)=>c.order-d.order)){let c=o.createElement("attribute");if(l.relatedEntity){S4(c,l);let d=u.get(l.relatedEntity);d||(d=o.createElement("link-entity"),d.setAttribute("name",l.relatedEntity),s.appendChild(d),u.set(l.relatedEntity,d)),d.appendChild(c)}else c.setAttribute("name",l.name),s.appendChild(c)}for(let l of e.sort){let c=o.createElement("order");c.setAttribute("attribute",l.attribute),c.setAttribute("descending",String(l.descending)),l.entityname&&c.setAttribute("entityname",l.entityname),s.appendChild(c)}return(e.filters.conditions.length>0||e.filters.groups.length>0)&&s.appendChild(Em(o,e.filters)),e.findColumns!==void 0&&(n?.state==="modelled"&&s.appendChild(o.importNode(n.filter,!0)),b4(o,a,e,(0,kd.classifyFindFilter)(a),t,r)),new XMLSerializer().serializeToString(o)}function Em(e,t){let n=e.createElement("filter");n.setAttribute("type",t.type);for(let r of t.conditions){let i=e.createElement("condition");i.setAttribute("attribute",r.attribute),i.setAttribute("operator",r.operator),r.entityname&&i.setAttribute("entityname",r.entityname),r.value!==void 0&&i.setAttribute("value",r.value),n.appendChild(i)}for(let r of t.groups)n.appendChild(Em(e,r));return n}function Lbe(e,t){var n;let r=new DOMParser().parseFromString("<grid/>","text/xml"),i=r.documentElement,o=[...e.columns].sort((s,u)=>s.order-u.order);i.setAttribute("name","resultset"),i.setAttribute("jump",((n=o[0])===null||n===void 0?void 0:n.name)||t||`${e.entityLogicalName}id`),i.setAttribute("select","1"),i.setAttribute("icon","1"),i.setAttribute("preview","1");let a=r.createElement("row");a.setAttribute("name","result"),a.setAttribute("id",t||`${e.entityLogicalName}id`),i.appendChild(a);for(let s of o){let u=r.createElement("cell");u.setAttribute("name",s.name),u.setAttribute("width",String(s.width)),a.appendChild(u)}return new XMLSerializer().serializeToString(r)}function Mbe(){return{adapter:new Iy,api:lbe.viewApi,publish:(e,t,n)=>(0,d4.publishBoundEntity)(e,n),publishScope:(e,t)=>(0,d4.boundEntityPublishScope)(t),rebaselineAfterPublish:"bracket"}}$d.viewRegistration=Mbe});function Dy(e,t){return e==="SetFieldValue"&&t!==void 0&&xbe.has(t.attributeType)&&(t.requiredLevel==="None"||t.requiredLevel==="Recommended")}var xbe,xN=B(()=>{"use strict";xbe=new Set(["Integer","Double","Decimal","Money","String","Memo","DateTime","Picklist","Lookup"])});function I4(e){return e!=="Entity"&&e!=="AllForms"&&typeof e=="string"&&e.trim()!==""}function FN(e){return e==="AllForms"||I4(e)?1:2}function UN(e){return I4(e)?e:null}function T4(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:Ld.WorkflowCategory.BusinessRule,type:Ld.WorkflowTypeCode.Definition,mode:1,scope:Ld.WorkflowScope.Organization,primaryentity:e.entityLogicalName,iscrmuiworkflow:!0,processtriggerscope:FN(e.scope),processtriggerformid:UN(e.scope)}}var Ld,O4=B(()=>{"use strict";Ld=Xe(Ds());});function D4(e,t=0){return(lr[e[t+0]]+lr[e[t+1]]+lr[e[t+2]]+lr[e[t+3]]+"-"+lr[e[t+4]]+lr[e[t+5]]+"-"+lr[e[t+6]]+lr[e[t+7]]+"-"+lr[e[t+8]]+lr[e[t+9]]+"-"+lr[e[t+10]]+lr[e[t+11]]+lr[e[t+12]]+lr[e[t+13]]+lr[e[t+14]]+lr[e[t+15]]).toLowerCase()}var lr,P4=B(()=>{lr=[];for(let e=0;e<256;++e)lr.push((e+256).toString(16).slice(1))});function qN(){return Py>Ry.length-16&&((0,R4.randomFillSync)(Ry),Py=0),Ry.slice(Py,Py+=16)}var R4,Ry,Py,k4=B(()=>{R4=require("crypto"),Ry=new Uint8Array(256),Py=Ry.length});var $4,BN,L4=B(()=>{$4=require("crypto"),BN={randomUUID:$4.randomUUID}});function Fbe(e,t,n){if(BN.randomUUID&&!t&&!e)return BN.randomUUID();e=e||{};let r=e.random??e.rng?.()??qN();if(r.length<16)throw new Error("Random bytes length must be >= 16");if(r[6]=r[6]&15|64,r[8]=r[8]&63|128,t){if(n=n||0,n<0||n+16>t.length)throw new RangeError(`UUID byte range ${n}:${n+15} is out of buffer bounds`);for(let i=0;i<16;++i)t[n+i]=r[i];return t}return D4(r)}var Wr,M4=B(()=>{L4();k4();P4();Wr=Fbe});var VN=B(()=>{M4()});var x4=B(()=>{"use strict";});function F4(e){return e!=null&&Ube.has(e)}function ky(e){if(e==null)return!1;let t=e.trim();if(!/^[+-]?\d+$/.test(t))return!1;let n=Number(t);return Number.isInteger(n)&&n>=-2147483648&&n<=2147483647}var Ube,GN=B(()=>{"use strict";Ube=new Set(["Picklist","State","Status"])});var $y=C(oo=>{"use strict";Object.defineProperty(oo,"__esModule",{value:!0});oo.WorkflowConditionOperator=oo.WorkflowAttributeType=oo.SystemStep=oo.FieldRequiredLevelTypes=oo.AttributeDateTimeBehavior=void 0;oo.AttributeDateTimeBehavior={None:0,Dynamic:1,DateOnly:2,StaticTimeZoneInvariant:3,UserLocal:4};oo.FieldRequiredLevelTypes={None:"0",Required:"1",Recommended:"2"};oo.SystemStep={IdentifyContact:"IdentifyContact",IdentifyAccount:"IdentifyAccount",IdentifyCustomer:"IdentifyCustomer",IdentifyCase:"IdentifyCase",Solution:"Solution",Resolve:"Resolve"};oo.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"};oo.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 Ly(e){return e!=null&&q4.includes(e)}function jN(e){return e===Te.WorkflowAttributeType.Integer}function WN(e,t){return t===Te.WorkflowConditionOperator.Equal||t===Te.WorkflowConditionOperator.NotEqual?e:qbe.includes(t)?q4.includes(e)||e===Te.WorkflowAttributeType.DateTime?e:Te.WorkflowAttributeType.String:t===Te.WorkflowConditionOperator.On||t===Te.WorkflowConditionOperator.NotOn?e===Te.WorkflowAttributeType.DateTime?e:Te.WorkflowAttributeType.String:Te.WorkflowAttributeType.String}function B4(e){let t=e.leftWorkflowType??e.valueWorkflowType??Te.WorkflowAttributeType.String,n=Am[e.operator]??Te.WorkflowConditionOperator.Equal;return WN(t,n)}function V4(e,t){let n=e.trim(),i=(n.startsWith("+")||n.startsWith("-")?n.slice(1):n).split(".");if(i.length>2)return!1;let[o,a=""]=i;return o.length===0&&a.length===0||!U4.test(o)||!U4.test(a)||o.length>1&&o.startsWith("0")||o.length>Bbe?!1:t!==Te.WorkflowAttributeType.Integer||i.length===1}var Te,Am,q4,qbe,U4,Bbe,zN=B(()=>{"use strict";Te=Xe($y());Am={Equals:Te.WorkflowConditionOperator.Equal,DoesNotEqual:Te.WorkflowConditionOperator.NotEqual,IsGreaterThan:Te.WorkflowConditionOperator.GreaterThan,IsLessThan:Te.WorkflowConditionOperator.LessThan,IsGreaterThanEqualTo:Te.WorkflowConditionOperator.GreaterThanOrEqual,IsLessThanEqualTo:Te.WorkflowConditionOperator.LessThanOrEqual,Contains:Te.WorkflowConditionOperator.Contains,DoesNotContain:Te.WorkflowConditionOperator.DoesNotContain,BeginsWith:Te.WorkflowConditionOperator.BeginsWith,DoesNotBeginWith:Te.WorkflowConditionOperator.DoesNotBeginWith,EndsWith:Te.WorkflowConditionOperator.EndsWith,DoesNotEndWith:Te.WorkflowConditionOperator.DoesNotEndWith,On:Te.WorkflowConditionOperator.On,NotOn:Te.WorkflowConditionOperator.NotOn,ContainsData:Te.WorkflowConditionOperator.NotNull,DoesNotContainData:Te.WorkflowConditionOperator.IsNull},q4=[Te.WorkflowAttributeType.Decimal,Te.WorkflowAttributeType.Float,Te.WorkflowAttributeType.Integer,Te.WorkflowAttributeType.Money],qbe=[Te.WorkflowConditionOperator.GreaterThan,Te.WorkflowConditionOperator.GreaterThanOrEqual,Te.WorkflowConditionOperator.LessThan,Te.WorkflowConditionOperator.LessThanOrEqual];U4=/^\d*$/,Bbe=28});var G4=B(()=>{"use strict";});function ko(e){return!Vbe.has(e)}function HN(e){return e==="Equals"||e==="DoesNotEqual"}function My(e){return W4.has(e)?Gbe:Kbe.has(e)?jbe:z4.has(e)?Wbe:Ybe.has(e)?Hbe:zbe}function H4(e){return My(e)[0]}function K4(e,t){return My(t).includes(e)}function j4(e){return W4.has(e)?"string":e==="Money"?"money":e==="Integer"||e==="BigInt"?"integer":e==="Decimal"||e==="Double"?"decimal":z4.has(e)?"date":Jbe.has(e)?"boolean":"other"}function xy(e,t){let n=j4(e),r=j4(t);return n==="other"||r==="other"?e===t:n===r}var Vbe,Gbe,jbe,Wbe,zbe,Hbe,W4,Kbe,z4,Jbe,Ybe,Fy=B(()=>{"use strict";G4();Vbe=new Set(["ContainsData","DoesNotContainData"]);Gbe=["Equals","DoesNotEqual","Contains","DoesNotContain","BeginsWith","DoesNotBeginWith","EndsWith","DoesNotEndWith","ContainsData","DoesNotContainData"],jbe=["Equals","DoesNotEqual","IsGreaterThan","IsGreaterThanEqualTo","IsLessThan","IsLessThanEqualTo","ContainsData","DoesNotContainData"],Wbe=["On","NotOn","Equals","DoesNotEqual","IsGreaterThan","IsGreaterThanEqualTo","IsLessThan","IsLessThanEqualTo","ContainsData","DoesNotContainData"],zbe=["Equals","DoesNotEqual","ContainsData","DoesNotContainData"],Hbe=["Equals","DoesNotEqual","Contains","DoesNotContain","BeginsWith","DoesNotBeginWith","EndsWith","DoesNotEndWith","ContainsData","DoesNotContainData"],W4=new Set(["String","Memo","EntityName"]),Kbe=new Set(["Integer","BigInt","Money","Decimal","Double"]),z4=new Set(["DateTime"]),Jbe=new Set(["Boolean"]),Ybe=new Set(["Lookup","Owner","Customer"])});function X4(e){switch(e){case"Boolean":return Ot.WorkflowAttributeType.Boolean;case"Customer":return Ot.WorkflowAttributeType.Customer;case"DateTime":return Ot.WorkflowAttributeType.DateTime;case"Decimal":return Ot.WorkflowAttributeType.Decimal;case"Double":return Ot.WorkflowAttributeType.Float;case"Integer":return Ot.WorkflowAttributeType.Integer;case"Lookup":return Ot.WorkflowAttributeType.Lookup;case"Money":return Ot.WorkflowAttributeType.Money;case"Owner":return Ot.WorkflowAttributeType.Owner;case"Picklist":return Ot.WorkflowAttributeType.Picklist;case"State":return Ot.WorkflowAttributeType.State;case"Status":return Ot.WorkflowAttributeType.Status;case"Uniqueidentifier":case"UniqueIdentifier":return Ot.WorkflowAttributeType.UniqueIdentifier;case"BigInt":return Ot.WorkflowAttributeType.BigType;default:return Ot.WorkflowAttributeType.String}}function o3(e){return e&&e!==Ot.WorkflowAttributeType.String?e:void 0}function Zbe(e){return{__class:i3,parameterName:"primaryEntity",entityName:e}}function J4(e){return{__class:JN,type:KN,typeSet:!1,behavior:Ot.AttributeDateTimeBehavior.None,method:Z4,parameters:[e]}}function Y4(e,t,n=Ot.WorkflowAttributeType.String){return{__class:t3,type:n,behavior:Ot.AttributeDateTimeBehavior.None,typeSet:!1,entity:Zbe(t),attributeName:e}}function eve(e,t=Ot.WorkflowAttributeType.String){return{__class:n3,type:t,behavior:Ot.AttributeDateTimeBehavior.None,typeSet:!1,primitiveValue:e}}function tve(e){return{__class:r3,type:KN,typeSet:!1,behavior:Ot.AttributeDateTimeBehavior.None,days:e,hours:"0",minutes:"0",months:"0",years:"0"}}function a3(e,t){let n=Qbe[e.operator],r=J4(Y4(e.leftField,t,e.leftWorkflowType)),i;e.dateArithmetic?i=tve(e.right.value??"0"):e.right.kind==="field"?i=Y4(e.right.field??"",t,e.right.workflowType):i=eve(e.right.value??"",e.right.workflowType??e.leftWorkflowType);let o=J4(i);return{__class:JN,type:KN,typeSet:!1,behavior:Ot.AttributeDateTimeBehavior.None,method:e3,parameters:[n,r,o]}}function s3(e){return typeof e=="object"&&e.__class===JN}function nve(e){return typeof e=="object"&&e.__class===r3}function Uy(e){return s3(e)&&e.method===Z4&&e.parameters.length>0?Uy(e.parameters[0]):e}function Q4(e){if(typeof e!="object"||e.__class!==t3)return null;let t=e.entity;if(t&&t.__class&&t.__class!==i3)return null;let n=e.attributeName;return n?{field:n,workflowType:o3(e.type)}:null}function u3(e){if(!e)return null;let t=Uy(e);if(!s3(t)||t.method!==e3||t.parameters.length!==3)return null;let n=t.parameters[0],r=Xbe[String(n)];if(!r)return null;let i=Q4(Uy(t.parameters[1]));if(!i)return null;let o=Uy(t.parameters[2]);if(nve(o))return r!=="+"&&r!=="-"?null:{leftField:i.field,leftWorkflowType:i.workflowType,operator:r,right:{kind:"value",value:String(o.days??"")},dateArithmetic:!0};let a=Q4(o);if(a)return{leftField:i.field,leftWorkflowType:i.workflowType,operator:r,right:{kind:"field",field:a.field,workflowType:a.workflowType}};if(typeof o=="object"&&o.__class===n3){let s=o.primitiveValue;return{leftField:i.field,leftWorkflowType:i.workflowType,operator:r,right:{kind:"value",value:s!=null?String(s):"",workflowType:o3(o.type)}}}return null}function QN(e){let t=(e??"").trim();if(!/^\d+$/.test(t))return!1;let n=Number(t);return Number.isSafeInteger(n)&&n>=YN&&n<=Md}function $l(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&&!QN(t)?"invalidDayCount":null}function xd(e){return $l(e)===null}var Ot,Z4,e3,KN,t3,n3,JN,r3,i3,Qbe,Xbe,YN,Md,Cm=B(()=>{"use strict";Ot=Xe($y());Fy();Z4="0",e3="3",KN="0",t3="EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions",n3="PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions",JN="MethodCallExpression:#Microsoft.Crm.Workflow.Expressions",r3="TimeSpanExpression:#Microsoft.Crm.Workflow.Expressions",i3="PrimaryEntity:#Microsoft.Crm.Workflow.Expressions";Qbe={"+":0,"-":1,"*":2,"/":3},Xbe={0:"+",1:"-",2:"*",3:"/"};YN=0,Md=2147483647});function ive(e){return e.startsWith("__")&&!rve.has(e)}function ove(e){let t=Object.create(null);return Object.keys(e).forEach(n=>{ive(n)&&(t[n]=e[n])}),Object.keys(t).length>0?t:void 0}function A3(e){return e.__class==="BinaryExpression:#Microsoft.Crm.Workflow.Expressions"}function Ml(e){return e.__class==="UnaryExpression:#Microsoft.Crm.Workflow.Expressions"}function qy(e){return A3(e)||Ml(e)}function ave(e){return e.__class==="ConditionBranchStep:#Microsoft.Crm.Workflow.ObjectModel"}function Sm(){return{list:[]}}function XN(e,t,n){return e&&e.list.length>0?{list:[{...e.list[0],description:t},...e.list.slice(1)]}:{list:[{labelId:Wr(),languageCode:n,description:t}]}}function e_(e){return{__class:"PrimaryEntity:#Microsoft.Crm.Workflow.Expressions",parameterName:"primaryEntity",entityName:e}}function jy(e,t,n,r=re.AttributeDateTimeBehavior.None){return{__class:"EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions",type:n,behavior:r,typeSet:!1,entity:e_(t),attributeName:e}}function Ll(e,t,n=re.AttributeDateTimeBehavior.None){return{__class:"PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions",type:t,behavior:n,typeSet:!1,primitiveValue:e}}function lve(e){return e.bpfField==="StageCategory"?e.stageType==="SelectedStage"?N3:S3:C3}function _3(e){return e.bpfField==="StageCategory"?re.WorkflowAttributeType.BpfStageCategory:re.WorkflowAttributeType.BpfProcess}function cve(e,t){let n=_3(e),r=e.bpfField==="StageCategory"?{__class:"EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions",type:n,behavior:re.AttributeDateTimeBehavior.None,typeSet:!1,entity:{__class:"RelatedEntity:#Microsoft.Crm.Workflow.Expressions",parameterName:`related_${c3}_${l3}`,entityName:l3,relatedAttributeName:c3},attributeName:uve}:jy(sve,t,n);return{__class:"MethodCallExpression:#Microsoft.Crm.Workflow.Expressions",type:n,behavior:re.AttributeDateTimeBehavior.None,typeSet:!1,method:r_,parameters:[lve(e),r]}}function I3(e){let t=e;if(t.__class!=="MethodCallExpression:#Microsoft.Crm.Workflow.Expressions"||String(t.method)!==r_)return null;let n=(t.parameters??[])[0];if(typeof n!="string")return null;let r=n.replace(/^"+|"+$/g,"");return r===S3?{bpfField:"StageCategory",stageType:"ActiveStage"}:r===N3?{bpfField:"StageCategory",stageType:"SelectedStage"}:r===C3?{bpfField:"ProcessName"}:null}function By(e){if(!e)return!1;let t=e;if(t.__class==="MethodCallExpression:#Microsoft.Crm.Workflow.Expressions"&&String(t.method)===r_){let n=(t.parameters??[])[0];if(typeof n=="string"&&dve.has(n.replace(/^"+|"+$/g,"")))return!0}return Ml(e)?By(e.operand):A3(e)?By(e.left)||(e.right??[]).some(By):!1}function T3(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 fve(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 d3(e){if(!e)return!1;switch(e.__class){case"EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions":return T3(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 pve(e){let t=n_[e.conditionOperatoroperator];if(!t)return!1;let n=t==="ContainsData"||t==="DoesNotContainData";if(Ml(e))return n&&f3(e.operand,!0);let r=e.right??[];return r.length!==(n?0:1)?!1:f3(e.left,n,r[0])}function f3(e,t,n){return I3(e)||T3(e)?t||d3(n):!1}function t_(e){if(!e||!qy(e))return!1;let t=e.conditionOperatoroperator;if(!Ml(e)&&(t===re.WorkflowConditionOperator.LogicalAnd||t===re.WorkflowConditionOperator.LogicalOr)){let n=e.right??[];return n.length>0&&t_(e.left)&&n.every(t_)}return pve(e)}function p3(e){return!e||fve(e)?!1:By(e)||!t_(e)}function O3(e){return{__class:"LookupExpression:#Microsoft.Crm.Workflow.Expressions",type:e.workflowType??re.WorkflowAttributeType.Lookup,behavior:re.AttributeDateTimeBehavior.None,typeSet:!1,entityType:e.entityType,label:e.label??"",staticValue:Ll(e.id.replace(/[{}]/g,""),re.WorkflowAttributeType.UniqueIdentifier)}}function hve(e){return e===re.WorkflowAttributeType.DateTime?re.AttributeDateTimeBehavior.DateOnly:re.AttributeDateTimeBehavior.None}function gve(e,t){if(t!==re.WorkflowAttributeType.DateTime)return re.AttributeDateTimeBehavior.None;let n=e.leftDateTimeBehavior;return n!==void 0&&n!==re.AttributeDateTimeBehavior.None?n:hve(t)}function yve(e,t,n){if(t!==re.WorkflowAttributeType.DateTime)return re.AttributeDateTimeBehavior.None;let r=e.valueFieldDateTimeBehavior;return r!==void 0&&r!==re.AttributeDateTimeBehavior.None?r:n}function vve(e){let t=e.trim().toLowerCase();if(t==="true"||t==="1")return"1";if(t==="false"||t==="0")return"0"}function Ive(e){let t=_ve.exec(e);if(t)return`${t[1]}T${t[2]}`;let n=Nve.exec(e);if(!n)return;let[,r,i,o,a,s,u]=n,l=Sve.indexOf(i.toLowerCase());if(l<0)return;let c=String(l+1).padStart(2,"0");return`${o}-${c}-${r}T${a}:${s}:${u}`}function Tve(e){let t=Ive(e.trim());return t!==void 0&&D3(t)?t:e}function D3(e){let t=e.trim(),n=t.indexOf("T")>=0?"T":" ",r=t.indexOf(n),i=r>=0?t.slice(0,r):t,o=r>=0?t.slice(r+1):"";if(!wve.test(i)||o.length>0&&!Eve.test(o)&&!Ave.test(o)&&!Cve.test(o))return!1;let[a,s,u]=i.split("-"),l=new Date(`${a}-${s}-${u}T00:00:00Z`);return!Number.isNaN(l.getTime())&&l.getUTCFullYear()===Number(a)&&l.getUTCMonth()+1===Number(s)&&l.getUTCDate()===Number(u)}function Ove(e,t){let n={value:e,type:re.WorkflowAttributeType.String};if(t===re.WorkflowAttributeType.String||bve.includes(t)||e.trim().length===0)return n;if(t===re.WorkflowAttributeType.Boolean){let r=vve(e);return r==null?n:{value:r,type:t}}return mve.includes(t)?ky(e)?{value:e.trim(),type:t}:n:Ly(t)?{value:e.trim(),type:t}:t===re.WorkflowAttributeType.DateTime&&D3(e)?{value:e.trim(),type:t}:n}function m3(e){return e==="ContainsData"||e==="DoesNotContainData"}function h3(e){return Dve.has(e)}function g3(e,t){return{__class:"UnaryExpression:#Microsoft.Crm.Workflow.Expressions",type:re.WorkflowAttributeType.Boolean,behavior:re.AttributeDateTimeBehavior.None,typeSet:!1,conditionOperatoroperator:t,operand:e}}function y3(e,t){let n=e.leftWorkflowType??e.valueWorkflowType??re.WorkflowAttributeType.String,r=Am[e.operator]??re.WorkflowConditionOperator.Equal,i=gve(e,n),o=WN(n,r);if(e.source==="BusinessProcess"){let u=cve(e,t);if(m3(e.operator))return g3(u,r);let l=_3(e);return{__class:"BinaryExpression:#Microsoft.Crm.Workflow.Expressions",type:re.WorkflowAttributeType.Boolean,behavior:re.AttributeDateTimeBehavior.None,typeSet:!1,conditionOperatoroperator:r,left:u,right:[Ll(e.value??"",l)]}}let a=jy(e.field,t,n,i);if(m3(e.operator))return g3(a,r);let s;if(e.valueType==="Field"&&e.valueField){let u=h3(o)&&h3(e.valueFieldWorkflowType??"")?e.valueFieldWorkflowType:o;s=[jy(e.valueField,t,u,yve(e,u,i))]}else if(e.valueType==="Lookup"){if(!e.lookupValue)throw new Error("Lookup condition is missing its record value.");s=[O3(e.lookupValue)]}else if(e.valueType==="Clear")s=[Ll(null,re.WorkflowAttributeType.String,i)];else if(e.valueType==="Expression")s=[Gy(e.valueType,e.value,e.valueField,t,e.expression,e.rawExpression)];else{let u=Ove(e.value??"",o);s=[Ll(u.value,u.type,i)]}return{__class:"BinaryExpression:#Microsoft.Crm.Workflow.Expressions",type:re.WorkflowAttributeType.Boolean,behavior:re.AttributeDateTimeBehavior.None,typeSet:!1,conditionOperatoroperator:r,left:a,right:s}}function Pve(){return Ll(!0,re.WorkflowAttributeType.Boolean)}function Rve(e,t,n){if(e.length===0)return null;let r=y3(e[0],n);for(let i=1;i<e.length;i++){let o=e[i].connector??t;r={__class:"BinaryExpression:#Microsoft.Crm.Workflow.Expressions",type:re.WorkflowAttributeType.Boolean,behavior:re.AttributeDateTimeBehavior.None,typeSet:!1,conditionOperatoroperator:o==="AND"?re.WorkflowConditionOperator.LogicalAnd:re.WorkflowConditionOperator.LogicalOr,left:r,right:[y3(e[i],n)]}}return r}function Vy(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===re.WorkflowAttributeType.Boolean){let n=t.trim().toLowerCase();if(n==="1"||n==="true")return{valueType:"Value",value:"true",valueWorkflowType:e.type};if(n==="0"||n==="false")return{valueType:"Value",value:"false",valueWorkflowType:e.type}}return e.type===re.WorkflowAttributeType.DateTime?{valueType:"Value",value:Tve(t),valueWorkflowType:e.type}:{valueType:"Value",value:t,valueWorkflowType:e.type}}if(e.__class==="LookupExpression:#Microsoft.Crm.Workflow.Expressions"){let t=e.staticValue,n=typeof t=="object"&&t?.__class==="PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions"?t.primitiveValue:t;return{valueType:"Lookup",lookupValue:{entityType:e.entityType,id:String(n??""),label:e.label,...e.type!==re.WorkflowAttributeType.Lookup?{workflowType:e.type}:{}}}}if(e.__class==="MethodCallExpression:#Microsoft.Crm.Workflow.Expressions"){let t=u3(e);return t?{valueType:"Expression",expression:t}:{valueType:"Expression",rawExpression:e}}return{valueType:"Value",value:""}}function kve(e){let t=n_[e.conditionOperatoroperator]??"Equals",n=t==="ContainsData"||t==="DoesNotContainData",r=Ml(e)?e.operand:e.left,i=Ml(e)?[]:e.right??[],o=I3(r);if(o){let g=i[0];return{id:Wr(),field:"",fieldDisplayName:"",source:"BusinessProcess",bpfField:o.bpfField,...o.stageType?{stageType:o.stageType}:{},operator:t,valueType:"Value",value:g?.primitiveValue!=null&&!n?String(g.primitiveValue):""}}let a=r.__class==="EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions",s=r.__class==="EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions"?r.attributeName:"",u=a?r.type:void 0,l=n?{valueType:"Value"}:Vy(i[0]),c=u,d=a&&r.type===re.WorkflowAttributeType.DateTime&&r.behavior!==re.AttributeDateTimeBehavior.None?r.behavior:void 0,f=l.valueWorkflowType??u,p=n?void 0:i[0],h=p?.__class==="EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions"&&p.type===re.WorkflowAttributeType.DateTime&&p.behavior!==re.AttributeDateTimeBehavior.None?p.behavior:void 0;return{id:Wr(),field:s,fieldDisplayName:s,operator:t,...l,...f?{valueWorkflowType:f}:{},...c?{leftWorkflowType:c}:{},...d!==void 0?{leftDateTimeBehavior:d}:{},...h!==void 0?{valueFieldDateTimeBehavior:h}:{}}}function b3(e){if(!e||!qy(e))return{clauses:[],logic:"AND"};let t=[],n=(o,a)=>{let s=o.conditionOperatoroperator;if(Ml(o)||s!==re.WorkflowConditionOperator.LogicalAnd&&s!==re.WorkflowConditionOperator.LogicalOr){t.push({...kve(o),...a?{connector:a}:{}});return}let u=s===re.WorkflowConditionOperator.LogicalAnd?"AND":"OR";qy(o.left)&&n(o.left,a),(o.right??[]).filter(qy).forEach(l=>n(l,u))};n(e,void 0);let i=t.slice(1).map(o=>o.connector??"AND")[0]??"AND";return{clauses:t,logic:i}}function Gy(e,t,n,r,i,o,a,s){if(e==="Field"&&n)return jy(n,r,re.WorkflowAttributeType.String);if(e==="Expression"){if(i)return a3(i,r);if(o!=null)return o}return e==="Lookup"&&a?O3(a):e==="Clear"?Ll(null,s??re.WorkflowAttributeType.String):Ll(t??"",re.WorkflowAttributeType.String)}function ZN(e,t){return{propertyName:e,propertyValueExpr:t}}function Fd(e){return`Step_${e.value++}`}function ao(e,t){let n=(t.counts[e]??0)+1,r=`${e}${n}`;for(;t.used.has(r);)n+=1,r=`${e}${n}`;return t.counts[e]=n,t.used.add(r),r}function v3(e,t,n){return e&&!n.used.has(e)?(n.used.add(e),e):ao(t,n)}function $ve(e){return e===E3.StateCode.Activated?"Active":"Draft"}function Lve(e){let t={},n=e;typeof n.ismanaged=="boolean"&&(t.isManaged=n.ismanaged);let r=n.iscustomizable;return typeof r=="boolean"?t.isCustomizable=r:r!==null&&typeof r=="object"&&typeof r.Value=="boolean"&&(t.isCustomizable=r.Value),t}function Mve(e,t){let n=e.processtriggerscope,r=e.processtriggerformid;return n===1?r&&r.trim()!==""?r:"AllForms":n===2?"Entity":t??"Entity"}function P3(e,t=1033){return new Ud({languageCode:t}).serialize(e)}function R3(e){return new Ud().deserialize(e)}var E3,re,rve,n_,r_,C3,S3,N3,sve,uve,l3,c3,dve,mve,bve,wve,Eve,Ave,Cve,Sve,Nve,_ve,Dve,i_,Ud,o_=B(()=>{"use strict";VN();E3=Xe(Ds());x4();GN();zN();Cm();re=Xe($y());rve=new Set(["__class"]);n_={};for(let e of Object.keys(Am))n_[Am[e]]=e;r_="23",C3="BpfProcess",S3="ActiveStageCategory",N3="SelectedStageCategory",sve="processid",uve="stagecategory",l3="processstage",c3="stageid";dve=new Set(["ActiveStage","SelectedStage","Stage"]);mve=[re.WorkflowAttributeType.Picklist,re.WorkflowAttributeType.State,re.WorkflowAttributeType.Status];bve=[re.WorkflowAttributeType.Lookup,re.WorkflowAttributeType.Customer,re.WorkflowAttributeType.Owner];wve=/^\d{4}-\d{2}-\d{2}$/,Eve=/^\d{2}:\d{2}$/,Ave=/^\d{2}:\d{2}:\d{2}$/,Cve=/^\d{2}:\d{2}:\d{2}\.\d{1,7}$/,Sve=["jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"],Nve=/^[A-Za-z]{3}, (\d{2}) ([A-Za-z]{3}) (\d{4}) (\d{2}):(\d{2}):(\d{2}) GMT$/,_ve=/^(\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$/;Dve=new Set([re.WorkflowAttributeType.Lookup,re.WorkflowAttributeType.Owner,re.WorkflowAttributeType.Customer]);i_={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"};Ud=class{resolveLabel;languageCode;entityName="";stepCounter={value:0};idCounter={counts:{},used:new Set};constructor(t={}){this.resolveLabel=t.resolveLabel??(n=>i_[n]),this.languageCode=t.languageCode??1033}label(t){return this.resolveLabel(t)}serialize(t){let n=t.wfomRoot;this.entityName=t.entityLogicalName,this.stepCounter={value:n?Number(n.nextStepIndex):1},this.idCounter={counts:{},used:new Set};let r=t.scope!=="Entity"&&t.scope!=="AllForms"?t.scope:null,i=t.rootCondition?[this.serializeConditionNode(t.rootCondition)]:[],o={...n?.reservedProperties??{},__class:"WorkflowStep:#Microsoft.Crm.Workflow.ObjectModel",id:n?.id??t.ruleId??Wr(),name:n?.name??"Step_0",description:n!==void 0?n.description:t.description||null,stepLabels:Sm(),argumentsArray:[],primaryEntityName:n?.primaryEntityName??this.entityName,nextStepIndex:String(this.stepCounter.value),isCrmUIWorkflow:!0,category:n?.category??"2",businessProcessType:n?.businessProcessType??"0",mode:n?.mode??"0",title:n?.title??t.name,formId:r,workflowEntityId:n?.workflowEntityId??t.ruleId??"",variables:n?.variables??[],inputs:n?.inputs??[],steps:{list:i}};return JSON.stringify(o)}makeApplyActionStep(t){return{__class:"SetAttributeValueStep:#Microsoft.Crm.Workflow.ObjectModel",id:ao("SetAttributeValueStep",this.idCounter),description:t.displayName||"New Action",name:t.stepName??Fd(this.stepCounter),stepLabels:{list:[]},specification:ZN(t.field,Gy(t.valueType,t.value,t.valueField,this.entityName,t.expression,t.rawExpression,t.lookupValue,t.valueWorkflowType)),entity:e_(this.entityName)}}makeRecommendationActionStep(t,n,r){let i=n.map(u=>this.makeApplyActionStep(u)),o=t??"",a=r?.stepLabels,s=XN(a,o,this.languageCode);return{__class:"ActionStep:#Microsoft.Crm.Workflow.ObjectModel",id:v3(r?.id,"ActionStep",this.idCounter),name:r?.name??Fd(this.stepCounter),description:r?.description??"Action step",stepLabels:s,steps:{list:i},actionId:null,actionType:r?.actionType??"4",processId:r?.processId??Wr(),uniqueName:r?.uniqueName??`id_${Wr().replace(/-/g,"")}ActionStep`}}serializeAction(t){let n=e_(this.entityName),r=t.stepName??Fd(this.stepCounter),i=t.stepLabels??Sm(),o={name:r,stepLabels:i,description:t.displayName},a=t.type;switch(a){case"SetFieldValue":return{...o,id:ao("SetAttributeValueStep",this.idCounter),__class:"SetAttributeValueStep:#Microsoft.Crm.Workflow.ObjectModel",entity:n,specification:ZN(t.field,Gy(t.valueType,t.value,t.valueField,this.entityName,t.expression,t.rawExpression,t.lookupValue,t.valueWorkflowType))};case"SetDefaultValue":return{...o,id:ao("SetDefaultValueStep",this.idCounter),__class:"SetDefaultValueStep:#Microsoft.Crm.Workflow.ObjectModel",entity:n,specification:ZN(t.field,Gy(t.valueType,t.value,t.valueField,this.entityName,t.expression,t.rawExpression,t.lookupValue,t.valueWorkflowType))};case"LockUnlock":return{...o,id:ao("SetDisplayModeStep",this.idCounter),__class:"SetDisplayModeStep:#Microsoft.Crm.Workflow.ObjectModel",controlId:t.field,controlType:"standard",isReadOnly:t.lock,entity:n};case"SetBusinessRequired":return{...o,id:ao("SetFieldRequiredLevelStep",this.idCounter),__class:"SetFieldRequiredLevelStep:#Microsoft.Crm.Workflow.ObjectModel",controlId:t.field,controlType:"standard",requiredLevel:t.required?re.FieldRequiredLevelTypes.Required:re.FieldRequiredLevelTypes.None,entity:n};case"SetVisibility":return{...o,id:ao("SetVisibilityStep",this.idCounter),__class:"SetVisibilityStep:#Microsoft.Crm.Workflow.ObjectModel",controlId:t.field,controlType:"standard",isVisible:t.visible,entity:n};case"ShowErrorMessage":{let s=t.errorMessage||t.displayName,u=XN(t.stepLabels,s,this.languageCode);return{...o,id:ao("SetMessageStep",this.idCounter),__class:"SetMessageStep:#Microsoft.Crm.Workflow.ObjectModel",stepLabels:u,name:s,controlId:t.field,entity:n,level:t.messageLevel??"error",actionSteps:t.messageActionSteps??{list:[]}}}case"Recommendation":{let s=t.messageText??t.recommendationTitle??t.displayName,u=XN(t.stepLabels,s,this.languageCode),l={list:[this.makeRecommendationActionStep(t.acceptanceText,t.applyActions??[],t.recommendationActionStepMeta)]};return{...o,id:ao("SetMessageStep",this.idCounter),__class:"SetMessageStep:#Microsoft.Crm.Workflow.ObjectModel",stepLabels:u,description:t.recommendationTitle||t.displayName,controlId:t.field,entity:n,level:"RECOMMENDATION",actionSteps:l}}default:throw new Error(`Unsupported action type: ${a}`)}}serializeConditionNode(t){let n=t.stepName??Fd(this.stepCounter),r=ao("ConditionStep",this.idCounter),i=[],o=t,a=!0;for(;o;){let s=o.rawConditionExpression??Rve(o.clauses,o.logic,this.entityName),u=a?o.branchName??Fd(this.stepCounter):Fd(this.stepCounter),c={__class:"ConditionBranchStep:#Microsoft.Crm.Workflow.ObjectModel",id:a?v3(o.branchId,"ConditionBranchStep",this.idCounter):ao("ConditionBranchStep",this.idCounter),name:u,description:o.displayName,stepLabels:Sm(),conditionExpression:s??(a?Pve():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:r,name:n,description:"",stepLabels:Sm(),containsElsebranch:i.length>1,steps:{list:i}}}makeTerminalElseBranch(t){return{__class:"ConditionBranchStep:#Microsoft.Crm.Workflow.ObjectModel",id:ao("ConditionBranchStep",this.idCounter),name:"Else",description:null,stepLabels:Sm(),conditionExpression:void 0,steps:{list:t.map(n=>this.serializeBranchItem(n))}}}serializeBranchItem(t){return t.kind==="condition"?this.serializeConditionNode(t):this.serializeAction(t)}deserialize(t){let n=t,r=null,i;if(t.wfomJson)try{let o=JSON.parse(t.wfomJson);i={id:o.id==="WorkflowStep0"||!o.id?t.workflowid??Wr():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:ove(o)};let s=(o.steps?.list??[]).find(u=>u.__class==="ConditionStep:#Microsoft.Crm.Workflow.ObjectModel");s&&(r=this.deserializeConditionStep(s))}catch{}return{ruleId:t.workflowid??null,name:t.name??"",description:t.description??"",entityLogicalName:t.primaryentity??"",scope:Mve(n,i?.formId),status:$ve(t.statecode),rootCondition:r,wfomRoot:i,...Lve(t)}}deserializeConditionStep(t){let n=(t.steps?.list??[]).filter(ave);return this.buildConditionNodeFromBranches(n,t,!0)}buildConditionNodeFromBranches(t,n,r){let[i,...o]=t,{clauses:a,logic:s}=b3(i?.conditionExpression),u=this.deserializeBranch(i?.steps?.list??[]),l=this.deserializeElseChain(o,n),c=i?.description||i?.name||n.description||n.name||this.label("condition");return{kind:"condition",id:(r?n.id:i?.id)??Wr(),displayName:c,clauses:a,logic:s,trueBranch:u,falseBranch:l,isCollapsed:!1,stepName:r?n.name:void 0,branchId:r?i?.id:void 0,branchName:r?i?.name:void 0,...p3(i?.conditionExpression)?{rawConditionExpression:i?.conditionExpression}:{}}}deserializeElseChain(t,n){if(t.length===0)return[];let[r]=t,{clauses:i}=b3(r.conditionExpression);return i.length===0&&!p3(r.conditionExpression)?this.deserializeBranch(r.steps?.list??[]):[this.buildConditionNodeFromBranches(t,n,!1)]}deserializeBranch(t){return t.map(n=>n.__class==="ConditionStep:#Microsoft.Crm.Workflow.ObjectModel"?this.deserializeConditionStep(n):this.deserializeAction(n)).filter(n=>n!==null)}parseRecommendationApplyActions(t){let r=(t?.list??[])[0];if(!r)return{applyActions:[]};let i={id:r.id,name:r.name,description:r.description??void 0,stepLabels:r.stepLabels,processId:r.processId,uniqueName:r.uniqueName,actionType:r.actionType},o=r.stepLabels?.list,a=o&&o.length>0?o[0].description??"":"";return{applyActions:(r.steps?.list??[]).filter(u=>u.__class==="SetAttributeValueStep:#Microsoft.Crm.Workflow.ObjectModel").map(u=>{let l=u.specification;return{id:u.id||Wr(),field:l?.propertyName??"",stepName:u.name??void 0,displayName:u.description??void 0,...Vy(l?.propertyValueExpr)}}),meta:i,acceptanceText:a}}deserializeAction(t){switch(t.__class){case"SetAttributeValueStep:#Microsoft.Crm.Workflow.ObjectModel":{let n=Vy(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,...n}}case"SetDefaultValueStep:#Microsoft.Crm.Workflow.ObjectModel":{let n=Vy(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,...n}}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!==re.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 n=t.stepLabels?.list,r=n&&n.length>0?n[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:r,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:r||t.name||"",messageLevel:t.level??void 0,messageActionSteps:t.actionSteps}}case"ActionStep:#Microsoft.Crm.Workflow.ObjectModel":{let{applyActions:n,meta:r,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:n,recommendationActionStepMeta:r}}default:return null}}}});var k3=B(()=>{"use strict";});function Bve(e){return typeof e=="object"&&e!==null?e:null}function qd(e){let t=Bve(e);if(!t)return!1;if(t.__class===Uve){let n=t;return String(n.method)===qve?!0:Array.isArray(n.parameters)&&n.parameters.some(qd)}if(t.__class===Fve)return qd(t.operand);if(t.__class===xve){let n=t;return qd(n.left)||Array.isArray(n.right)&&n.right.some(qd)}return!1}var xve,Fve,Uve,qve,$3=B(()=>{"use strict";k3();xve="BinaryExpression:#Microsoft.Crm.Workflow.Expressions",Fve="UnaryExpression:#Microsoft.Crm.Workflow.Expressions",Uve="MethodCallExpression:#Microsoft.Crm.Workflow.Expressions",qve="23"});function l_(e){return Vve.has(e.type)}function a_(e,t,n,r,i,o,a){let s=i.get(n);!s||!x3.has(s.attributeType)||r!=="Value"||a?.operator&&!HN(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 Gve(e,t){let n=t.get(e.field);return!!n&&x3.has(n.attributeType)&&HN(e.operator)}function s_(e){return!!(e?.entityType?.trim()&&e.id?.trim())}function u_(e,t,n){return{nodeId:e,kind:"INVALID_DAY_COUNT",message:`Please enter a whole number of days between 0 and ${Md}.`,target:t,itemId:n,messageKey:"Validation.InvalidDayCount",messageParams:{max:Md}}}function L3(e,t,n,r,i,o,a,s){if(i!=="Clear")return;let u=o.get(r);Dy(n,u)||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 zy(e){if(!e)return!1;for(let t of[...e.trueBranch,...e.falseBranch])if(t.kind==="action"){if(l_(t))return!0}else if(zy(t))return!0;return!1}function c_(e,t){if(e.id===t)return e;for(let n of[...e.trueBranch,...e.falseBranch]){if(n.id===t)return n;if(n.kind==="condition"){let r=c_(n,t);if(r)return r}}return null}function jve(e){if(!e||typeof e!="object")return!1;let{__class:t,primitiveValue:n}=e;return t!=="PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions"?!1:n===!0||typeof n=="string"&&n.toLowerCase()==="true"}function Wve(e){return e.clauses.length===0&&(e.rawConditionExpression===void 0||jve(e.rawConditionExpression))}function Hve(e){return!!e.clauses?.some(t=>t.source==="BusinessProcess")||qd(e.rawConditionExpression)}function Bd(e,t){for(let n=0;n<e.trueBranch.length;n++){let r=e.trueBranch[n];if(r.id===t)return{node:e,branch:"true",index:n};if(r.kind==="condition"){let i=Bd(r,t);if(i)return i}}for(let n=0;n<e.falseBranch.length;n++){let r=e.falseBranch[n];if(r.id===t)return{node:e,branch:"false",index:n};if(r.kind==="condition"){let i=Bd(r,t);if(i)return i}}return null}function d_(e,t){return{...e,trueBranch:M3(e.trueBranch,t),falseBranch:M3(e.falseBranch,t)}}function M3(e,t){return e.filter(n=>n.id!==t).map(n=>n.kind==="condition"?d_(n,t):n)}function wu(e,t,n){return e.id===t?n(e):{...e,trueBranch:e.trueBranch.map(r=>r.kind==="condition"?wu(r,t,n):r),falseBranch:e.falseBranch.map(r=>r.kind==="condition"?wu(r,t,n):r)}}function Wy(e,t,n){return{...e,trueBranch:e.trueBranch.map(r=>r.kind==="action"&&r.id===t?n(r):r.kind==="condition"?Wy(r,t,n):r),falseBranch:e.falseBranch.map(r=>r.kind==="action"&&r.id===t?n(r):r.kind==="condition"?Wy(r,t,n):r)}}function F3(e,t,n,r){return wu(e,t,i=>({...i,trueBranch:n==="true"?[...i.trueBranch,r]:i.trueBranch,falseBranch:n==="false"?[...i.falseBranch,r]:i.falseBranch}))}function f_(e){return e.length===1&&e[0].kind==="condition"}function Jve(e){let t=0,n=e??void 0;for(;n;){t+=1;let{falseBranch:r}=n;if(f_(r)){n=r[0];continue}r.length>0&&(t+=1),n=void 0}return t}function Yve(e){return!!e&&Jve(e)<Kve}function Qve(e,t){if(!e)return;let n=(r,i)=>{if(r.id===t)return i;let o=[];if(f_(r.falseBranch)){let a=n(r.falseBranch[0],i);if(a)return a}else o.push(...r.falseBranch.filter(a=>a.kind==="condition"));o.push(...r.trueBranch.filter(a=>a.kind==="condition"));for(let a of o){let s=n(a,a);if(s)return s}};return n(e,e)}function U3(e,t,n){let r=Qve(e,t);return!r||!Yve(r)?e:wu(e,t,i=>q3(i,n))}function q3(e,t){if(f_(e.falseBranch))return{...e,falseBranch:[q3(e.falseBranch[0],t)]};let n=p_(t);return n.falseBranch=e.falseBranch,{...e,falseBranch:[n]}}function B3(e,t){let n=Bd(e,t);if(!n||n.branch!=="false")return e;let r=n.node.falseBranch[n.index];if(!r||r.kind!=="condition")return e;let i=r.falseBranch;return wu(e,n.node.id,o=>({...o,falseBranch:i}))}function V3(e,t,n){let r=Bd(e,t);if(!r)return e;let i=o=>{let a=[...o],s=a[r.index+n];return s?(a[r.index+n]=a[r.index],a[r.index]=s,a):o};return wu(e,r.node.id,o=>({...o,trueBranch:r.branch==="true"?i(o.trueBranch):o.trueBranch,falseBranch:r.branch==="false"?i(o.falseBranch):o.falseBranch}))}function p_(e){return{kind:"condition",id:Wr(),displayName:e??"New Condition",clauses:[],logic:"AND",trueBranch:[],falseBranch:[],isCollapsed:!1}}function G3(e,t){let n={kind:"action",id:Wr(),type:e,displayName:t??`New ${e}`};switch(e){case"Recommendation":return{...n,type:"Recommendation",field:"",recommendationTitle:"",messageText:"",applyActions:[{id:Wr(),field:"",valueType:"Value",value:""}]};case"LockUnlock":return{...n,type:"LockUnlock",field:"",lock:!0};case"ShowErrorMessage":return{...n,type:"ShowErrorMessage",field:"",errorMessage:""};case"SetFieldValue":return{...n,type:"SetFieldValue",field:"",valueType:"Value",value:""};case"SetDefaultValue":return{...n,type:"SetDefaultValue",field:"",valueType:"Value",value:""};case"SetBusinessRequired":return{...n,type:"SetBusinessRequired",field:"",required:!0};case"SetVisibility":return{...n,type:"SetVisibility",field:"",visible:!0};default:return{...n,type:"SetFieldValue",field:"",valueType:"Value",value:""}}}function j3(e){if(!e)return[];let t=[];return W3(e,t),[...new Set(t)]}function W3(e,t){e.clauses.forEach(n=>{n.field&&t.push(n.field)}),[...e.trueBranch,...e.falseBranch].forEach(n=>{n.kind==="condition"?W3(n,t):"field"in n&&n.field&&t.push(n.field)})}function z3(e,t=[],n){if(!e)return[{nodeId:"root",kind:"NO_CONDITION",message:"A business rule must include at least one condition.",target:"node"}];let r=[],i=new Map(t.map(o=>[o.logicalName,o]));return K3(e,r,i,!0),n==="Entity"&&H3(e,r),zy(e)||r.push({nodeId:"root",kind:"NO_ACTION",message:"A business rule must include at least one action step.",target:"node"}),r}function H3(e,t){Hve(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(n=>{n.kind==="condition"&&H3(n,t)})}function K3(e,t,n,r=!1){let i=r&&Wve(e),o=!!e.rawConditionExpression;e.clauses.length===0&&!r&&!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?$l(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(ko(a.operator)&&a.valueType==="Value"&&!a.value&&!Gve(a,n))t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_VALUE",message:"Please enter a value for this clause.",target:"clauseValue",itemId:a.id});else if(ko(a.operator)&&a.valueType==="Value"&&a.value){let l=n.get(a.field);l?.maxLength&&a.value.length>l.maxLength&&t.push({nodeId:e.id,kind:"CLAUSE_VALUE_TOO_LONG",message:`Value exceeds the field's maximum length of ${l.maxLength} characters.`,target:"clauseValue",itemId:a.id,messageParams:{maxLength:l.maxLength}})}else ko(a.operator)&&a.valueType==="Expression"&&!a.rawExpression&&!xd(a.expression)?t.push(s==="invalidDayCount"?u_(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"}):ko(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"});ko(a.operator)&&a.valueType==="Value"&&a.value&&F4(n.get(a.field)?.attributeType)&&!ky(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 u=B4(a);ko(a.operator)&&a.valueType==="Value"&&a.value&&Ly(u)&&!V4(a.value,u)&&t.push({nodeId:e.id,kind:"INVALID_CLAUSE_NUMERIC_VALUE",message:jN(u)?"Please enter a whole number for this clause.":"Please enter a valid number for this clause.",target:"clauseValue",itemId:a.id,messageKey:jN(u)?"Validation.InvalidClauseWholeNumberValue":"Validation.InvalidClauseNumericValue"}),ko(a.operator)&&a.valueType==="Lookup"&&(s_(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"})),ko(a.operator)&&a_(e.id,"Condition",a.field,a.valueType,n,t,{operator:a.operator,target:"clauseValue",itemId:a.id})}),i&&e.trueBranch.forEach(a=>{a.kind==="action"&&zve.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")K3(a,t,n);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=n.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(n.size>0){let s=n.get(a.field),u=n.get(a.valueField);s&&u&&!xy(s.attributeType,u.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:$l(a.expression);!a.rawExpression&&!xd(a.expression)&&t.push(s==="invalidDayCount"?u_(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"&&!s_(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&&(a_(a.id,a.type,a.field,a.valueType,n,t,{target:"actionValue"}),L3(a.id,a.type,a.type,a.field,a.valueType,n,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(u=>{if(!u.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:u.id,messageKey:"Validation.RecommendationApplyField"});else if(u.valueType==="Field")u.valueField||t.push({nodeId:a.id,kind:"EMPTY_ACTION_VALUE",message:"Recommendation: please select a field to copy from.",target:"applyActionValue",itemId:u.id,messageKey:"Validation.RecommendationApplySourceField"});else if(u.valueType==="Expression"){let l=u.rawExpression?null:$l(u.expression);!u.rawExpression&&!xd(u.expression)&&t.push(l==="invalidDayCount"?u_(a.id,"applyActionValue",u.id):{nodeId:a.id,kind:"EMPTY_ACTION_VALUE",message:"Recommendation: please complete the formula.",target:"applyActionValue",itemId:u.id,messageKey:"Validation.RecommendationApplyFormula"})}else u.valueType==="Lookup"?s_(u.lookupValue)||t.push({nodeId:a.id,kind:"EMPTY_ACTION_VALUE",message:"Recommendation: please complete the lookup record.",target:"applyActionValue",itemId:u.id,messageKey:"Validation.RecommendationApplyLookupValue"}):u.valueType==="Clear"||u.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:u.id,messageKey:"Validation.RecommendationApplyValue"});u.field&&(a_(a.id,"Recommendation",u.field,u.valueType,n,t,{target:"applyActionValue",itemId:u.id}),L3(a.id,"Recommendation","SetFieldValue",u.field,u.valueType,n,t,{target:"applyActionValue",itemId:u.id}))})}}})}var Vve,x3,zve,Kve,m_=B(()=>{"use strict";VN();xN();Fy();Cm();$3();zN();GN();Vve=new Set(["LockUnlock","ShowErrorMessage","Recommendation","SetFieldValue","SetDefaultValue","SetBusinessRequired","SetVisibility"]);x3=new Set(["Lookup","Customer","Owner"]);zve=new Set(["SetFieldValue","ShowErrorMessage","Recommendation"]);Kve=10});var J3={};Fi(J3,{DAY_COUNT_MAX:()=>Md,DAY_COUNT_MIN:()=>YN,DEFAULT_DESERIALIZE_LABELS:()=>i_,WorkflowJsonMapper:()=>Ud,addElseIfInTree:()=>U3,appendToBranch:()=>F3,areFieldKindsCompatible:()=>xy,attributeTypeToWorkflowType:()=>X4,buildWorkflowEntity:()=>T4,collectUsedFields:()=>j3,createEmptyAction:()=>G3,createEmptyCondition:()=>p_,deserializeWorkflowJson:()=>R3,findNode:()=>c_,findParent:()=>Bd,getDefaultOperatorForFieldType:()=>H4,getExpressionModelIssue:()=>$l,getOperatorsForFieldType:()=>My,hasAnyTriggerGeneratingAction:()=>zy,isDayCountValid:()=>QN,isExpressionModelComplete:()=>xd,isOperatorCompatible:()=>K4,isTriggerGeneratingAction:()=>l_,moveBranchItemInTree:()=>V3,operatorNeedsValue:()=>ko,processTriggerFormIdFromScope:()=>UN,processTriggerScopeFromScope:()=>FN,removeElseIfInTree:()=>B3,removeNodeFromTree:()=>d_,serializeToWorkflowJson:()=>P3,supportsClearForActionType:()=>Dy,updateActionInTree:()=>Wy,updateConditionInTree:()=>wu,validateBusinessRule:()=>z3});var Y3=B(()=>{"use strict";xN();O4();o_();o_();m_();m_();Fy();Cm();Cm();});var Eu=C(Hy=>{"use strict";Object.defineProperty(Hy,"__esModule",{value:!0});Hy.cloneJson=void 0;function Xve(e){return JSON.parse(JSON.stringify(e))}Hy.cloneJson=Xve});var uj=C(Au=>{"use strict";Object.defineProperty(Au,"__esModule",{value:!0});Au.BUSINESS_RULE_NULL_GUID=Au.businessRuleRegistration=Au.BusinessRuleAdapter=void 0;var Q3=ft(),Nm=(Y3(),_i(J3)),X3=mo(),Z3=Y(),Zve=Eu(),ba=Vi(),ewe=Mv(),twe=ft(),nwe=fl(),rwe=new Set(["ShowErrorMessage","Recommendation"]);function rj(e){var t,n;return e?[...(t=e.trueBranch)!==null&&t!==void 0?t:[],...(n=e.falseBranch)!==null&&n!==void 0?n:[]].some(r=>Array.isArray(r.trueBranch)||Array.isArray(r.falseBranch)?rj(r):rwe.has(String(r.type))):!1}function iwe(e){return ij((0,Zve.cloneJson)(e))}function ij(e){var t,n;let r=i=>(i??[]).map(o=>owe(o)?ij(o):o);return{...e,logic:(t=e.logic)!==null&&t!==void 0?t:"AND",clauses:(n=e.clauses)!==null&&n!==void 0?n:[],trueBranch:r(e.trueBranch),falseBranch:r(e.falseBranch)}}function owe(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 awe(e){var t;if(e===null||typeof e!="object"||Array.isArray(e))throw new Z3.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 Z3.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 swe="00000000-0000-0000-0000-000000000000";Au.BUSINESS_RULE_NULL_GUID=swe;var uwe=new Set(["Recommendation","LockUnlock","ShowErrorMessage","SetFieldValue","SetDefaultValue","SetBusinessRequired","SetVisibility"]),lwe=["ruleId","name","description","entityLogicalName","scope","status","rootCondition"],cwe=["kind","id","displayName","logic","clauses","trueBranch","falseBranch"],dwe=["id","field","fieldDisplayName","operator","valueType","value","valueField","lookupValue","expression","rawExpression","valueWorkflowType"];function $o(e,t){return e===void 0?t:{...e,...t}}var xl=["kind","id","type","displayName","field","stepName","stepLabels"],ej=["valueType","valueWorkflowType","value","valueField","lookupValue","expression","rawExpression"],fwe={Recommendation:[...xl,"recommendationTitle","messageText","acceptanceText","applyActions","recommendationActionStepMeta"],LockUnlock:[...xl,"lock"],ShowErrorMessage:[...xl,"errorMessage","messageLevel","messageActionSteps"],SetFieldValue:[...xl,...ej],SetDefaultValue:[...xl,...ej],SetBusinessRequired:[...xl,"required"],SetVisibility:[...xl,"visible"]};function Ne(e,t){return t===void 0?{}:{[e]:t}}function oj(e){var t;return e==null?void 0:{...e,label:(t=e.label)!==null&&t!==void 0?t:""}}function h_(e){return{valueType:e.valueType,...Ne("valueWorkflowType",e.valueWorkflowType),...Ne("value",e.value),...Ne("valueField",e.valueField),...Ne("lookupValue",oj(e.lookupValue)),...Ne("expression",e.expression),...Ne("rawExpression",e.rawExpression)}}function aj(e,t){let n=new Set(t),r={};for(let[i,o]of Object.entries(e))n.has(i)||o!==void 0&&(r[i]=o);return Object.keys(r).length>0?r:void 0}var pwe=["id","field","valueType","valueWorkflowType","value","valueField","lookupValue","expression","rawExpression","stepName","displayName"];function mwe(e){return $o(e.bag,{id:e.id,field:e.field,...h_(e),...Ne("stepName",e.stepName),...Ne("displayName",e.displayName)})}function hwe(e){let t=aj(e,pwe);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 tj(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 nj(e){throw new Error(`Unsupported business-rule action type: ${e.type}`)}var gwe=new Set(["INVALID_CLEAR_FOR_FIELD","INVALID_VALUE_TYPE_FOR_FIELD","CLAUSE_VALUE_TOO_LONG","ACTION_VALUE_TOO_LONG"]),ywe=new Set,bwe="INVALID_CLEAR_FOR_FIELD";function vwe(e){let t=r=>{var i;return(0,ba.isJsonObject)(r)&&(r.label===""||r.label===void 0)?{...r,label:String((i=r.id)!==null&&i!==void 0?i:"")}:r},n=r=>{if(!(0,ba.isJsonObject)(r))return r;let i={...r};"lookupValue"in i&&(i.lookupValue=t(i.lookupValue)),Array.isArray(i.applyActions)&&(i.applyActions=i.applyActions.map(n));for(let o of["clauses","trueBranch","falseBranch"])Array.isArray(i[o])&&(i[o]=i[o].map(n));return i};return n(e)}var Ky=class{toArtifact(t){let n=this.residualBag(t,lwe),r={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 n&&(r.bag=n),r}fromArtifact(t){let n=t.rootCondition?this.conditionFromJson(t.rootCondition):null;return $o(t.bag,{ruleId:t.id,name:t.name,description:t.description,entityLogicalName:t.entityLogicalName,scope:t.scope,status:t.status,rootCondition:n})}fromApiResponse(t){var n;let r=t??{},i={...(n=r.Entity)!==null&&n!==void 0?n:{},wfomJson:r.WfomJson},o=(0,Nm.deserializeWorkflowJson)(i);return this.toArtifact(o)}needsBaseLanguage(t){return rj(t.rootCondition)}toApiPayload(t,n,r){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,Nm.serializeToWorkflowJson)(a,(i=r?.baseLanguageCode)!==null&&i!==void 0?i:nwe.DEFAULT_LCID),u=(o=a.ruleId)!==null&&o!==void 0?o:(0,Q3.newId)();return{Entity:this.buildWorkflowEntity(a,u),WfomJson:s,status:t.status}}createDefault(t){var n,r,i,o,a,s;let u={ruleId:(n=t.id)!==null&&n!==void 0?n:null,name:(r=t.name)!==null&&r!==void 0?r:"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,Nm.createEmptyCondition)():t.rootCondition===null?null:this.conditionFromJson(iwe(awe(t.rootCondition)))},l=this.toArtifact(u);return l.id||(l.id=(0,Q3.newId)()),l}assignMissingIds(t){return(0,twe.assignMissingIds)(t)}validate(t){let n=[],r=t.rootCondition;return r==null?n:(0,ba.isJsonObject)(r)?(sj(r,"/rootCondition",n),n):(n.push((0,ba.issue)("/rootCondition","condition-must-be-object",`rootCondition must be a JSON object or null, got ${typeof r}`)),n)}semanticIssues(t,n=[]){let r;try{r=this.fromArtifact(t)}catch(a){return[(0,ba.issue)("/rootCondition","rule-not-representable",a instanceof Error?a.message:String(a))]}let i=r.rootCondition===null?null:vwe(r.rootCondition),o;return n.length===0?o=gwe:n.some(a=>a.requiredLevel!==void 0)?o=ywe:o=new Set([bwe]),(0,Nm.validateBusinessRule)(i,n).filter(a=>!o.has(a.kind)).map(a=>(0,ba.issue)(`/rootCondition (${a.nodeId})`,`business-rule-${a.kind}`,a.message))}issuesBlockingPush(t,n=[],r){return this.semanticIssues(t,n)}columnsCheckedAtPush(t){let n;try{n=this.fromArtifact(t)}catch{return[]}let r=new Set,i=a=>{a&&r.add(a)},o=a=>{var s;for(let u of a.clauses)i(u.field),i(u.valueField);for(let u of[...a.trueBranch,...a.falseBranch]){if(u.kind==="condition"){o(u);continue}if(i(u.field),u.type==="SetFieldValue"||u.type==="SetDefaultValue")i(u.valueField);else if(u.type==="Recommendation")for(let l of(s=u.applyActions)!==null&&s!==void 0?s:[])i(l.field),i(l.valueField)}};return n.rootCondition&&o(n.rootCondition),[...r]}residualBag(t,n){return aj(t,n)}buildWorkflowEntity(t,n){return(0,Nm.buildWorkflowEntity)(t,n)}conditionToJson(t){let n=this.residualBag(t,cwe),r={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 n&&(r.bag=n),r}clauseToJson(t){let n=this.residualBag(t,dwe),r={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 n&&(r.bag=n),r}branchItemToJson(t){return t.kind==="condition"?this.conditionToJson(t):this.actionToJson(t)}actionToJson(t){let n=this.residualBag(t,fwe[t.type]),r={kind:"action",id:t.id,displayName:t.displayName,field:t.field,...Ne("stepName",t.stepName),...Ne("stepLabels",t.stepLabels),...Ne("bag",n)};switch(t.type){case"Recommendation":return{...r,type:"Recommendation",recommendationTitle:t.recommendationTitle,messageText:t.messageText,...Ne("acceptanceText",t.acceptanceText),applyActions:t.applyActions.map(hwe),...Ne("recommendationActionStepMeta",t.recommendationActionStepMeta)};case"LockUnlock":return{...r,type:"LockUnlock",lock:t.lock};case"ShowErrorMessage":return{...r,type:"ShowErrorMessage",errorMessage:t.errorMessage,...Ne("messageLevel",t.messageLevel),...Ne("messageActionSteps",t.messageActionSteps)};case"SetFieldValue":return{...r,type:"SetFieldValue",...tj(t)};case"SetDefaultValue":return{...r,type:"SetDefaultValue",...tj(t)};case"SetBusinessRequired":return{...r,type:"SetBusinessRequired",required:t.required};case"SetVisibility":return{...r,type:"SetVisibility",visible:t.visible};default:return nj(t)}}conditionFromJson(t){var n;let r=(n=t.bag)!==null&&n!==void 0?n:{};return $o(r,{kind:"condition",isCollapsed:typeof r.isCollapsed=="boolean"?r.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 n;return $o(t.bag,{id:t.id,field:t.field,fieldDisplayName:(n=t.fieldDisplayName)!==null&&n!==void 0?n:t.field,operator:t.operator,valueType:t.valueType,...Ne("value",t.value),...Ne("valueField",t.valueField),...Ne("lookupValue",oj(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(!uwe.has(t.type))throw new Error(`Unsupported business-rule action type: ${t.type}`);Ewe(t);let n={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 $o(t.bag,{...n,type:"Recommendation",recommendationTitle:t.recommendationTitle,messageText:t.messageText,...Ne("acceptanceText",t.acceptanceText),applyActions:t.applyActions.map(mwe),...Ne("recommendationActionStepMeta",t.recommendationActionStepMeta)});case"LockUnlock":return $o(t.bag,{...n,type:"LockUnlock",lock:t.lock});case"ShowErrorMessage":return $o(t.bag,{...n,type:"ShowErrorMessage",errorMessage:t.errorMessage,...Ne("messageLevel",t.messageLevel),...Ne("messageActionSteps",t.messageActionSteps)});case"SetFieldValue":return $o(t.bag,{...n,type:"SetFieldValue",...h_(t)});case"SetDefaultValue":return $o(t.bag,{...n,type:"SetDefaultValue",...h_(t)});case"SetBusinessRequired":return $o(t.bag,{...n,type:"SetBusinessRequired",required:t.required});case"SetVisibility":return $o(t.bag,{...n,type:"SetVisibility",visible:t.visible});default:return nj(t)}}isConditionJson(t){return Object.prototype.hasOwnProperty.call(t,"clauses")&&Object.prototype.hasOwnProperty.call(t,"logic")&&!Object.prototype.hasOwnProperty.call(t,"type")}};Au.BusinessRuleAdapter=Ky;function sj(e,t,n){(0,ba.optionalEnum)(e,"logic",["AND","OR"],t,"condition-logic-invalid",n),(0,ba.childObjects)(e,"clauses",t,"clause",n);for(let r of["trueBranch","falseBranch"])(0,ba.childObjects)(e,r,t,"branchItem",n).forEach(({node:o,index:a})=>{"clauses"in o||"trueBranch"in o||"falseBranch"in o?sj(o,`${t}/${r}/${a}`,n):wwe(o,`${t}/${r}/${a}`,n)})}function wwe(e,t,n){e.type==="SetDefaultValue"&&e.valueType==="Clear"&&n.push((0,ba.issue)(`${t}/valueType`,"clear-only-set-field-value","Clear is only supported for SetFieldValue actions."))}function Ewe(e){if(e.type==="SetDefaultValue"&&e.valueType==="Clear")throw new Error("Clear is only supported for SetFieldValue actions.")}function Awe(){return{adapter:new Ky,api:ewe.businessRuleApi,publish:(e,t,n)=>(0,X3.publishBoundEntity)(e,n),publishScope:(e,t)=>(0,X3.boundEntityPublishScope)(t)}}Au.businessRuleRegistration=Awe});var Nj=C(Cu=>{"use strict";Object.defineProperty(Cu,"__esModule",{value:!0});Cu.appRegistration=Cu.AppAdapter=Cu.HEADER_NAV_BOOLEAN_RULE=void 0;var ys=Vi(),Yn=Us(),Tm=ja(),Om=vc(),g_=Ff(),y_=Ga(),Cwe=ft(),Swe=ae(),bj=fl(),vj=Y(),wj=h0();Object.defineProperty(Cu,"HEADER_NAV_BOOLEAN_RULE",{enumerable:!0,get:function(){return wj.HEADER_NAV_BOOLEAN_RULE}});var Xy="7.0.0.0",lj=`<SiteMap IntroducedVersion="${Xy}"></SiteMap>`,cj="/_imgs/imagestrips/transparent_spacer.gif",dj="/_imgs/TableIconsFluentV9/document_one_page_sparkle.svg",Ej=["Entity","Url","DefaultDashboard","Page","GenPageId"],_m="sitemapId",fj="sitemapName",b_="sitemapNameUnique",pj="aiDescription",mj="[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}",Nwe=new RegExp(`^(?:\\{${mj}\\}|${mj})$`);function hj(e,t){if(!Nwe.test(e.trim()))throw new vj.ValidationError("app",t,[{pointer:"/sitemapId",rule:"app-sitemapid-guid",message:`sitemapId must be a GUID; received '${e}'.`}]);return e.trim()}function gj(e,t,n){if(e===void 0)return n;if(typeof e!="boolean")throw new vj.ValidationError("app",t,[Aj(e)]);return e}function Aj(e){return(0,ys.issue)("/headerAndNavigationRefresh",wj.HEADER_NAV_BOOLEAN_RULE,`headerAndNavigationRefresh must be a boolean, got ${typeof e}`)}function _we(e){let t=r=>{let i=e[r];return typeof i=="string"&&i.trim()!==""?i.trim():void 0},n=r=>{let i=t(r);if(i!==void 0)try{return(0,Swe.normalizeGuid)(i,r)}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 n("dashboardId")&&`DashBoard:${n("dashboardId")}`;case"CustomPage":return t("page")&&`CustomPage:${t("page").toLowerCase()}`;case"GenPage":return n("genPageId")&&`GenPage:${n("genPageId")}`;default:return}}function Iwe(e){var t,n,r,i;let o=[];for(let a of(n=(t=e.siteMap)===null||t===void 0?void 0:t.areas)!==null&&n!==void 0?n:[])for(let s of(r=a.groups)!==null&&r!==void 0?r:[])for(let u of(i=s.subAreas)!==null&&i!==void 0?i:[])u.type==="Entity"&&u.entity&&o.push(u.entity);return o}var Zy=class{constructor(t=bj.DEFAULT_LCID){this.lcid=t}toArtifact(t){let{bag:n,modeledEls:r}=Jy(t,"Area");return{id:"",name:"",uniqueName:"",description:"",siteMap:{areas:r.map(i=>this.areaToJson(i)),bag:n},bag:(0,Yn.emptyBag)()}}fromArtifact(t){(0,y_.installDomShim)();let n=this.assignMissingIds(JSON.parse(JSON.stringify(t))),r=new DOMParser().parseFromString("<root/>","text/xml"),i=this.rootToRaw(n);return(0,Yn.rebuildRaw)(i,(0,Tm.domEngine)(r),null)}fromApiResponse(t){var n,r,i,o,a,s,u,l,c,d,f;(0,y_.installDomShim)();let p=t??{},m=(n=p.$sitemap)!==null&&n!==void 0?n:p,h=(0,Tm.parseXmlRoot)((r=m.sitemapxml)!==null&&r!==void 0?r:lj,lj),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:[[_m,(l=(u=m.sitemapid)!==null&&u!==void 0?u:p._sitemapid_value)!==null&&l!==void 0?l:""],[fj,(c=m.sitemapname)!==null&&c!==void 0?c:""],[b_,(d=m.sitemapnameunique)!==null&&d!==void 0?d:""],[pj,(f=p.aiappdescription)!==null&&f!==void 0?f:""]],c:[]},g}toApiPayload(t,n){var r,i,o,a,s,u,l,c,d,f,p,m,h,g,y,b;(0,y_.installDomShim)();let E=(0,Tm.serializeNode)(this.fromArtifact(t)),w=[],_=[];for(let T of(i=(r=t.siteMap)===null||r===void 0?void 0:r.areas)!==null&&i!==void 0?i:[])for(let O of(o=T.groups)!==null&&o!==void 0?o:[])for(let v of(a=O.subAreas)!==null&&a!==void 0?a:[])v.type==="Entity"&&v.entity?w.push(v.entity):v.type==="DashBoard"&&v.dashboardId&&_.push(v.dashboardId);let I=(s=t.bag)!==null&&s!==void 0?s:(0,Yn.emptyBag)();return{sitemapId:Im(I,_m)||(t.sitemapId?hj(t.sitemapId,t.id):""),sitemapxml:E,sitemapname:Im(I,fj)||t.name,...Im(I,b_)?{sitemapNameUnique:Im(I,b_)}:{},appModuleId:t.id,appModuleName:t.name,appModuleDescription:t.description,...t.aiDescription!==void 0&&t.aiDescription!==(n?n.aiDescription:Im(I,pj))?{appModuleAiDescription:t.aiDescription}:{},appModuleUniqueName:t.uniqueName,...t.iconWebResourceId?{iconWebResourceId:t.iconWebResourceId}:{},...t.headerAndNavigationRefresh===void 0?{}:{appSettings:{[g_.HEADER_AND_NAVIGATION_REFRESH]:gj(t.headerAndNavigationRefresh,(u=t.id)!==null&&u!==void 0?u:"(unknown)",!0)?g_.APP_SETTING_ON:g_.APP_SETTING_OFF}},...typeof t.published=="boolean"?{published:t.published}:{},entities:w,components:{forms:(c=(l=t.components)===null||l===void 0?void 0:l.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:[],..._],...((y=t.components)===null||y===void 0?void 0:y.mainFormsByTable)!==void 0?{mainFormsByTable:t.components.mainFormsByTable}:{},...((b=t.components)===null||b===void 0?void 0:b.mainFormsOnUpdate)!==void 0?{mainFormsOnUpdate:t.components.mainFormsOnUpdate}:{}}}}createDefault(t){var n,r,i,o,a,s;let u=!((n=t.siteMap)===null||n===void 0)&&n.areas&&t.siteMap.areas.length>0?t.siteMap.areas:[{id:"",title:"Area",groups:[{id:"",title:"Group",subAreas:[]}]}],l=(r=t.id)!==null&&r!==void 0?r:(0,Cwe.newId)();return{id:l,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:u},...t.sitemapId?{sitemapId:hj(t.sitemapId,l)}:{},...t.iconWebResourceId?{iconWebResourceId:t.iconWebResourceId}:{},headerAndNavigationRefresh:gj(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 n=t;if(!n||typeof n!="object")return t;let r=n.siteMap;return r&&Array.isArray(r.areas)?r.areas.forEach(E_):Array.isArray(n.areas)?n.areas.forEach(E_):Array.isArray(n.groups)?E_(n):Array.isArray(n.subAreas)?Sj(n):"type"in n&&eb(n,"subarea"),t}validate(t){let n=[],r=t.published;r!==void 0&&typeof r!="boolean"&&n.push((0,ys.issue)("/published","published-must-be-boolean",`published must be a boolean, got ${typeof r}`));let i=t.siteMap,o=t.headerAndNavigationRefresh;if(o!==void 0&&typeof o!="boolean"&&n.push(Aj(o)),i==null)return n;if(!(0,ys.isJsonObject)(i))return n.push((0,ys.issue)("/siteMap","sitemap-must-be-object",`siteMap must be a JSON object, got ${typeof i}`)),n;let a=(0,ys.childObjects)(i,"areas","/siteMap","area",n),s=new Map;return a.forEach(({node:u,index:l})=>{let c=`/siteMap/areas/${l}`;(0,ys.childObjects)(u,"groups",c,"group",n).forEach(({node:f,index:p})=>{let m=`${c}/groups/${p}`;(0,ys.childObjects)(f,"subAreas",m,"subArea",n).forEach(({node:g,index:y})=>{let b=`${m}/subAreas/${y}`;(0,ys.optionalEnum)(g,"type",["Entity","URL","DashBoard","CustomPage","GenPage"],b,"subarea-type-invalid",n);let E=_we(g);if(!E)return;let w=s.get(E);if(w===void 0){s.set(E,b);return}n.push((0,ys.issue)(b,"subarea-duplicate-target",`the sitemap already navigates to this target at ${w}; a duplicate SubArea would pin it twice and a single removeElement would leave one behind`))})})}),n}issuesBlockingPush(t){var n,r,i;return[...(0,Om.mainFormSetShapeIssues)((n=t.components)===null||n===void 0?void 0:n.mainFormsByTable,Iwe(t)),...(0,Om.mainFormModeIssues)((r=t.components)===null||r===void 0?void 0:r.mainFormsOnUpdate,(i=t.components)===null||i===void 0?void 0:i.mainFormsByTable)]}applyServerIdentity(t,n){let r=n[_m];if(!r)return;t.bag||(t.bag=(0,Yn.emptyBag)());let i=t.bag.a.find(o=>o[0]===_m);i?i[1]=r:t.bag.a.push([_m,r])}areaToJson(t){var n;let{bag:r,modeledEls:i}=Jy(t,"Group"),o={id:(n=t.getAttribute("Id"))!==null&&n!==void 0?n:"",title:v_(t,this.lcid),groups:i.map(u=>this.groupToJson(u)),bag:r},a=t.getAttribute("Icon");a&&(o.icon=a);let s=t.getAttribute("VectorIcon");return s&&(o.vectorIcon=s),o}groupToJson(t){var n;let{bag:r,modeledEls:i}=Jy(t,"SubArea");return{id:(n=t.getAttribute("Id"))!==null&&n!==void 0?n:"",title:v_(t,this.lcid),subAreas:i.map(o=>this.subAreaToJson(o)),bag:r}}subAreaToJson(t){var n;let{bag:r}=Jy(t,null),i=Twe(t),o={id:(n=t.getAttribute("Id"))!==null&&n!==void 0?n:"",type:i,title:v_(t,this.lcid),bag:r};if(i==="Entity"){let u=t.getAttribute("Entity");u&&(o.entity=u)}else if(i==="DashBoard"){let u=t.getAttribute("DefaultDashboard");u&&(o.dashboardId=u);let l=t.getAttribute("Url");l&&(o.dashboardUrl=l)}else if(i==="CustomPage"){let u=t.getAttribute("Page");u&&(o.page=u)}else if(i==="GenPage"){let u=t.getAttribute("GenPageId");u&&(o.genPageId=u)}else{let u=t.getAttribute("Url");u&&(o.url=u)}let a=t.getAttribute("Icon");a&&a!==cj&&(o.icon=a);let s=t.getAttribute("VectorIcon");return s&&(o.vectorIcon=s),o}rootToRaw(t){var n,r,i,o;let a=(r=(n=t.siteMap)===null||n===void 0?void 0:n.bag)!==null&&r!==void 0?r:(0,Yn.emptyBag)(),u=Yy(a)?[["IntroducedVersion",Xy]]:[],l=((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,Yn.mergeAttrs)(a.a,u),c:(0,Yn.spliceChildren)(a.c,l)}}areaToRaw(t){var n,r;let i=(n=t.bag)!==null&&n!==void 0?n:(0,Yn.emptyBag)(),o=Yy(i),a=[],s=[];t.id&&a.push(["Id",t.id]),o&&a.push(["ShowGroups","true"],["ResourceId","SitemapDesigner.NewTitle"],["DescriptionResourceId","SitemapDesigner.NewTitle"],["IntroducedVersion",Xy]),t.icon!==void 0?a.push(["Icon",t.icon]):Qy(i.a,"Icon")&&s.push("Icon"),t.vectorIcon!==void 0?a.push(["VectorIcon",t.vectorIcon]):Qy(i.a,"VectorIcon")&&s.push("VectorIcon");let u=((r=t.groups)!==null&&r!==void 0?r:[]).map(c=>this.groupToRaw(c)),l=w_((0,Yn.spliceChildren)(i.c,u),t.title,o,this.lcid);return{n:"Area",a:(0,Yn.mergeAttrs)(i.a,a,s),c:l}}groupToRaw(t){var n,r;let i=(n=t.bag)!==null&&n!==void 0?n:(0,Yn.emptyBag)(),o=Yy(i),a=[];t.id&&a.push(["Id",t.id]),o&&a.push(["ResourceId","SitemapDesigner.NewGroup"],["DescriptionResourceId","SitemapDesigner.NewGroup"],["ToolTipResourseId","SitemapDesigner.Unknown"],["IntroducedVersion",Xy],["IsProfile","false"]);let s=((r=t.subAreas)!==null&&r!==void 0?r:[]).map(l=>this.subAreaToRaw(l)),u=w_((0,Yn.spliceChildren)(i.c,s),t.title,o,this.lcid);return{n:"Group",a:(0,Yn.mergeAttrs)(i.a,a),c:u}}subAreaToRaw(t){var n;let r=(n=t.bag)!==null&&n!==void 0?n:(0,Yn.emptyBag)(),i=Yy(r),o=Dwe(r.a,t.type),a=[],s=[];t.id&&a.push(["Id",t.id]);let u=!i&&!r.a.some(([c])=>Ej.includes(c));Rwe(a,t,u),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]):Qy(o,"Icon",cj)&&s.push("Icon"),t.vectorIcon!==void 0?a.push(["VectorIcon",t.vectorIcon]):Qy(o,"VectorIcon")?t.type==="GenPage"?a.push(["VectorIcon",dj]):s.push("VectorIcon"):t.type==="GenPage"&&!Owe(o,"VectorIcon")&&a.push(["VectorIcon",dj]);let l=w_((0,Yn.spliceChildren)(r.c,[]),t.title,i,this.lcid);return{n:"SubArea",a:(0,Yn.mergeAttrs)(o,a,s),c:l}}};Cu.AppAdapter=Zy;function Jy(e,t){let n=(0,Tm.nodeLikeFromDom)(e).getAllProperties().map(s=>[s.key,s.value]),r=[],i=[],o=e.childNodes,a=0;for(let s=0;s<o.length;s+=1){let u=o[s];u.nodeType!==1&&u.nodeType!==3||(u.nodeType===1&&t!==null&&u.tagName===t?i.push(u):r.push({i:a,node:(0,Yn.rawFromNode)((0,Tm.nodeLikeFromDom)(u))}),a+=1)}return{bag:{a:n,c:r},modeledEls:i}}function yj(e,t){let n=[],r=e.childNodes;for(let i=0;i<r.length;i+=1){let o=r[i];o.nodeType===1&&o.tagName===t&&n.push(o)}return n}function v_(e,t){var n;let r=yj(e,"Titles")[0];if(!r)return"";let o=yj(r,"Title").find(a=>a.getAttribute("LCID")===String(t));return o&&(n=o.getAttribute("Title"))!==null&&n!==void 0?n:""}function Twe(e){return e.getAttribute("GenPageId")?"GenPage":e.getAttribute("Entity")?"Entity":e.getAttribute("Page")?"CustomPage":e.getAttribute("DefaultDashboard")?"DashBoard":"URL"}function Yy(e){return e.a.length===0&&e.c.length===0}function Owe(e,t){return e.some(([n])=>n===t)}function Qy(e,t,n){let r=e.find(([o])=>o===t),i=r?.[1];return!!i&&i!==n}function Im(e,t){let n=e.a.find(([r])=>r===t);return n?n[1]:void 0}function Dwe(e,t){let n=Pwe(t);return e.filter(([r])=>!Ej.includes(r)||n.has(r)).map(r=>[r[0],r[1]])}function Pwe(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 Rwe(e,t,n){var r,i,o,a,s;switch(t.type){case"Entity":e.push(["Entity",(r=t.entity)!==null&&r!==void 0?r:""]);break;case"URL":(t.url!==void 0||!n)&&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 w_(e,t,n,r){if(!t)return e;let i=e.findIndex(o=>o.n==="Titles");if(i>=0){let o=e.slice();return o[i]=kwe(e[i],t,r),o}return n?[$we(t,r),...e]:e}function kwe(e,t,n){let r=!1,i=e.c.map(o=>!r&&o.n==="Title"&&Lwe(o,"LCID")===String(n)?(r=!0,{n:o.n,a:(0,Yn.mergeAttrs)(o.a,[["Title",t]]),c:o.c}):o);return r||i.unshift(Cj(t,n)),{n:e.n,a:e.a.map(o=>[o[0],o[1]]),c:i}}function $we(e,t){return{n:"Titles",a:[],c:[Cj(e,t)]}}function Cj(e,t){return{n:"Title",a:[["LCID",String(t)],["Title",e]],c:[]}}function Lwe(e,t){let n=e.a.find(([r])=>r===t);return n?n[1]:void 0}function Mwe(e){let t="0123456789abcdef",n="";for(let r=0;r<e;r+=1)n+=t[Math.floor(Math.random()*t.length)];return n}function eb(e,t){e&&(typeof e.id!="string"||e.id.length===0)&&(e.id=`${t}_${Mwe(8)}`)}function E_(e){var t;eb(e,"area");for(let n of(t=e.groups)!==null&&t!==void 0?t:[])Sj(n)}function Sj(e){var t;eb(e,"group");for(let n of(t=e.subAreas)!==null&&t!==void 0?t:[])eb(n,"subarea")}function xwe(e=bj.DEFAULT_LCID){return{adapter:new Zy(e),api:Om.appApi,languageSensitive:!0,publish:(t,n)=>(0,Om.publishApp)(t,n),assertCombinablePublish:(t,n)=>(0,Om.assertAppPublicationCombinable)(t,n),publishScope:t=>({envelope:"appmodule",targetIds:[t]}),publishesOnPush:(t,n)=>{let r=t?.published;return n?r!==!1:r===!0},rebaselineAfterPublish:"bracket"}}Cu.appRegistration=xwe});var _j={};Fi(_j,{ActionType:()=>C_,AppActionOrigin:()=>P_,AppActionVisibilityType:()=>D_,ButtonType:()=>N_,CannotUpdateAppActionColumns:()=>Fwe,Context:()=>I_,IconType:()=>S_,Location:()=>__,OnClickEventType:()=>O_,Scope:()=>T_,VisibilityType:()=>A_});var A_,C_,S_,N_,__,I_,T_,O_,D_,P_,Fwe,Ij=B(()=>{"use strict";(function(e){e[e.NotSupported=0]="NotSupported",e[e.Show=1]="Show",e[e.ClassicRules=2]="ClassicRules",e[e.Expression=3]="Expression"})(A_||(A_={}));(function(e){e[e.NotSupported=0]="NotSupported",e[e.None=1]="None",e[e.JavaScript=2]="JavaScript",e[e.Expression=3]="Expression"})(C_||(C_={}));(function(e){e[e.NoIcon=0]="NoIcon",e[e.UseIcon=1]="UseIcon",e[e.UseWebResource=2]="UseWebResource"})(S_||(S_={}));(function(e){e[e.Standard=0]="Standard",e[e.Dropdown=1]="Dropdown",e[e.Split=2]="Split",e[e.Group=3]="Group"})(N_||(N_={}));(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"})(__||(__={}));(function(e){e[e.All=0]="All",e[e.Entity=1]="Entity"})(I_||(I_={}));(function(e){e[e.App=0]="App",e[e.Entity=1]="Entity",e[e.Global=2]="Global"})(T_||(T_={}));(function(e){e[e.None=0]="None",e[e.Formula=1]="Formula",e[e.JavaScript=2]="JavaScript"})(O_||(O_={}));(function(e){e[e.None=0]="None",e[e.Formula=1]="Formula",e[e.ClassicRules=2]="ClassicRules"})(D_||(D_={}));(function(e){e[e.Default=0]="Default",e[e.Migrated=1]="Migrated",e[e.MigratedClone=2]="MigratedClone"})(P_||(P_={}));Fwe=["appactionid","appmoduleid","context","contextvalue","location","name","type","uniquename","isdisabled","origin"]});var Hj=C(jd=>{"use strict";Object.defineProperty(jd,"__esModule",{value:!0});jd.commandRegistration=jd.CommandAdapter=void 0;var fn=(Ij(),_i(_j)),Tj=mo(),Ln=Vi(),Vd=Xv(),Uwe=aw(),F_=LA(),$j=ft(),Fl=ae(),Gd=Y(),k_="$ClientSvg:",$_=".svg",qwe=2,Bwe=1,Vwe=1,Lj="entityMetadataId",Gwe=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"]),Pm=class{toArtifact(t){var n,r,i,o,a,s,u;let l=(n=t.appActions)!==null&&n!==void 0?n:[],c=(r=t.entityLogicalName)!==null&&r!==void 0?r:"",d=l.find(h=>typeof h.appactionid!="string"||h.appactionid==="");if(d)throw new Gd.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 l){let g=typeof h._parentappactionid_value=="string"&&h._parentappactionid_value?h._parentappactionid_value:"",y=(o=f.get(g))!==null&&o!==void 0?o:[];y.push(h),f.set(g,y)}let p=new Map;for(let h of(a=f.get(""))!==null&&a!==void 0?a:[]){let g=x_(h.location),y=(s=p.get(g))!==null&&s!==void 0?s:[];y.push(h),p.set(g,y)}let m=[];for(let[h,g]of p)m.push({location:h,groups:Wwe(g,f,q_(h),c)});return{id:c,entityLogicalName:c,commandBars:zwe(m),bag:{a:[[Lj,(u=t.entityMetadataId)!==null&&u!==void 0?u:""]]}}}fromArtifact(t){return{entityLogicalName:t.entityLogicalName,entityMetadataId:M_(t),appActions:nb(t).map(n=>n.row)}}fromApiResponse(t){return this.toArtifact(t??{})}toApiPayload(t,n){let r=new Set(n?nb(n).map(f=>f.appactionid):[]),i=nb(t,new Set([...r].map(f=>f.toLowerCase()))),o=new Set(i.map(f=>f.appactionid)),a=i.map(f=>{let p=f.exists||r.has(f.appactionid);return{appactionid:f.appactionid,exists:p,etag:f.etag,body:p?rEe(f.row):zj(f.row),...f.inheritsParentLocation===!0&&!p?{inheritsParentLocation:!0}:{}}}),s=[...r].filter(f=>!o.has(f));(0,Vd.assertOneWritePerRow)(t.entityLogicalName,{rows:a,deletedRowIds:s});let{sentDisabled:u,disabledAfter:l}=tEe(t,n,r),c=new Map([...u].map(([f,p])=>[va(f),p]));for(let f of a){let p=f.exists?c.get(va(f.appactionid)):void 0;p!==void 0&&(f.body.isdisabled=p)}let d=nEe(t,n,r);return{entityLogicalName:t.entityLogicalName,entityMetadataId:M_(t),rows:a,...s.length>0?{deletedRowIds:s}:{},...Object.keys(d).length>0?{keptDisabled:d}:{},...l.size>0?{disabledAfter:Object.fromEntries(l)}:{},...u.size>0?{sentDisabled:Object.fromEntries(u)}:{}}}committed(t,n){let{keptDisabled:r,disabledAfter:i}=n??{},o=new Map(Object.entries(r??{}).map(([l,c])=>[va(l),c])),a=new Map(Object.entries(i??{}).map(([l,c])=>[va(l),c]));if(o.size===0&&a.size===0)return{artifact:t,baseline:t};let u=Dj(t,l=>{let c=!wa(l.bag)&&l.disabled===void 0?o.get(va(l.id)):void 0,d=wa(l.bag)?a.get(va(Rm(l))):void 0,f=d!==void 0?Oj(l.bag,d):void 0;return c===void 0&&f===void 0?l:{...l,...c!==void 0?{disabled:c}:{},...f?{bag:f}:{}}});return{artifact:u,baseline:u}}partiallyCommitted(t,n,r){var i;let o=(i=n?.sentDisabled)!==null&&i!==void 0?i:{},a=new Set(r.map(va)),s=Object.keys(o).filter(l=>a.has(va(l)));return s.length===0?t:Dj(t,l=>{let c=va(Rm(l)),d=s.find(f=>va(f)===c);return d===void 0?l:wa(l.bag)?{...l,bag:Oj(l.bag,o[d])}:{...l,disabled:o[d]}})}createDefault(t){var n,r,i,o;let a=(r=(n=t.entityLogicalName)!==null&&n!==void 0?n:t.id)!==null&&r!==void 0?r:"";return{id:(i=t.id)!==null&&i!==void 0?i:a,entityLogicalName:a,commandBars:(o=t.commandBars)!==null&&o!==void 0?o:[]}}assignMissingIds(t){return(0,$j.assignMissingIds)(t)}normalize(t){let n=Hwe(t),r=!1,i=(Array.isArray(t.commandBars)?t.commandBars:[]).map(o=>{let a=(0,Ln.isJsonObject)(o)&&Array.isArray(o.groups)?o.groups:void 0;if(!a)return o;let s=!1,u=a.map(l=>{let c=(0,Ln.isJsonObject)(l)&&Array.isArray(l.controls)?l.controls:void 0;if(!c)return l;let d=c.map(f=>Bj(f,n));return d.every((f,p)=>f===c[p])?l:(s=!0,{...l,controls:d})});return s?(r=!0,{...o,groups:u}):o});return r?{...t,commandBars:i}:t}validate(t){let n=[];return(0,Ln.childObjects)(t,"commandBars","","commandBar",n).forEach(({node:i,index:o})=>{let a=`/commandBars/${o}`;(0,Ln.optionalEnum)(i,"location",["MainTab","ContextualTab","HomeTab"],a,"bar-location-invalid",n),(0,Ln.childObjects)(i,"groups",a,"group",n).forEach(({node:u,index:l})=>{let c=`${a}/groups/${l}`;wa(u.bag)||((0,Ln.optionalGuidId)(u,"id",c,"group-id-invalid",n),typeof u.title=="string"&&u.title.length>0&&n.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."})),Mj((0,Ln.childObjects)(u,"controls",c,"control",n),`${c}/controls`,n)})}),n}};jd.CommandAdapter=Pm;function wa(e){let t=e?.a;return Array.isArray(t)&&t.length>0}function va(e){try{return(0,Fl.normalizeGuid)(e,"row id")}catch{return e.toLowerCase()}}function Oj(e,t){return{...e,a:[...e.a.filter(([n])=>n!=="isdisabled"),["isdisabled",t]]}}function Dj(e,t){var n;let r=i=>{let o=Array.isArray(i.children)?i.children.map(r):void 0,a=o!==void 0&&o.some((u,l)=>{var c;return u!==((c=i.children)===null||c===void 0?void 0:c[l])}),s=t(i);return a?{...s,children:o}:s};return{...e,commandBars:((n=e.commandBars)!==null&&n!==void 0?n:[]).map(i=>({...i,groups:Array.isArray(i.groups)?i.groups.map(o=>({...o,controls:Array.isArray(o.controls)?o.controls.map(r):o.controls})):i.groups}))}}function Mj(e,t,n){e.forEach(({node:r,index:i})=>{let o=`${t}/${i}`;wa(r.bag)||(0,Ln.optionalGuidId)(r,"id",o,"control-id-invalid",n),(0,Ln.optionalEnum)(r,"type",["Button","FlyoutAnchor","SplitButton"],o,"control-type-invalid",n);let a=r.location;a!==void 0&&(typeof a!="number"||!Number.isInteger(a)||a<0||a>6)&&n.push((0,Ln.issue)(`${o}/location`,"control-location-invalid",`location must be an integer 0-6 when present, got ${JSON.stringify(a)}`)),r.action!==void 0&&r.action!==null&&((0,Ln.isJsonObject)(r.action)?(0,Ln.optionalEnum)(r.action,"type",["javascript"],`${o}/action`,"action-type-invalid",n):n.push((0,Ln.issue)(`${o}/action`,"control-action-must-be-object",`a control action must be a JSON object when present, got ${typeof r.action}`)));let s=(0,Ln.childObjects)(r,"children",o,"control",n);s.length>0&&Mj(s,`${o}/children`,n)})}function L_(e){return{a:Object.entries(e)}}function jwe(e){return Object.fromEntries(e.a)}function Lo(e,t){if(e){for(let[n,r]of e.a)if(n===t)return r}}function M_(e){let t=Lo(e.bag,Lj);return typeof t=="string"?t:""}function Wwe(e,t,n,r){var i,o;let a=[],s=[];for(let u of ob(e))u.type===fn.ButtonType.Group?a.push({id:U_(u.name,r),title:typeof u.grouptitle=="string"?u.grouptitle:"",controls:ob((o=t.get((i=u.appactionid)!==null&&i!==void 0?i:""))!==null&&o!==void 0?o:[]).map(l=>ib(l,t,n,r)),bag:L_(u)}):s.push(ib(u,t,n,r));return s.length>0&&a.unshift({id:eEe(r,n),title:"",controls:s}),a}function Rm(e){let t=e.bag?Lo(e.bag,"appactionid"):void 0;return typeof t=="string"&&t.trim()!==""?t:e.id}function ib(e,t,n,r){var i,o,a,s,u;let l=U_(e.name,r),c={id:l,type:Dm(e.type),label:typeof e.buttonlabeltext=="string"?e.buttonlabeltext:"",command:typeof e.appactionid=="string"?e.appactionid:l,bag:L_(e)},d=xj(e);d&&(c.icon=d);let f=Fj(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!==n&&(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 ob(p))if(g.type===fn.ButtonType.Group){let y=(o=g.appactionid)!==null&&o!==void 0?o:"",b=L_(g);c.flyoutGroupId===void 0&&(c.flyoutGroupId=(a=g.appactionid)!==null&&a!==void 0?a:void 0,c.flyoutGroupBag=b);let E=[];for(let w of ob((u=t.get((s=g.appactionid)!==null&&s!==void 0?s:""))!==null&&u!==void 0?u:[])){let _=ib(w,t,n,r);m.push(_),E.push(Rm(_))}h.push({id:y,bag:b,childIds:E})}else m.push(ib(g,t,n,r));c.children=m,h.length>1&&(c.flyoutGroups=h)}return c}function xj(e){var t;if(!((t=e.IconWebResourceId)===null||t===void 0)&&t.name)return e.IconWebResourceId.name;if(e.fonticon)return e.fonticon.startsWith(k_)?e.fonticon.slice(k_.length)+$_:e.fonticon}function Fj(e){var t;let n=e.onclickeventjavascriptfunctionname;if(typeof n!="string"||!n)return;let r=e.OnClickEventJavaScriptWebResourceId,i=e._onclickeventjavascriptwebresourceid_value,o={type:"javascript",webResourceId:(t=typeof i=="string"?i:r?.webresourceid)!==null&&t!==void 0?t:"",functionName:n};r?.name&&(o.libraryName=r.name);let a=e.onclickeventjavascriptparameters;return typeof a=="string"&&a&&(o.parameters=a),o}function Pj(e){return typeof e.sequence=="number"?e.sequence:typeof e.buttonsequencepriority=="number"?e.buttonsequencepriority:0}function ob(e){return[...e].sort((t,n)=>Pj(t)-Pj(n))}function zwe(e){let t={MainTab:0,ContextualTab:1,HomeTab:2};return[...e].sort((n,r)=>{var i,o;return((i=t[n.location])!==null&&i!==void 0?i:9)-((o=t[r.location])!==null&&o!==void 0?o:9)})}function U_(e,t){if(!e)return"";if(e.indexOf("{!EntityLogicalName}")>=0)return e.replace("{!EntityLogicalName}",t);let n=e.split("!");return n.length===2?n[1]:e}function x_(e){switch(e){case fn.Location.Form:case fn.Location.QuickForm:return"MainTab";case fn.Location.HomePageGrid:case fn.Location.Dashboard:return"HomeTab";default:return"ContextualTab"}}function q_(e){switch(e){case"MainTab":return fn.Location.Form;case"HomeTab":return fn.Location.HomePageGrid;default:return fn.Location.SubGridStandard}}function Dm(e){switch(e){case fn.ButtonType.Dropdown:return"FlyoutAnchor";case fn.ButtonType.Split:return"SplitButton";default:return"Button"}}function B_(e){switch(e){case"FlyoutAnchor":return fn.ButtonType.Dropdown;case"SplitButton":return fn.ButtonType.Split;default:return fn.ButtonType.Standard}}function Uj(e){var t;return e.bag&&e.bag.a.length>0?!0:((t=e.title)!==null&&t!==void 0?t:"").length>0}function qj(e,t){var n,r,i;return((r=(n=e.bag)===null||n===void 0?void 0:n.a.length)!==null&&r!==void 0?r:0)>0?!0:t.has(((i=e.id)!==null&&i!==void 0?i:"").toLowerCase())}function nb(e,t=new Set){var n,r,i,o;let a=[],s=M_(e);for(let u of(n=e.commandBars)!==null&&n!==void 0?n:[]){let l=q_(u.location),c=((r=u.groups)!==null&&r!==void 0?r:[]).flatMap(p=>{var m;return(m=p.controls)!==null&&m!==void 0?m:[]}),d=c.length>0&&c.every(p=>!qj(p,t)),f=0;for(let p of(i=u.groups)!==null&&i!==void 0?i:[]){let m,h=l;if(Uj(p)){let g=Jwe(p,l,void 0,e,s);a.push(g),m=g.appactionid,h=rb(g,p.bag,t,l)}for(let g of(o=p.controls)!==null&&o!==void 0?o:[])Vj(g,l,h,m,e,s,a,d?f:void 0,t),f+=1}}return a}function Bj(e,t){if(!(0,Ln.isJsonObject)(e))return e;let n=e.children,r=n,i=!1;Array.isArray(n)&&(r=n.map(s=>Bj(s,t)),i=r.some((s,u)=>s!==n[u]));let o=!wa(e.bag)&&(typeof e.id!="string"||e.id.trim()==="");if(!o&&!i)return e;let a;if(o){do a=(0,$j.newId)();while(t.has(a));t.add(a)}return{...e,...a!==void 0?{id:a}:{},...i?{children:r}:{}}}function Hwe(e){let t=new Set,n=(o,...a)=>{if((0,Ln.isJsonObject)(o))for(let s of[...a.map(u=>o[u]),wa(o.bag)?Lo(o.bag,"appactionid"):void 0])typeof s=="string"&&s.trim()!==""&&t.add(s.toLowerCase())},r=o=>{(0,Ln.isJsonObject)(o)&&(n(o,"id","flyoutGroupId"),n({bag:o.flyoutGroupBag}),(Array.isArray(o.flyoutGroups)?o.flyoutGroups:[]).forEach(a=>n(a,"id")),(Array.isArray(o.children)?o.children:[]).forEach(r))},i=e.commandBars;return(Array.isArray(i)?i:[]).forEach(o=>{let a=(0,Ln.isJsonObject)(o)?o.groups:void 0;(Array.isArray(a)?a:[]).forEach(s=>{n(s,"id");let u=(0,Ln.isJsonObject)(s)?s.controls:void 0;(Array.isArray(u)?u:[]).forEach(r)})}),t}function Vj(e,t,n,r,i,o,a,s,u=new Set){var l,c;let d=Kwe(e,n==="read"?t:n,r,i,o,s);n==="read"&&e.location===void 0&&Gj(d,u)&&(d.inheritsParentLocation=!0),a.push(d);let f=rb(d,e.bag,u,(l=e.location)!==null&&l!==void 0?l:n),p=(c=e.children)!==null&&c!==void 0?c:[];if(p.length===0&&!(e.flyoutGroups&&e.flyoutGroups.length>0))return;let m=p.every(w=>!qj(w,u)),h=(w,_,I,T)=>{Vj(w,t,I,_,i,o,a,m?T:void 0,u)},g=e.flyoutGroups;if(g&&g.length>0){let w=new Map(p.map(N=>[Rm(N),N])),_=new Set,I=0,T,O=f;for(let[N,S]of g.entries()){let R=S.id||(N===0?R_(d.appactionid):(0,F_.deterministicId)("flyout-group",`${d.appactionid}#${N}`)),x=Rj(R,f,t,d.appactionid,i,o,S.bag,u);a.push(x);let G=rb(x,S.bag,u,f),U=x.appactionid;T===void 0&&(T=U,O=G);for(let M of S.childIds){let q=w.get(M);!q||_.has(M)||(_.add(M),h(q,U,G,I),I+=1)}}let v=T??R_(d.appactionid);for(let N of p){let S=Rm(N);_.has(S)||(_.add(S),h(N,v,O,I),I+=1)}return}let y=e.flyoutGroupId||R_(d.appactionid),b=Rj(y,f,t,d.appactionid,i,o,e.flyoutGroupBag,u);a.push(b);let E=rb(b,e.flyoutGroupBag,u,f);for(let[w,_]of p.entries())h(_,y,E,w)}function Gj(e,t){return!e.exists&&!t.has(e.appactionid.toLowerCase())}function rb(e,t,n,r){if(e.exists){let i=Lo(t,"location");return(0,Vd.isStorableLocation)(i)?i:"read"}return n.has(e.appactionid.toLowerCase())?"read":r}function Kwe(e,t,n,r,i,o){let a=V_(e,t,n,r,i),s=a.row;o!==void 0&&typeof s.sequence!="number"&&(s.sequence=o);let u=xj(s);return e.location!==void 0&&(s.location=e.location),s.type=B_(e.type),s.buttonlabeltext=e.label,Qwe(s,e.icon,u),Zwe(s,e.action),Xwe(s),e.hidden!==void 0&&(s.hidden=e.hidden),e.disabled!==void 0&&(s.isdisabled=e.disabled),{...a,row:s}}function Jwe(e,t,n,r,i){let o=V_(e,t,n,r,i);return o.row.type=fn.ButtonType.Group,o.row.grouptitle=e.title,o}function Rj(e,t,n,r,i,o,a,s){let u=V_({id:e,bag:a},t==="read"?n:t,r,i,o);t==="read"&&Gj(u,s)&&(u.inheritsParentLocation=!0);let l=u.row;return l["[email protected]"]=`/appactions(${(0,Fl.normalizeGuid)(r,"Command flyout group id")})`,l.type=fn.ButtonType.Group,l.grouptitle===void 0&&(l.grouptitle=""),l.isgrouptitlehidden===void 0&&(l.isgrouptitlehidden=!0),u}function V_(e,t,n,r,i){let o,a,s,u;if(e.bag&&e.bag.a.length>0){o=jwe(e.bag),a=!0;let l=Lo(e.bag,"@odata.etag");s=typeof l=="string"?l:null;let c=Lo(e.bag,"appactionid");u=typeof c=="string"&&c?c:e.id}else{if(typeof e.id!="string"||e.id.trim()==="")throw new Gd.InvalidArgumentError(`Cannot serialize command '${r.entityLogicalName}': a new control has no id. Its primary key is minted once, before the first push, by normalize() \u2014 serialize the normalized artifact.`);u=e.id,o=Ywe(u,t,r,i),a=!1,s=null}return n?o["[email protected]"]=`/appactions(${(0,Fl.normalizeGuid)(n,"Command parent appaction id")})`:a&&typeof o._parentappactionid_value=="string"&&o._parentappactionid_value&&o.type!==fn.ButtonType.Group&&(o["[email protected]"]=null),delete o._parentappactionid_value,{appactionid:u,exists:a,etag:s,row:o}}function Ywe(e,t,n,r){let i={appactionid:e,name:`${e}!${e.replace(/-/g,"").slice(0,32)}`,uniquename:"",location:t,context:fn.Context.Entity,contextvalue:n.entityLogicalName,scope:fn.Scope.Entity};return r&&(i["[email protected]"]=`/entities(${(0,Fl.normalizeGuid)(r,"Command context entity metadata id")})`),i}function Qwe(e,t,n){if(t===n){let r=e._iconwebresourceid_value;typeof r=="string"&&r&&!e.fonticon&&(e["[email protected]"]=`/webresourceset(${(0,Fl.normalizeGuid)(r,"Command icon web resource id")})`);return}if(t===void 0){e.fonticon="",e.IconWebResourceId=null;return}e.fonticon=t.toLowerCase().endsWith($_)?k_+t.slice(0,t.length-$_.length):t,e.IconWebResourceId=null}function Xwe(e){let t=(r,i)=>{let o=e[r];if(typeof o!="string"||o.length===0||e[`${i}@odata.bind`]!==void 0)return;let a=(0,Fl.normalizeGuid)(o,`Command ${i}`);e[`${i}@odata.bind`]=`/canvasapps(${a})`};e.onclickeventtype===Bwe&&t("_onclickeventformulacomponentlibraryid_value","OnClickEventFormulaComponentLibraryId");let n=e.visibilitytype;(!n||n===Vwe)&&t("_visibilityformulacomponentlibraryid_value","VisibilityFormulaComponentLibraryId")}function Zwe(e,t){if(!(!t||t.type!=="javascript")){if(e.onclickeventtype=qwe,t.webResourceId){let n=(0,Fl.normalizeGuid)(t.webResourceId,"Command action web resource id");e["[email protected]"]=`/webresourceset(${n})`}e.onclickeventjavascriptfunctionname=t.functionName,t.parameters!==void 0&&(e.onclickeventjavascriptparameters=t.parameters)}}function R_(e){return(0,F_.deterministicId)("flyout-group",e)}function eEe(e,t){return(0,F_.deterministicId)("loose-group",`${e}|${t}`)}function ab(e){var t,n,r;let i=[],o=a=>{let s=wa(a.bag)?Lo(a.bag,"appactionid"):void 0;return typeof s=="string"&&s?s:a.id};for(let a of(t=e.commandBars)!==null&&t!==void 0?t:[]){let s=q_(a.location);for(let u of(n=a.groups)!==null&&n!==void 0?n:[]){Uj(u)&&i.push({rowId:o(u),bag:wa(u.bag)?u.bag:void 0,kind:"group",bar:a.location,location:s,type:fn.ButtonType.Group,disabled:void 0});let l=c=>{var d,f;i.push({rowId:o(c),bag:wa(c.bag)?c.bag:void 0,kind:"control",bar:a.location,location:(d=c.location)!==null&&d!==void 0?d:s,type:B_(c.type),disabled:c.disabled}),((f=c.children)!==null&&f!==void 0?f:[]).forEach(l)};((r=u.controls)!==null&&r!==void 0?r:[]).forEach(l)}}return i}function tEe(e,t,n){var r,i;let o=e.entityLogicalName,a=new Map,s=new Map,u=new Map((t?ab(t):[]).map(f=>[f.rowId,f])),l=f=>new Map(nb(f).map(p=>[p.appactionid,p.row.location])),c=t?l(t):new Map,d;for(let f of ab(e)){if(f.bag){let h=Lo(f.bag,"location");if((0,Vd.isStorableLocation)(h)){if(f.kind==="group"&&x_(h)!==f.bar)throw kj(o,f.rowId,x_(h),f.bar,"stored");if(f.kind==="control"&&f.location!==h)throw tb(o,f.rowId,"Location",String(h),String(f.location),"stored")}let g=Lo(f.bag,"type");if(f.kind==="control"&&typeof g=="number"){let b=Dm(g);if(B_(b)!==f.type)throw tb(o,f.rowId,"type",b,Dm(f.type),"stored")}let y=Lo(f.bag,"isdisabled");if(f.kind==="control"){let b=n.has(f.rowId)?u.get(f.rowId):void 0,E=b?.kind==="control"&&b.bag?Lo(b.bag,"isdisabled"):y;f.disabled!==void 0&&(typeof E!="boolean"||f.disabled!==E)&&a.set(f.rowId,f.disabled);let w=(r=f.disabled)!==null&&r!==void 0?r:typeof E=="boolean"?E:void 0;w!==void 0&&w!==y&&s.set(f.rowId,w)}continue}let p=n.has(f.rowId)?u.get(f.rowId):void 0;if(!p||p.kind!==f.kind)continue;if(f.kind==="group"&&p.bar!==f.bar)throw kj(o,f.rowId,p.bar,f.bar,"pushed");if(f.kind==="control"){d=d??l(e);let h=c.get(f.rowId),g=d.get(f.rowId);if((0,Vd.isStorableLocation)(h)&&(0,Vd.isStorableLocation)(g)&&h!==g)throw tb(o,f.rowId,"Location",String(h),String(g),"pushed")}if(f.kind==="control"&&p.type!==f.type)throw tb(o,f.rowId,"type",Dm(p.type),Dm(f.type),"pushed");let m=(i=p.disabled)!==null&&i!==void 0?i:!1;f.kind==="control"&&f.disabled!==void 0&&f.disabled!==m&&a.set(f.rowId,f.disabled)}return{sentDisabled:a,disabledAfter:s}}function nEe(e,t,n){var r;let i={};if(!t)return i;let o=new Map(ab(t).map(a=>[a.rowId,a]));for(let a of ab(e)){let s=n.has(a.rowId)?(r=o.get(a.rowId))===null||r===void 0?void 0:r.disabled:void 0;a.kind==="control"&&!a.bag&&a.disabled===void 0&&typeof s=="boolean"&&(i[a.rowId]=s)}return i}var jj="An existing app action keeps its Location and its type: an update never carries either, and the platform ignores a Location update \u2014 so the push would report a change that did not happen. Nothing was written.";function Wj(e){return e==="stored"?"as stored on the server":"as last pushed \u2014 re-fetch the command to read the stored one"}function tb(e,t,n,r,i,o){return new Gd.SdkError(Gd.COMMAND_IMMUTABLE_COLUMN_CHANGED_CODE,`Refusing to push command '${e}': it would change the ${n} of app action '${t}' from ${r} (${Wj(o)}) to ${i}. ${jj} Set it back to ${r}${n==="Location"?" and keep the control in its bar":""}, or remove the control and add a new one with the ${n} you want.`)}function kj(e,t,n,r,i){return new Gd.SdkError(Gd.COMMAND_IMMUTABLE_COLUMN_CHANGED_CODE,`Refusing to push command '${e}': it would move group '${t}' from the ${n} bar (${Wj(i)}) to the ${r} bar, which is another Location. ${jj} Move it back to the ${n} bar, or remove it and add a new group to the ${r} bar.`)}function zj(e){let t={...e};for(let n of Gwe)delete t[n];return t}function rEe(e){let t=zj(e);for(let n of fn.CannotUpdateAppActionColumns)delete t[n];return t}var iEe={project:(e,t,n)=>new Pm().toArtifact({entityLogicalName:e,entityMetadataId:t,appActions:n}),projectedId:U_,action:e=>Fj(e)};function oEe(){return{adapter:new Pm,api:Vd.commandApi,publish:(e,t,n)=>(0,Tj.publishBoundEntity)(e,n),publishScope:(e,t)=>(0,Tj.boundEntityPublishScope)(t),inspect:(e,t,n)=>(0,Uwe.inspectCommandBar)(e,t,n,iEe)}}jd.commandRegistration=oEe});var Jj=C(km=>{"use strict";Object.defineProperty(km,"__esModule",{value:!0});km.chartApi=void 0;var aEe=Ke(),G_=qi(),zr=pe(),Su=ae(),Kj="savedqueryvisualizationid,name,description,primaryentitytypecode,datadescription,presentationdescription,charttype,type,isdefault",sEe="savedqueryvisualizationid,name,primaryentitytypecode,charttype,isdefault";km.chartApi={async get(e,t){let n=(0,Su.normalizeGuid)(t,"id"),r=await(0,zr.readRowEtag)(e,"savedqueryvisualizations","savedqueryvisualizationid",n),i=`/savedqueryvisualizations(${n})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,Su.odataQuery)([["$select",Kj]]);return{raw:(0,zr.ensureSuccess)(await e.get(i),e.apiUrl(i)).body,etag:r}},async readContentThenToken(e,t){let n=(0,Su.normalizeGuid)(t,"id"),r=`/savedqueryvisualizations(${n})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,Su.odataQuery)([["$select",Kj]]),i=(0,zr.ensureSuccess)(await e.get(r),e.apiUrl(r)),o=await(0,zr.readRowEtag)(e,"savedqueryvisualizations","savedqueryvisualizationid",n);return{raw:i.body,etag:o}},async list(e,t){let n=`/savedqueryvisualizations${(0,Su.odataQuery)([["$select",sEe],["$filter",t?.entityLogicalName?`primaryentitytypecode eq '${(0,Su.odataLiteral)(t.entityLogicalName)}'`:void 0]])}`;return(await(0,aEe.collectPages)(e,n,"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,n,r=void 0){let i=t,o=(0,zr.echoWrite)("savedqueryvisualizationid"),a=`/savedqueryvisualizations${o.query}`;if(r){let u=n?(0,Su.normalizeGuid)(n,"savedqueryvisualizationid"):void 0;return r.reached({effects:[{componentName:"SavedQueryVisualization",componentId:u,identity:"known",operation:"create"}],attemptsWrite:!0},u?()=>(0,G_.existsByKey)(e,r,{collection:"/savedqueryvisualizations",key:"savedqueryvisualizationid",id:u,componentName:"SavedQueryVisualization"}):void 0)}let s=(0,zr.ensureSuccess)(await e.post(a,(0,zr.withClientMintedId)({name:i.name,description:i.description,datadescription:i.datadescription,presentationdescription:i.presentationdescription,primaryentitytypecode:i.primaryentitytypecode,charttype:i.charttype,isdefault:i.isdefault},"savedqueryvisualizationid",n),o.options),e.apiUrl(a));return{id:(0,zr.resolveCreatedId)(s,"savedqueryvisualizationid","chart",n),etag:(0,zr.readEtag)(s)}},async update(e,t,n,r,i=void 0,o,a){let s=n,u=(0,Su.normalizeGuid)(t,"id");a&&!(0,zr.isVersionToken)(r)&&a.observe({guard:"ifMatch",componentName:"SavedQueryVisualization",componentId:u,held:r,status:"missingHeld"});let l=(0,zr.echoWrite)("savedqueryvisualizationid",{"If-Match":(0,zr.requireEtag)(r,"chart",u)}),c=`/savedqueryvisualizations(${u})${l.query}`;if(a)return await(0,G_.observeIfMatch)(e,a,{entitySet:"savedqueryvisualizations",idColumn:"savedqueryvisualizationid",id:u,componentName:"SavedQueryVisualization",held:l.options.headers["If-Match"]}),a.reached({effects:[{componentName:"SavedQueryVisualization",componentId:u,identity:"known",operation:"update"}],attemptsWrite:!0});let d=(0,zr.ensureSuccess)(await e.patch(c,{name:s.name,description:s.description,datadescription:s.datadescription,presentationdescription:s.presentationdescription},l.options),e.apiUrl(c));return{id:u,etag:(0,zr.readEtag)(d)}},delete(e,t){return(0,zr.deleteRecord)(e,"savedqueryvisualizations",t)},planPush(e,t,n){return(0,G_.planPushThrough)(km.chartApi,e,t,n)}}});var fW=C(zd=>{"use strict";Object.defineProperty(zd,"__esModule",{value:!0});zd.chartRegistration=zd.ChartAdapter=void 0;var j_=Us(),Yj=Vi(),Ea=ja(),Qj=mo(),uEe=Jj(),W_=Ga(),lEe=ft(),cEe=["Column","StackedColumn","StackedColumn100","Bar","StackedBar","StackedBar100","Area","StackedArea","StackedArea100","Line","Pie","Doughnut","Funnel","Tag"],dEe=new Map(cEe.map(e=>[e.toLowerCase(),e]));function nW(e){var t;return e&&(t=dEe.get(e.toLowerCase()))!==null&&t!==void 0?t:"Column"}function fEe(){return'<Chart Palette="BrightPastel"><Series><Series ChartType="Column" ChartArea="Default" /></Series><ChartAreas><ChartArea Name="Default" /></ChartAreas><Legends><Legend Name="Default" /></Legends></Chart>'}function pEe(e){var t,n;let r=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="${Wd(h.series.attribute)}" aggregate="${Wd(h.series.aggregate)}" />`,s=h=>`<attribute alias="${h.alias}" name="${Wd(h.category.attribute)}" groupby="true"${h.category.dateGrouping?` dategrouping="${Wd(h.category.dateGrouping)}"`:""} />`,u=[],l=new Map,c=(h,g)=>{if(!h){u.push(g);return}let y=l.get(h);y?y.push(g):l.set(h,[g])};i.forEach(h=>c(h.series.relatedEntity,a(h))),o.forEach(h=>c(h.category.relatedEntity,s(h)));let d=[...l.entries()].map(([h,g])=>`<link-entity name="${Wd(h)}">${g.join("")}</link-entity>`).join(""),f=u.join("")+d,p=i.map(h=>`<measurecollection><measure alias="${h.alias}" /></measurecollection>`).join(""),m=(n=(t=o[0])===null||t===void 0?void 0:t.alias)!==null&&n!==void 0?n:"";return`<datadefinition><fetchcollection><fetch mapping="logical" aggregate="true"><entity name="${Wd(r)}">${f}</entity></fetch></fetchcollection><categorycollection><category alias="${m}">${p}</category></categorycollection></datadefinition>`}var sb=class{toArtifact(t){var n,r,i,o,a,s,u;(0,W_.installDomShim)();let l=(n=t.datadescription)!==null&&n!==void 0?n:"",c=(r=t.presentationdescription)!==null&&r!==void 0?r:"",d=(0,Ea.parseXmlRoot)(l,"<datadefinition/>"),f=(0,Ea.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:ub(f),isDefault:(u=t.isdefault)!==null&&u!==void 0?u:!1,series:oW(d),categories:aW(d),presentation:rW(f),dataBag:l?(0,Ea.projectElementBag)(d):void 0,presentationBag:c?(0,Ea.projectElementBag)(f):void 0,rowBag:mEe(t.charttype,t.type)}}fromArtifact(t){(0,W_.installDomShim)();let{datadescription:n,presentationdescription:r}=hEe(t);return{savedqueryvisualizationid:t.id,name:t.name,description:t.description,primaryentitytypecode:t.entityLogicalName,datadescription:n,presentationdescription:r,charttype:Xj(t.rowBag,"charttype"),type:Xj(t.rowBag,"type"),isdefault:t.isDefault}}fromApiResponse(t){return this.toArtifact(t??{})}toApiPayload(t){var n,r,i,o,a,s,u;let l=this.fromArtifact(t);return{name:(n=l.name)!==null&&n!==void 0?n:"",description:(r=l.description)!==null&&r!==void 0?r:"",datadescription:(i=l.datadescription)!==null&&i!==void 0?i:"",presentationdescription:(o=l.presentationdescription)!==null&&o!==void 0?o:"",primaryentitytypecode:(a=l.primaryentitytypecode)!==null&&a!==void 0?a:"",charttype:(s=l.charttype)!==null&&s!==void 0?s:0,isdefault:(u=l.isdefault)!==null&&u!==void 0?u:!1}}createDefault(t){var n,r,i,o,a,s,u;(0,W_.installDomShim)();let l=(n=t.entityLogicalName)!==null&&n!==void 0?n:"";return{id:(r=t.id)!==null&&r!==void 0?r:(0,lEe.newId)(),name:(i=t.name)!==null&&i!==void 0?i:"New Chart",description:(o=t.description)!==null&&o!==void 0?o:"",entityLogicalName:l,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:(u=t.presentation)!==null&&u!==void 0?u:{palette:"BrightPastel",showLegend:!0}}}assignMissingIds(t){return t}validate(t){let n=[],r=t;return(0,Yj.childObjects)(r,"series","","series",n),(0,Yj.childObjects)(r,"categories","","category",n),n}};zd.ChartAdapter=sb;function mEe(e,t){let n=[];return e!==void 0&&n.push(["charttype",String(e)]),t!==void 0&&n.push(["type",String(t)]),n.length>0?{a:n,c:[]}:void 0}function Xj(e,t){if(!e)return;let n=e.a.find(([i])=>i===t);if(!n)return;let r=parseInt(n[1],10);return Number.isNaN(r)?void 0:r}function ub(e){let t=e.getElementsByTagName("Series");for(let n=0;n<t.length;n+=1)if(t[n].getAttribute("ChartType"))return nW(t[n].getAttribute("ChartType"));return"Column"}function rW(e){var t;let n={showLegend:e.getElementsByTagName("Legend").length>0},r=e.getAttribute("Palette");r&&(n.palette=r);let i=e.getElementsByTagName("Title")[0],o=((t=i?.textContent)!==null&&t!==void 0?t:"").trim();return o&&(n.title=o),n}function lb(e){return e.getElementsByTagName("fetch")[0]}function iW(e){let t=new Map;if(!e)return t;let n=e.getElementsByTagName("link-entity");for(let r=0;r<n.length;r+=1){let i=n[r],o=i.getAttribute("name");if(!o)continue;let a=i.getElementsByTagName("attribute");for(let s=0;s<a.length;s+=1){let u=a[s],l=u.getAttribute("alias")||u.getAttribute("name");l&&t.set(l,o)}}return t}function oW(e){let t=lb(e);if(!t)return[];let n=iW(t),r=t.getElementsByTagName("attribute"),i=[];for(let o=0;o<r.length;o+=1){let a=r[o],s=a.getAttribute("aggregate");if(!s)continue;let u=a.getAttribute("name");if(!u)continue;let l={attribute:u,aggregate:s},c=a.getAttribute("charttype");c&&(l.seriesType=nW(c));let d=a.getAttribute("alias");d&&(l.alias=d);let f=d||u,p=n.get(f);p&&(l.relatedEntity=p),i.push(l)}return i}function aW(e){var t;let n=lb(e);if(!n)return[];let r=iW(n),i=n.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 u=s.getAttribute("name");if(!u)continue;let l={attribute:u},c=s.getAttribute("dategrouping");c&&(l.dateGrouping=c);let d=s.getAttribute("alias");d&&(l.alias=d);let f=d||u,p=r.get(f);p&&(l.relatedEntity=p),o.push(l)}return o}function hEe(e){var t,n;let r=(t=e.series)!==null&&t!==void 0?t:[],i=(n=e.categories)!==null&&n!==void 0?n:[];if(!Zj(e.dataBag)||!Zj(e.presentationBag)){let c=pEe({...e,series:r,categories:i});return{datadescription:c,presentationdescription:$Ee(e,c)}}let o=new DOMParser().parseFromString("<root/>","text/xml"),a=eW(e.dataBag,"datadefinition",o),s=eW(e.presentationBag,"Chart",o),u=e.chartType||ub(s),l=oW(a);if(!z_(r,l)){let c=H_(a);gEe(o,a,r);let d=H_(a),f=d.length>0?d:r.map(()=>"");sW(o,s,f,c,u)}return z_(i,aW(a))||yEe(o,a,i),e.chartType&&e.chartType!==ub(s)&&cW(s,e.chartType),e.presentation&&!z_(e.presentation,rW(s))&&dW(s,e.presentation),{datadescription:(0,Ea.serializeNode)(a),presentationdescription:(0,Ea.serializeNode)(s)}}function Zj(e){return!!e&&(e.c.length>0||e.a.length>0)}function sW(e,t,n,r,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=[],u=o.childNodes;for(let d=0;d<u.length;d+=1)u[d].nodeType===1&&u[d].tagName==="Series"&&s.push(u[d]);let l=new Map;r.forEach((d,f)=>{let p=s[f];if(!p)return;let m=l.get(d);m?m.push(p):l.set(d,[p])});let c=n.map(d=>{let f=l.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 H_(e){let t=[],n=e.getElementsByTagName("measure");for(let r=0;r<n.length;r+=1)t.push(n[r].getAttribute("alias")||"");return t}function eW(e,t,n){let r={n:t,a:(0,j_.mergeAttrs)(e.a,[]),c:(0,j_.spliceChildren)(e.c,[])};return(0,j_.rebuildRaw)(r,(0,Ea.domEngine)(n),null)}function gEe(e,t,n){let r=lb(t),i=r?.getElementsByTagName("entity")[0];!r||!i||uW(e,t,i,SEe(r),n,_Ee,{aliasPrefix:"aggregate_column",addRef:wEe,removeRef:CEe})}function yEe(e,t,n){let r=lb(t),i=r?.getElementsByTagName("entity")[0];!r||!i||uW(e,t,i,NEe(r),n,IEe,{aliasPrefix:"groupby_column",addRef:EEe,removeRef:AEe})}function uW(e,t,n,r,i,o,a){let s=new Map;for(let p of r){let m=p.getAttribute("alias");m&&s.set(m,p)}let u=new Set,l=[],c=(p,m)=>{var h;let g=TEe(n,p),y=m.relatedEntity;(g??void 0)!==(y??void 0)&&((h=p.parentNode)===null||h===void 0||h.removeChild(p),tW(e,n,p,y))};for(let p of i){let m=p.alias?s.get(p.alias):void 0;m&&!u.has(m)?(o(m,p),c(m,p),u.add(m)):l.push(p)}let d=r.filter(p=>!u.has(p)),f=0;for(let p of l)if(f<d.length){let m=d[f];o(m,p),c(m,p),u.add(m),f+=1}else{let m=e.createElement("attribute"),h=p.alias||vEe(t,a.aliasPrefix);m.setAttribute("alias",h),o(m,p),tW(e,n,m,p.relatedEntity),a.addRef(e,t,h)}for(let p of r)if(!u.has(p)){let m=p.getAttribute("alias");m&&a.removeRef(t,m),DEe(p)}}function bEe(e){let t=new Set;for(let n of["attribute","measure","category"]){let r=e.getElementsByTagName(n);for(let i=0;i<r.length;i+=1){let o=r[i].getAttribute("alias");o&&t.add(o)}}return t}function vEe(e,t){let n=bEe(e);if(!n.has(t))return t;for(let r=2;;r+=1){let i=`${t}_${r}`;if(!n.has(i))return i}}function lW(e,t){let n=t.getElementsByTagName("categorycollection")[0];if(n)return n;let r=e.createElement("categorycollection");return t.appendChild(r),r}function wEe(e,t,n){let r=lW(e,t),i=r.getElementsByTagName("category")[0];i||(i=e.createElement("category"),r.appendChild(i));let o=e.createElement("measurecollection"),a=e.createElement("measure");a.setAttribute("alias",n),o.appendChild(a),i.appendChild(o)}function EEe(e,t,n){let r=lW(e,t),i=e.createElement("category");i.setAttribute("alias",n),r.appendChild(i)}function AEe(e,t){let n=e.getElementsByTagName("category");for(let r=0;r<n.length;r+=1)n[r].getAttribute("alias")===t&&n[r].removeAttribute("alias")}function CEe(e,t){var n;let r=e.getElementsByTagName("measure"),i=[];for(let o=0;o<r.length;o+=1)r[o].getAttribute("alias")===t&&i.push(r[o]);for(let o of i){let a=o.parentNode;a?.removeChild(o),a&&a.tagName==="measurecollection"&&!REe(a)&&((n=a.parentNode)===null||n===void 0||n.removeChild(a))}}function SEe(e){let t=[],n=e.getElementsByTagName("attribute");for(let r=0;r<n.length;r+=1)n[r].getAttribute("aggregate")&&t.push(n[r]);return t}function NEe(e){var t;let n=[],r=e.getElementsByTagName("attribute");for(let i=0;i<r.length;i+=1)((t=r[i].getAttribute("groupby"))!==null&&t!==void 0?t:"").toLowerCase()==="true"&&n.push(r[i]);return n}function _Ee(e,t){e.setAttribute("name",t.attribute),e.setAttribute("aggregate",t.aggregate),t.seriesType&&e.setAttribute("charttype",t.seriesType)}function IEe(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 TEe(e,t){let n=t.parentNode;for(;n&&n!==e;){let r=n;if(r.nodeType===1&&r.tagName==="link-entity")return r.getAttribute("name")||void 0;n=r.parentNode}}function tW(e,t,n,r){r?OEe(e,t,r).appendChild(n):t.appendChild(n)}function OEe(e,t,n){let r=t.getElementsByTagName("link-entity");for(let o=0;o<r.length;o+=1)if(r[o].getAttribute("name")===n)return r[o];let i=e.createElement("link-entity");return i.setAttribute("name",n),t.appendChild(i),i}function DEe(e){let t=e.parentNode;if(t&&(t.removeChild(e),t.tagName==="link-entity"&&!PEe(t))){let n=t.parentNode;n&&n.removeChild(t)}}function PEe(e){let t=e.childNodes;for(let n=0;n<t.length;n+=1){let r=t[n];if(r.nodeType===1){let i=r.tagName;if(i==="attribute"||i==="link-entity")return!0}}return!1}function REe(e){let t=e.childNodes;for(let n=0;n<t.length;n+=1)if(t[n].nodeType===1)return!0;return!1}function cW(e,t){let n=e.getElementsByTagName("Series"),r=!1;for(let i=0;i<n.length;i+=1)n[i].getAttribute("ChartType")&&(n[i].setAttribute("ChartType",t),r=!0);if(!r){for(let i=0;i<n.length;i+=1)if(!kEe(n[i])){n[i].setAttribute("ChartType",t);return}}}function kEe(e){let t=e.childNodes;for(let n=0;n<t.length;n+=1){let r=t[n];if(r.nodeType===1&&r.tagName==="Series")return!0}return!1}function dW(e,t){var n;let r=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=r.createElement("Legends"),e.appendChild(o));let a=r.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 u=0;u<s.length;u+=1)a.push(s[u]);for(let u of a)(n=u.parentNode)===null||n===void 0||n.removeChild(u)}}if(t.title!==void 0){let i=e.getElementsByTagName("Title")[0];i&&(i.textContent=t.title)}}function $Ee(e,t){let n=(0,Ea.parseXmlRoot)(fEe(),"<Chart/>"),r=e.chartType||ub(n);cW(n,r),e.presentation&&dW(n,e.presentation);let i=H_((0,Ea.parseXmlRoot)(t,"<datadefinition/>"));return i.length>0&&sW(n.ownerDocument,n,i,i.slice(0,1),r),(0,Ea.serializeNode)(n)}function z_(e,t){return JSON.stringify(e)===JSON.stringify(t)}function Wd(e){return String(e??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function LEe(){return{adapter:new sb,api:uEe.chartApi,publish:(e,t,n)=>(0,Qj.publishBoundEntity)(e,n),publishScope:(e,t)=>(0,Qj.boundEntityPublishScope)(t),rebaselineAfterPublish:"bracket"}}zd.chartRegistration=LEe});var K_=C(Aa=>{"use strict";Object.defineProperty(Aa,"__esModule",{value:!0});Aa.dashboardApi=Aa.unpublishedDashboardPath=Aa.dashboardEntity=void 0;var MEe=Ke(),pW=qi(),Nu=pe(),Ul=ae(),xEe=oE(),mW=Sc();function hW(e){return e&&e.toLowerCase()!=="none"?e:void 0}Aa.dashboardEntity=hW;var gW="formid,name,description,formxml,type,objecttypecode,istabletenabled,iscustomizable,componentstate,versionnumber",FEe={select:gW,required:["name","type","objecttypecode","istabletenabled"]},UEe="formid,name,type,objecttypecode",qEe=0,BEe=10;function yW(e){return`/systemforms(${e})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,Ul.odataQuery)([["$select",gW]])}Aa.unpublishedDashboardPath=yW;Aa.dashboardApi={async get(e,t){let n=(0,Ul.normalizeGuid)(t,"id"),r=yW(n),i=(0,Nu.ensureSuccess)(await e.get(r),e.apiUrl(r));return(0,mW.assertSystemFormRecordKind)(i.body,n,"dashboard","fetch"),{raw:i.body,etag:(0,Nu.readEtag)(i)}},async list(e,t){let n=[`(type eq ${qEe} or type eq ${BEe})`];t?.entityLogicalName&&n.push(`objecttypecode eq '${(0,Ul.odataLiteral)(t.entityLogicalName)}'`);let r=`/systemforms${(0,Ul.odataQuery)([["$select",UEe],["$filter",n.join(" and ")]])}`;return(await(0,MEe.collectPages)(e,r,"listArtifacts('dashboard')")).map(o=>{var a,s;let u=hW(o.objecttypecode);return{type:"dashboard",id:(a=o.formid)!==null&&a!==void 0?a:"",name:(s=o.name)!==null&&s!==void 0?s:"",...u?{entityLogicalName:u}:{},isDirty:!1}})},async create(e,t,n,r=void 0){let i=t,o=(0,Nu.echoWrite)("formid"),a=`/systemforms${o.query}`,s={name:i.name,description:i.description,formxml:i.formxml,istabletenabled:i.istabletenabled,type:i.type};if(i.objecttypecode&&(s.objecttypecode=i.objecttypecode),r){let l=n?(0,Ul.normalizeGuid)(n,"formid"):void 0;return r.reached({effects:[{componentName:"SystemForm",componentId:l,identity:"known",operation:"create"}],attemptsWrite:!0},l?()=>(0,pW.existsByKey)(e,r,{collection:"/systemforms",key:"formid",id:l,componentName:"SystemForm"}):void 0)}let u=(0,Nu.ensureSuccess)(await e.post(a,(0,Nu.withClientMintedId)(s,"formid",n),o.options),e.apiUrl(a));return{id:(0,Nu.resolveCreatedId)(u,"formid","dashboard",n),etag:(0,Nu.readEtag)(u)}},async update(e,t,n,r,i=void 0,o,a){let s=n;return(0,xEe.patchSystemForm)(e,(0,Ul.normalizeGuid)(t,"id"),"dashboard",{name:s.name,description:s.description,formxml:s.formxml,istabletenabled:s.istabletenabled},r,FEe,a)},readContentThenToken(e,t){return Aa.dashboardApi.get(e,t)},planPush(e,t,n){return(0,pW.planPushThrough)(Aa.dashboardApi,e,t,n)},async delete(e,t){let n=(0,Ul.normalizeGuid)(t,"id");return await(0,mW.assertSystemFormKind)(e,n,"dashboard"),(0,Nu.deleteRecord)(e,"systemforms",n)}}});var NW=C(Hd=>{"use strict";Object.defineProperty(Hd,"__esModule",{value:!0});Hd.inspectDashboard=Hd.validateDashboardInspectOptions=void 0;var AW=ja(),VEe=vy(),bs=Y(),GEe=Ga(),jEe=Eu(),bW=Rs(),CW=pe(),J_=ae(),WEe=K_(),zEe=vE(),vW=Sc(),vs="inspectArtifact('dashboard')",HEe="0x80040217",KEe=new Set([0,10]),JEe=20;function ws(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function wW(e){return ws(e)&&Array.isArray(e.a)&&e.a.every(t=>Array.isArray(t)&&t.length===2&&typeof t[0]=="string"&&typeof t[1]=="string")&&(e.c===void 0||Array.isArray(e.c))}function Y_(e){return e.replace(/[{}]/g,"").toLowerCase()}function SW(e,t){let n=(0,J_.normalizeGuid)(String(e??""),`${vs} id`);if(t===void 0)return{normalizedId:n};if(!ws(t))throw new bs.InvalidArgumentError(`${vs}: options must be an object when given.`);let r=Object.keys(t).find(a=>a!=="expected");if(r!==void 0)throw new bs.InvalidArgumentError(`${vs}: '${r}' is not a dashboard inspection option (only 'expected'${r==="find"||r==="appModuleId"?`; '${r}' is the command inspection's`:""}).`);let i=t.expected;if(i===void 0)return{normalizedId:n};if(!ws(i)||typeof i.id!="string"||!Array.isArray(i.components))throw new bs.InvalidArgumentError(`${vs}: expected must be a dashboard artifact (getArtifact before the push).`);if((0,J_.normalizeGuid)(i.id,`${vs} expected.id`)!==n)throw new bs.InvalidArgumentError(`${vs}: expected.id '${i.id}' is not the inspected dashboard '${n}' \u2014 a witness compares a row only with the artifact pushed to it.`);if(!wW(i.bag))throw new bs.InvalidArgumentError(`${vs}: expected.bag must be the dashboard's hybrid bag ({ a: [...], c: [...] }).`);i.components.forEach((a,s)=>{let u=`${vs}: expected.components[${s}]`;if(!ws(a))throw new bs.InvalidArgumentError(`${u} must be a dashboard component object.`);if(a.id!==void 0&&typeof a.id!="string")throw new bs.InvalidArgumentError(`${u}.id must be the control id (text) when given.`);if(a.bag!==void 0&&!wW(a.bag))throw new bs.InvalidArgumentError(`${u}.bag must be a hybrid bag ({ a: [...], c: [...] }) when given.`)});let o=new Set;for(let a of i.components)if(typeof a.id=="string"&&a.id!==""){let s=Y_(a.id);if(o.has(s))throw new bs.InvalidArgumentError(`${vs}: expected holds control id '${a.id}' twice, so its tiles cannot be paired with the row's.`);o.add(s)}return{normalizedId:n,expected:i}}Hd.validateDashboardInspectOptions=SW;function YEe(e){var t;let n=ws(e)?(t=e.error)!==null&&t!==void 0?t:e.Error:void 0,r=ws(n)?n.code:void 0;return typeof r=="string"?r:void 0}function QEe(e){var t;let n=ws(e)?(t=e.error)!==null&&t!==void 0?t:e.Error:void 0,r=ws(n)?n.message:void 0;return typeof r=="string"?r:void 0}async function XEe(e,t,n,r,i){var o;let{normalizedId:a,expected:s}=SW(t,n),u;try{u=await e.get((0,WEe.unpublishedDashboardPath)(a))}catch(g){return EW(a,"unreadable",{reasonCode:"READ_FAILED",reason:`The row could not be read: ${g instanceof Error?g.message:String(g)}`})}let l=(0,CW.nowIso)(),c=(g,y={})=>EW(a,g,y,l),d=YEe(u.body);if(u.status===404&&d?.toLowerCase()===HEe)return c("missing");if(u.status<200||u.status>=300)return c("unreadable",{reasonCode:"READ_FAILED",reason:`HTTP ${u.status}${d?` ${d}`:""}: ${(o=QEe(u.body))!==null&&o!==void 0?o:"no message"}`});let f=u.body,p=ZEe(f,a);if(p)return c(p.observation,{reasonCode:p.reasonCode,reason:p.reason});let m;try{m=r.fromApiResponse(f)}catch(g){return c("unreadable",{reasonCode:"SCHEMA",reason:`The row cannot be projected: ${g instanceof Error?g.message:String(g)}`})}if(!s)return c("present",{artifact:m});if(s.dashboardType==="Interactive")return c("unreadable",{reasonCode:"COMPARISON_NOT_ESTABLISHED",reason:"An Interactive dashboard is not compared: its stored form was never measured against what was sent."});if(s.components.some(g=>typeof g.name!="string"||g.name===""))return c("unreadable",{reasonCode:"COMPARISON_NOT_ESTABLISHED",reason:"A tile with an empty name is completed by the platform; its stored label cannot be checked."});let h;try{h=await(0,zEe.readProvisionedLanguages)(e)}catch(g){return c("unreadable",{reasonCode:"LANGUAGES_UNREADABLE",reason:`The org's provisioned languages could not be read: ${g instanceof Error?g.message:String(g)}`})}if(h.length!==1||h[0]!==i)return c("unreadable",{reasonCode:"COMPARISON_NOT_ESTABLISHED",reason:`The org provisions ${h.join(", ")}; a comparison is established only for one language that is the authoring language (${i}).`});try{let g=eAe(s,String(f.formxml));if(typeof g=="string")return c("unreadable",{reasonCode:"PAIRING",reason:g});(0,GEe.installDomShim)();let y=r.toApiPayload(g),b=String(f.formxml),E=(0,VEe.completeLabelsAsStored)(y.formxml,b,i,{emptyInsertionsOnly:!0}),w=r.fromApiResponse({...f,...y,formxml:E});if((0,bW.deepEqual)(w,m))return c("matching",{artifact:m});let _=(0,bW.deepDiff)(w,m).map(I=>I.pointer).slice(0,JEe);return c("conflicting",{reasonCode:"CONTENT",artifact:m,differences:_})}catch(g){return c("unreadable",{reasonCode:"COMPARISON_NOT_ESTABLISHED",reason:`The comparison could not be made: ${g instanceof Error?g.message:String(g)}`})}}Hd.inspectDashboard=XEe;function EW(e,t,n,r=(0,CW.nowIso)()){return{type:"dashboard",id:e,observedAt:r,observation:t,...n}}function ZEe(e,t){let n=o=>({observation:"unreadable",reasonCode:"SCHEMA",reason:o});if(!ws(e))return n("The answer is not a row.");let r;try{r=typeof e.formid=="string"?(0,J_.normalizeGuid)(e.formid,"formid"):void 0}catch{r=void 0}if(r!==t)return{observation:"unreadable",reasonCode:"IDENTITY_MISMATCH",reason:`The row answered with formid ${JSON.stringify(e.formid)}, not ${t}.`};let i=(0,vW.decodeCode)(e.type);if(!KEe.has(i))return(0,vW.isKnownSystemFormType)(i)?{observation:"conflicting",reasonCode:"KIND",reason:`The row is a systemform of type ${i}, not a dashboard.`}:n(`The row's type ${JSON.stringify(e.type)} is not a known systemform type.`);if(typeof e.name!="string")return n("The row has no name.");if(typeof e.istabletenabled!="boolean")return n("The row has no istabletenabled flag.");if(typeof e.objecttypecode!="string")return n("The row has no objecttypecode.");if(e.description!==void 0&&e.description!==null&&typeof e.description!="string")return n("The row has a description that is not text.");if(typeof e.formxml!="string"||e.formxml.trim()==="")return n("The row has no formxml.");try{let o=(0,AW.parseXmlRoot)(e.formxml,"<form/>");if(o.nodeName!=="form")return n(`The row's formxml root is <${o.nodeName}>, not <form>.`)}catch(o){return n(`The row's formxml cannot be parsed: ${o instanceof Error?o.message:String(o)}`)}}function eAe(e,t){var n,r,i,o,a,s,u,l,c,d,f,p;let m=new Map,h=(0,AW.parseXmlRoot)(t,"<form/>"),g=Array.from(h.getElementsByTagName("cell"));for(let b of g){let E=(n=b.getAttribute("id"))!==null&&n!==void 0?n:"";for(let w of Array.from(b.childNodes).filter(_=>_.nodeType===1&&_.nodeName==="control")){let _=Y_((r=w.getAttribute("id"))!==null&&r!==void 0?r:"");m.set(_,[...(i=m.get(_))!==null&&i!==void 0?i:[],E])}}let y=(0,jEe.cloneJson)(e);for(let b of y.components){if(((s=(a=(o=b.bag)===null||o===void 0?void 0:o.a)===null||a===void 0?void 0:a.find(I=>I[0]==="id"))===null||s===void 0?void 0:s[1])!==void 0)continue;let w=typeof b.id=="string"?Y_(b.id):"",_=w?(u=m.get(w))!==null&&u!==void 0?u:[]:[];if(_.length!==1||_[0]==="")return`Tile '${(l=b.id)!==null&&l!==void 0?l:""}' cannot be paired with a stored cell: ${_.length===0?"no stored cell holds its control id":`${_.length} stored cells hold its control id`}.`;b.bag={a:[...(d=(c=b.bag)===null||c===void 0?void 0:c.a)!==null&&d!==void 0?d:[],["id",_[0]]],c:(p=(f=b.bag)===null||f===void 0?void 0:f.c)!==null&&p!==void 0?p:[]}}return y}});var FW=C(Ca=>{"use strict";Object.defineProperty(Ca,"__esModule",{value:!0});Ca.dashboardRegistration=Ca.TILE_CLASS_ID=Ca.DashboardAdapter=void 0;var Lm=Us(),so=ja(),Q_=mo(),$m=Vi(),PW=K_(),X_=Ga(),ql=ft(),RW=ae(),kW=fl(),tAe=vy(),nAe=NW(),_W="0",Z_="10",rAe=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"]]),iAe="{3FF9A528-DD50-4ACA-8F10-2E5ED73513AD}",db=class{constructor(t=kW.DEFAULT_LCID){this.lcid=t}toArtifact(t){var n,r,i,o,a;(0,X_.installDomShim)();let s=(n=t.formxml)!==null&&n!==void 0?n:"",u=(0,so.parseXmlRoot)(s,"<form/>");return{id:(r=t.formid)!==null&&r!==void 0?r:"",name:(i=t.name)!==null&&i!==void 0?i:"",description:(o=t.description)!==null&&o!==void 0?o:"",dashboardType:oAe(t.type),entityLogicalName:(a=(0,PW.dashboardEntity)(t.objecttypecode))!==null&&a!==void 0?a:null,enabledForMobile:!!t.istabletenabled,layoutType:aAe(u),components:IW(u,this.lcid),bag:(0,so.projectElementBag)(u)}}fromArtifact(t){var n;return(0,X_.installDomShim)(),{formid:t.id,name:t.name,description:t.description,type:t.dashboardType==="Interactive"?Z_:_W,objecttypecode:(n=t.entityLogicalName)!==null&&n!==void 0?n:"",istabletenabled:t.enabledForMobile,formxml:TW(t,this.lcid)}}fromApiResponse(t){return this.toArtifact(t??{})}completeAsStored(t,n){return(0,tAe.completeRecordAsStored)(t,n,this.lcid)}toApiPayload(t){return{name:t.name,description:t.description,formxml:TW(t,this.lcid),istabletenabled:t.enabledForMobile,type:t.dashboardType==="Interactive"?Z_:_W,objecttypecode:t.entityLogicalName}}createDefault(t){var n,r,i,o,a,s,u,l;(0,X_.installDomShim)();let c=(0,so.parseXmlRoot)(vAe(),"<form/>");return{id:(n=t.id)!==null&&n!==void 0?n:(0,ql.newId)(),name:(r=t.name)!==null&&r!==void 0?r:"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:(u=t.layoutType)!==null&&u!==void 0?u:0,components:(l=t.components)!==null&&l!==void 0?l:IW(c,this.lcid),bag:(0,so.projectElementBag)(c)}}assignMissingIds(t){if(t&&typeof t=="object"&&!Array.isArray(t)&&"position"in t&&!("components"in t)){let n=t;(typeof n.id!="string"||n.id.length===0)&&(n.id=(0,ql.newId)())}return t}validate(t){let n=[],r=(0,$m.childObjects)(t,"components","","component",n),i=new Set;return r.forEach(({node:o,index:a})=>{let s=`/components/${a}`;for(let u of["position","parameters"]){let l=o[u];l!==void 0&&!(0,$m.isJsonObject)(l)&&n.push((0,$m.issue)(`${s}/${u}`,`component-${u}-must-be-object`,`a component ${u} must be a JSON object when present, got ${l===null?"null":typeof l}`))}if((0,$m.isJsonObject)(o.position)){let u=Mm(o.position);i.has(u)?n.push((0,$m.issue)(`${s}/position`,"component-position-collision",`two components occupy the same dashboard position (${u}); move one to a free cell`)):i.add(u)}}),n}};Ca.DashboardAdapter=db;function oAe(e){return String(e??"")===Z_?"Interactive":"Standard"}function aAe(e){let t=e?.getAttribute("formLayout")||e?.getAttribute("layoutType"),n=parseInt(t??"",10);return Number.isNaN(n)?0:n}function Oe(e,t){let n=[],r=e.childNodes;for(let i=0;i<r.length;i+=1){let o=r[i];o.nodeType===1&&o.tagName.toLowerCase()===t&&n.push(o)}return n}function IW(e,t){let n=[];return Oe(e,"tabs").flatMap(i=>Oe(i,"tab")).forEach((i,o)=>{Oe(i,"columns").flatMap(s=>Oe(s,"column")).forEach((s,u)=>{Oe(s,"sections").flatMap(c=>Oe(c,"section")).forEach((c,d)=>{sAe(c,{tabIndex:o,columnIndex:u,sectionIndex:d},n,t)})})}),n}function sAe(e,t,n,r){Oe(e,"rows").flatMap(o=>Oe(o,"row")).forEach((o,a)=>{Oe(o,"cell").forEach((s,u)=>{let l=uAe(s,{...t,rowIndex:a,cellIndex:u},r);l&&n.push(l)})})}function uAe(e,t,n){var r,i;let o=MW((r=e.getAttribute("id"))!==null&&r!==void 0?r:"");if(o.toLowerCase().startsWith("spacer"))return null;let a=Oe(e,"control")[0];if(!a)return null;let s=(i=a.getAttribute("classid"))!==null&&i!==void 0?i:"",u=dAe(a),l=fAe(s,u,a),c=lAe(a);return{id:a.getAttribute("id")||o,type:l,name:LW(e,n),classId:s,position:t,colspan:fb(e,"colspan",1),rowspan:fb(e,"rowspan",1),parameters:u,bag:(0,so.projectElementBag)(e),...c?{icProperties:c}:{}}}function $W(e){let t=e.childNodes;for(let n=0;n<t.length;n+=1){let r=t[n];if(r.nodeType===1&&r.tagName.toLowerCase()==="icproperties")return r}}function lAe(e){let t=$W(e);return t?(0,so.serializeNode)(t):void 0}function cAe(e,t,n){let r=$W(t);if(!n){r&&t.removeChild(r);return}let i=new DOMParser().parseFromString(n,"text/xml").documentElement,o=(0,Lm.rebuildRaw)((0,Lm.rawFromNode)((0,so.nodeLikeFromDom)(i)),(0,so.domEngine)(e),null);r&&(0,so.serializeNode)(r)===(0,so.serializeNode)(o)||(r?t.replaceChild(o,r):t.appendChild(o))}function LW(e,t){var n,r;let i=Oe(e,"labels")[0];if(!i)return"";let o=Oe(i,"label"),a=(n=o.find(s=>s.getAttribute("languagecode")===String(t)))!==null&&n!==void 0?n:o[0];return(r=a?.getAttribute("description"))!==null&&r!==void 0?r:""}function dAe(e){var t;let n={},r=Oe(e,"parameters")[0];if(!r)return n;let i=r.childNodes;for(let o=0;o<i.length;o+=1){let a=i[o];a.nodeType===1&&(n[a.tagName]=((t=a.textContent)!==null&&t!==void 0?t:"").trim())}return n}function fAe(e,t,n){var r;let i=rAe.get(e.toUpperCase());return i?i==="chart"?t.ChartGridMode==="Chart"?"chart":"list":i==="assistant"?((r=n.getAttribute("uniqueid"))!==null&&r!==void 0?r:"").toUpperCase()===iAe?"assistant":t.ChartGridMode!==void 0||n.getAttribute("indicationOfSubgrid")==="true"?t.ChartGridMode==="Chart"?"chart":"list":"unknown":i:"unknown"}function fb(e,t,n){var r;let i=parseInt((r=e.getAttribute(t))!==null&&r!==void 0?r:"",10);return Number.isNaN(i)?n:i}function MW(e){return e.replace(/^\{/,"").replace(/\}$/,"")}function pAe(e,t){let n={n:"form",a:(0,Lm.mergeAttrs)(e.bag.a,[]),c:(0,Lm.spliceChildren)(e.bag.c,[])};return(0,Lm.rebuildRaw)(n,(0,so.domEngine)(t),null)}function TW(e,t){let n=new DOMParser().parseFromString("<root/>","text/xml"),r=pAe(e,n);return gAe(n,r,e.components,t),mAe(n,r,e.components,t),(0,so.serializeNode)(r)}function mAe(e,t,n,r){let i=xW(t);for(let o of n)i.has(Mm(o.position))||hAe(e,t,o,r)}function hAe(e,t,n,r){var i,o,a,s;let u=(o=(i=n.position)===null||i===void 0?void 0:i.sectionIndex)!==null&&o!==void 0?o:0,l=wAe(t,e,u);for(let N of Oe(l,"row"))Oe(N,"cell").some(S=>Oe(S,"control").length>0)||l.removeChild(N);let c=n.classId||Ca.TILE_CLASS_ID[n.type]||Ca.TILE_CLASS_ID.iframe,d=n.rowspan&&n.rowspan>0?n.rowspan:4,f=n.bag&&OW(n.bag,"id")?String(OW(n.bag,"id")):cb((0,ql.newId)()),p=n.id?cb(n.id):cb((0,ql.newId)()),m=l.parentNode,h=Math.max(1,parseInt(m&&m.getAttribute&&m.getAttribute("columns")||"1",10)||1),g=Math.min(Math.max(1,n.colspan&&n.colspan>0?n.colspan:1),h),y=Oe(l,"row"),b=y[y.length-1],E=b?Oe(b,"cell").reduce((N,S)=>N+fb(S,"colspan",1),0):0;(!b||E+g>h)&&(b=e.createElement("row"),l.appendChild(b));let w=e.createElement("cell");w.setAttribute("id",f),w.setAttribute("colspan",String(g)),w.setAttribute("rowspan",String(d)),w.setAttribute("showlabel","true");let _=e.createElement("labels"),I=e.createElement("label");I.setAttribute("description",(a=n.name)!==null&&a!==void 0?a:""),I.setAttribute("languagecode",String(r)),_.appendChild(I),w.appendChild(_);let T=e.createElement("control");T.setAttribute("id",p),T.setAttribute("classid",cb(c));let O=e.createElement("parameters"),v=(s=n.parameters)!==null&&s!==void 0?s:{};for(let N of Object.keys(v)){let S=(0,RW.createSafeXmlElement)(e,N,"dashboard tile parameter");S.textContent=v[N],O.appendChild(S)}T.appendChild(O),w.appendChild(T),b.appendChild(w)}function OW(e,t){if(!e)return;let n=e.a.find(r=>r[0]===t);return n?n[1]:void 0}function gAe(e,t,n,r){var i;let o=xW(t),a=new Set(n.map(s=>Mm(s.position)));for(let s of n){let u=o.get(Mm(s.position));if(!u)continue;let l=Oe(u,"control")[0];l&&(yAe(e,u,s.name,r),bAe(e,l,s.parameters),DW(u,"colspan",s.colspan),DW(u,"rowspan",s.rowspan),s.icProperties!==void 0&&cAe(e,l,s.icProperties))}for(let[s,u]of o)a.has(s)||(i=u.parentNode)===null||i===void 0||i.removeChild(u)}function xW(e){let t=new Map;return Oe(e,"tabs").flatMap(r=>Oe(r,"tab")).forEach((r,i)=>{Oe(r,"columns").flatMap(a=>Oe(a,"column")).forEach((a,s)=>{Oe(a,"sections").flatMap(l=>Oe(l,"section")).forEach((l,c)=>{Oe(l,"rows").flatMap(f=>Oe(f,"row")).forEach((f,p)=>{Oe(f,"cell").forEach((m,h)=>{var g;MW((g=m.getAttribute("id"))!==null&&g!==void 0?g:"").toLowerCase().startsWith("spacer")||Oe(m,"control")[0]&&t.set(Mm({tabIndex:i,columnIndex:s,sectionIndex:c,rowIndex:p,cellIndex:h}),m)})})})})}),t}function Mm(e){let t=e??{};return`${t.tabIndex}.${t.columnIndex}.${t.sectionIndex}.${t.rowIndex}.${t.cellIndex}`}function yAe(e,t,n,r){if(n===LW(t,r))return;let i=Oe(t,"labels")[0];i||(i=e.createElement("labels"),t.appendChild(i));let o=Oe(i,"label").find(a=>a.getAttribute("languagecode")===String(r));o||(o=e.createElement("label"),o.setAttribute("languagecode",String(r)),i.appendChild(o)),o.setAttribute("description",n)}function bAe(e,t,n){var r;if(!n)return;let i=Object.keys(n);if(i.length===0)return;let o=Oe(t,"parameters")[0];o||(o=e.createElement("parameters"),t.appendChild(o));let a=new Map,s=o.childNodes;for(let u=0;u<s.length;u+=1){let l=s[u];l.nodeType===1&&a.set(l.tagName,l)}for(let u of i){let l=n[u],c=a.get(u);if(c)((r=c.textContent)!==null&&r!==void 0?r:"")!==l&&(c.textContent=l);else{let d=(0,RW.createSafeXmlElement)(e,u,"dashboard component parameter");d.textContent=l,o.appendChild(d)}}}function DW(e,t,n){fb(e,t,1)!==n&&e.setAttribute(t,String(n))}function vAe(e=2){let t=`{${(0,ql.newId)()}}`,n=`{${(0,ql.newId)()}}`,r=`{${(0,ql.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="${n}" name="Section 1" showlabel="false" columns="${i}"><rows><row><cell id="${r}" rowspan="12" colspan="${i}" showlabel="true" /></row></rows></section></sections></column></columns></tab></tabs></form>`}Ca.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 cb(e){return`{${e.replace(/[{}]/g,"")}}`}function wAe(e,t,n){var r;let i=Oe(e,"tabs").flatMap(l=>Oe(l,"tab"))[0];if(!i)throw new Error("addDashboardTile: dashboard formxml has no <tab>");let o=Oe(i,"columns").flatMap(l=>Oe(l,"column"))[0];if(!o)throw new Error("addDashboardTile: dashboard formxml has no <column>");let a=Oe(o,"sections").flatMap(l=>Oe(l,"section")),s=(r=a[n])!==null&&r!==void 0?r:a[0];if(!s)throw new Error("addDashboardTile: dashboard formxml has no <section>");let u=Oe(s,"rows")[0];return u||(u=t.createElement("rows"),s.appendChild(u)),u}function EAe(e=kW.DEFAULT_LCID){let t=new db(e);return{adapter:t,api:PW.dashboardApi,languageSensitive:!0,publish:(n,r,i)=>i?.entityLogicalName?(0,Q_.publishBoundEntity)(n,i):(0,Q_.publishDashboardById)(n,r),publishScope:(n,r)=>r?.entityLogicalName?(0,Q_.boundEntityPublishScope)(r):{envelope:"dashboard",targetIds:[n]},rebaselineAfterPublish:"bracket",inspect:(n,r,i)=>(0,nAe.inspectDashboard)(n,r,i,t,e)}}Ca.dashboardRegistration=EAe});var tI=C(Ei=>{"use strict";Object.defineProperty(Ei,"__esModule",{value:!0});Ei.readEveryInOrder=Ei.readInOrder=Ei.plainRead=Ei.resolveReadConcurrency=Ei.MAX_READ_CONCURRENCY=void 0;var UW=Y();Ei.MAX_READ_CONCURRENCY=8;function AAe(e){if(e===void 0)return 1;if(typeof e!="number"||!Number.isInteger(e)||e<1||e>Ei.MAX_READ_CONCURRENCY)throw new UW.InvalidArgumentError(`readConcurrency must be a whole number from 1 to ${Ei.MAX_READ_CONCURRENCY} (got ${typeof e=="string"?`'${e}'`:String(e)})`);return e}Ei.resolveReadConcurrency=AAe;var CAe=e=>({ok:!0,value:e}),eI=e=>({ok:!1,error:e});function SAe(e){let t=(async()=>e())().then(CAe,eI);return{outcome:t,finish:async n=>{await n()},discard:async()=>{await t}}}Ei.plainRead=SAe;async function qW(e,t,n,r,i){if(!Number.isInteger(t)||t<1)throw new UW.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(),u=!1,l=0,c,d=async f=>{if(u)return{refusal:new Error("The read was not started: an earlier read had already failed.")};try{let p=await n(e[f],f),m=p.outcome.catch(eI);return i==="stop"&&m.then(h=>{u=u||!h.ok}),{read:p,outcome:m}}catch(p){return u=u||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 y=s.then(()=>d(g));o.set(g,y),s=y}let p=await o.get(f),m="read"in p?await p.outcome:eI(p.refusal);if(!m.ok&&i==="stop"){c={error:m.error};break}l=f+1,o.delete(f);let h=()=>r(m,e[f],f);"read"in p?await p.read.finish(h):await h()}}finally{u=!0;for(let f=l;f<a;f+=1){let p=await o.get(f);"read"in p&&await p.read.discard().catch(()=>{})}}if(c)throw c.error}function NAe(e,t,n,r){return qW(e,t,n,(i,o,a)=>r(i.value,o,a),"stop")}Ei.readInOrder=NAe;function _Ae(e,t,n,r){return qW(e,t,n,r,"continue")}Ei.readEveryInOrder=_Ae});var iz=C(Bm=>{"use strict";Object.defineProperty(Bm,"__esModule",{value:!0});Bm.genPageApi=void 0;var pb=Ke(),ZW=Zo(),Bl=qi(),Ft=pe(),$e=ae(),xo=ia(),tn=Y(),ez=ft(),BW=tI();function IAe(e){if(ArrayBuffer.isView(e)){let n=e;return new Uint8Array(n.buffer,n.byteOffset,n.byteLength)}if(Object.prototype.toString.call(e)==="[object ArrayBuffer]")return new Uint8Array(e);let t=globalThis;if(t.Buffer&&t.Buffer.isBuffer(e)){let n=e;return new Uint8Array(n.buffer,n.byteOffset,n.byteLength)}}var Mo="uxagentprojects",Gl="uxagentprojectfiles",Um="agentconversationmessages",Kd="uxagentprojectid",cr="uxagentprojectfileid",jl="agentconversationmessageid",xm=`${Kd},name`,TAe=`${cr},filename,filetype`,tz=2e8,nz=200000001,_u={"MSCRM.IncludeUnpublished":"true"},nI={};function Vl(e,t){return{"MSCRM.VersioningChangeset":e,..._u,...t}}async function oI(e,t,n,r){var i;let o=`/${t}(${n})`+(0,$e.odataQuery)([["$select",r]]),a=(0,Ft.ensureSuccess)(await e.get(o,{headers:{..._u}}),e.apiUrl(o));return{row:(i=a.body)!==null&&i!==void 0?i:{},etag:(0,Ft.readEtag)(a)}}async function qm(e,t,n=_u){let r=`/${Gl}(${t})/filecontent/$value`,i=await e.get(r,{headers:{...n}});if(i.status===404)return{status:"unavailable",reason:"missing"};(0,Ft.ensureSuccess)(i,e.apiUrl(r));let o=i.body,a=IAe(o);if(a)return{status:"available",data:(0,xo.bytesToBase64)(a)};if(typeof o=="string")return{status:"available",data:(0,xo.utf8ToBase64)(o)};throw new tn.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 rz(e){let t=e.lastIndexOf("/");return t>=0?e.slice(t+1):e}async function OAe(e,t,n,r,i,o){if(!e.supportsBinaryPatch)throw new tn.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=`/${Gl}(${t})/filecontent`,s=(0,xo.base64ToBytes)(r);(0,$e.assertNoControlChars)(n,"generative-page file name"),(0,Ft.ensureSuccess)(await e.patchRaw(a,s,{headers:Vl(i,{"Content-Type":"application/octet-stream","Content-Length":String(s.byteLength),"x-ms-file-name":rz(n),...o?{"If-Match":"*"}:{}})}),e.apiUrl(a))}async function Fm(e,t,n=_u){let r=`/${Gl}`+(0,$e.odataQuery)([["$select",TAe],["$filter",`_${Kd}_value eq ${t}`]]);return(await(0,pb.collectPages)(e,r,"fetchArtifact('genPage')",void 0,{headers:{...n}})).map(o=>({row:o,etag:typeof o["@odata.etag"]=="string"?o["@odata.etag"]:null}))}async function rI(e,t){let n=`/${Um}`+(0,$e.odataQuery)([["$select",`${jl},message,messagesender,createdon`],["$filter",`_regardingobjectid_value eq ${t}`],["$orderby","createdon asc,versionnumber asc"]]);return(0,pb.collectPages)(e,n,"fetchArtifact('genPage')",void 0,{headers:{..._u}})}async function VW(e,t){var n,r,i;let{row:o,etag:a}=await oI(e,Mo,t,xm),s=new Map;for(let{row:u,etag:l}of await Fm(e,t))s.set((0,$e.normalizeGuid)(String((n=u[cr])!==null&&n!==void 0?n:""),cr),{filename:String((r=u.filename)!==null&&r!==void 0?r:""),filetype:Number(u.filetype),etag:l});return{name:String((i=o.name)!==null&&i!==void 0?i:""),etag:a,rows:s}}function GW(e,t,n){var r,i,o,a,s;let u=[];n||u.push({kind:"createProject",name:t.name});let l=new Set;for(let c of(r=t.files)!==null&&r!==void 0?r:[]){let d=(0,$e.normalizeGuid)(c.id,"file id");l.add(d);let f=n?.rows.get(d);if(c.content.status==="retain"){if(!n)throw new tn.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 tn.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)&&u.push({kind:"renameRow",file:c}):u.push({kind:"createRow",file:c}),c.content.status==="available"&&u.push({kind:"content",file:c,data:c.content.data,existing:f!==void 0}))}for(let c of(i=n?.rows.keys())!==null&&i!==void 0?i:[])l.has(c)||u.push({kind:"deleteRow",fileId:c});(!n||u.length>0||n.name!==t.name||((a=(o=t.messages)===null||o===void 0?void 0:o.length)!==null&&a!==void 0?a:0)>0)&&u.push({kind:"patchProject",name:t.name});for(let c of(s=t.messages)!==null&&s!==void 0?s:[])u.push({kind:"message",turn:c});return u}function aI(e){let t=(0,xo.base64ToUtf8)(e);return(0,xo.utf8ToBase64)(t)===(0,xo.bytesToBase64)((0,xo.base64ToBytes)(e))?t:void 0}function DAe(e,t,n,r){var i,o,a,s,u,l,c,d;let f=t.sender==="user"?{changeSet:r,dataSources:(o=(i=n.messageContext)===null||i===void 0?void 0:i.dataSources)!==null&&o!==void 0?o:[],model:(s=(a=n.messageContext)===null||a===void 0?void 0:a.model)!==null&&s!==void 0?s:"",enabledTools:(l=(u=n.messageContext)===null||u===void 0?void 0:u.enabledTools)!==null&&l!==void 0?l:[],configurableTools:(d=(c=n.messageContext)===null||c===void 0?void 0:c.configurableTools)!==null&&d!==void 0?d:[]}:{changeSet:r};return{...t.id?{[jl]:(0,$e.normalizeGuid)(t.id,"message id")}:{},"[email protected]":`/${Mo}(${e})`,message:t.message,messagecontext:JSON.stringify(f),messagesender:t.sender==="user"?tz:nz}}async function PAe(e,t,n){var r,i,o,a;let s=((r=n.messages)!==null&&r!==void 0?r:[]).map(f=>f.id).filter(f=>typeof f=="string"&&f!=="").map(f=>(0,$e.normalizeGuid)(f,"message id"));if(s.length===0)return n;let u=`/${Um}`+(0,$e.odataQuery)([["$select",`${jl},message,messagesender,_regardingobjectid_value`],["$filter",s.map(f=>`${jl} eq ${f}`).join(" or ")]]),l=await(0,pb.collectPages)(e,u,"pushArtifact('genPage')",void 0,{headers:{..._u}});if(l.length===0)return n;let c=new Map(l.map(f=>{var p;return[String((p=f[jl])!==null&&p!==void 0?p:"").toLowerCase(),f]})),d=[];for(let f of(i=n.messages)!==null&&i!==void 0?i:[]){let p=f.id?c.get((0,$e.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"?tz:nz)&&String((a=p._regardingobjectid_value)!==null&&a!==void 0?a:"").toLowerCase()===t))throw new tn.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{...n,messages:d}}function iI(e,t,n,r){switch(t.kind){case"createProject":return{method:"POST",path:`/${Mo}`,body:(0,Ft.withClientMintedId)({name:t.name},Kd,e),headers:Vl(r)};case"createRow":return{method:"POST",path:`/${Gl}`,body:(0,Ft.withClientMintedId)({filename:t.file.name,filetype:t.file.fileType,[`${Kd}@odata.bind`]:`/${Mo}(${e})`},cr,(0,$e.normalizeGuid)(t.file.id,"file id")),headers:Vl(r)};case"renameRow":return{method:"PATCH",path:`/${Gl}(${(0,$e.normalizeGuid)(t.file.id,"file id")})`,body:{filename:t.file.name,filetype:t.file.fileType},headers:Vl(r,{"If-Match":"*"})};case"content":{let i=aI(t.data);if(i===void 0)throw new tn.SdkError("GENPAGE_CONTENT_NOT_TEXT",`File '${t.file.name}' is not UTF-8 text and cannot ride in a change set.`);return(0,$e.assertNoControlChars)(t.file.name,"generative-page file name"),{method:"PATCH",path:`/${Gl}(${(0,$e.normalizeGuid)(t.file.id,"file id")})/filecontent`,rawBody:i,contentType:"application/octet-stream; charset=utf-8",headers:Vl(r,{"x-ms-file-name":rz(t.file.name),...t.existing?{"If-Match":"*"}:{}})}}case"deleteRow":return{method:"DELETE",path:`/${Gl}(${t.fileId})`,headers:Vl(r,{"If-Match":"*"})};case"patchProject":return{method:"PATCH",path:`/${Mo}(${e})`,body:{name:t.name},headers:Vl(r,{"If-Match":"*"})};case"message":return{method:"POST",path:`/${Um}`,body:DAe(e,t.turn,n,r)};default:{let i=t;throw new tn.SdkError("GENPAGE_WRITE_UNKNOWN",`Unknown generative-page write: ${JSON.stringify(i)}`)}}}function jW(e,t){return e.supportsAtomicBatch&&t.every(n=>n.kind!=="content"||aI(n.data)!==void 0)}async function WW(e,t,n,r,i){await(0,ZW.postChangeSet)(e,n.map(o=>iI(t,o,r,i)),`generative page '${t}' (${n.length} operation(s))`)}async function zW(e,t,n,r,i){var o;let a=[];for(let s of n){if(s.kind==="message"){a.push(s);continue}if(s.kind==="content"){await OAe(e,(0,$e.normalizeGuid)(s.file.id,"file id"),s.file.name,s.data,i,s.existing);continue}let u=iI(t,s,r,i),l={headers:(o=u.headers)!==null&&o!==void 0?o:{}},c=u.method==="POST"?await e.post(u.path,u.body,l):u.method==="PATCH"?await e.patch(u.path,u.body,l):await e.delete(u.path,l);(0,Ft.ensureSuccess)(c,e.apiUrl(u.path))}if(a.length===0)return{warnings:[],turnRecorded:!0};try{let s=a.map(u=>iI(t,u,r,i));if(e.supportsAtomicBatch)await(0,ZW.postChangeSet)(e,s,`the conversation turn of generative page '${t}'`);else for(let u of s)(0,Ft.ensureSuccess)(await e.post(u.path,u.body),e.apiUrl(u.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 HW(e,t,n,r,i,o,a){var s;let u=l=>({id:t,etag:null,memberEtags:{},warnings:[...a,l]});try{let l=await VW(e,t),c=new Map;for(let E of n)(E.kind==="createRow"||E.kind==="renameRow"||E.kind==="content")&&c.set((0,$e.normalizeGuid)(E.file.id,"file id"),E.file);let d=[];l.name!==r.name&&d.push(`the page is named '${l.name}', not '${r.name}'`);for(let[E,w]of c){let _=l.rows.get(E);_&&(_.filename!==w.name||_.filetype!==w.fileType)&&d.push(`file '${w.name}' is stored as '${_.filename}' (type ${_.filetype})`)}for(let E of n){if(E.kind!=="content")continue;let w=await qm(e,(0,$e.normalizeGuid)(E.file.id,"file id")),_=(0,xo.bytesToBase64)((0,xo.base64ToBytes)(E.data));(w.status!=="available"||w.data!==_)&&d.push(w.status==="available"?`file '${E.file.name}' holds ${(0,xo.base64ToBytes)(w.data).byteLength} byte(s) that differ from the ${(0,xo.base64ToBytes)(_).byteLength} written`:`file '${E.file.name}' holds no content`)}let f=new Set(n.filter(E=>E.kind==="content").map(E=>(0,$e.normalizeGuid)(E.file.id,"file id")));for(let[E,w]of c)!f.has(E)&&(await qm(e,E)).status==="available"&&d.push(`file '${w.name}' holds content this push did not write`);if(d.length>0)return u(`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 VW(e,t),m=[...p.rows.keys()],h=p.etag!==l.etag||p.rows.size!==l.rows.size||m.some(E=>{var w,_;return((w=l.rows.get(E))===null||w===void 0?void 0:w.etag)!==((_=p.rows.get(E))===null||_===void 0?void 0:_.etag)}),g=m.length!==i.size||m.some(E=>!i.has(E)),y={},b=[];for(let[E,w]of p.rows){let _=c.has(E)||!o?w.etag:(s=o.get(E))!==null&&s!==void 0?s:null;y[E]=_,_!==w.etag&&b.push(w.filename)}return h||g||!p.etag||Object.values(y).some(E=>!E)?u(`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.`):RAe({id:t,etag:p.etag,memberEtags:y},[...a,...b.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(l){return u(`The generative page was written, but reading it back failed (${l instanceof Error?l.message:String(l)}). The local baseline is unusable: re-fetch the page before editing it \u2014 the next push will refuse rather than overwrite blind.`)}}async function KW(e,t,n,r=e.readConcurrency){var i;let o=(0,$e.normalizeGuid)(t,"id"),{row:a,etag:s}=await oI(e,Mo,o,xm),u=await Fm(e,o),l={},c=[];if(r>1)await(0,BW.readInOrder)(u,r,({row:f})=>{var p;let m=(0,$e.normalizeGuid)(String((p=f[cr])!==null&&p!==void 0?p:""),cr);return(0,BW.plainRead)(async()=>({fileId:m,content:await qm(e,m)}))},({fileId:f,content:p},{row:m,etag:h})=>{l[f]=h,c.push({...m,content:p})});else for(let{row:f,etag:p}of u){let m=(0,$e.normalizeGuid)(String((i=f[cr])!==null&&i!==void 0?i:""),cr);l[m]=p;let h=await qm(e,m);c.push({...f,content:h})}return{raw:n?{project:a,files:c,conversation:await rI(e,o)}:{project:a,files:c},etag:s,memberEtags:l}}Bm.genPageApi={get(e,t,n){return KW(e,t,!0,n?.fileConcurrency)},getForRebaseline(e,t){return KW(e,t,!1)},async getPublished(e,t){var n,r;let i=(0,$e.normalizeGuid)(t,"id"),o=`/${Mo}(${i})`+(0,$e.odataQuery)([["$select",xm]]),a=await e.get(o);if(a.status===404)return null;(0,Ft.ensureSuccess)(a,e.apiUrl(o));let s=(n=a.body)!==null&&n!==void 0?n:{},u={},l=[],c=await Fm(e,i,nI);for(let{row:g,etag:y}of c){let b=(0,$e.normalizeGuid)(String((r=g[cr])!==null&&r!==void 0?r:""),cr);u[b]=y,l.push({...g,content:await qm(e,b,nI)})}let d=g=>g.map(({row:y,etag:b})=>`${String(y[cr])}@${String(b)}`).sort().join("|"),f=()=>new tn.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,Ft.ensureSuccess)(p,e.apiUrl(o));let m=await Fm(e,i,nI);if([(0,Ft.readEtag)(a),(0,Ft.readEtag)(p),...[...c,...m].map(g=>g.etag)].some(g=>!g))throw new tn.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,Ft.readEtag)(p)!==(0,Ft.readEtag)(a)||d(m)!==d(c))throw f();return{raw:{project:s,files:l,conversation:[]},etag:(0,Ft.readEtag)(a),memberEtags:u}},async list(e,t){let n=`/${Mo}`+(0,$e.odataQuery)([["$select",xm]]);return(await(0,pb.collectPages)(e,n,"listArtifacts('genPage')",void 0,{headers:{..._u}})).map(i=>{var o,a;return{type:"genPage",id:String((o=i[Kd])!==null&&o!==void 0?o:""),name:String((a=i.name)!==null&&a!==void 0?a:""),isDirty:!1}})},async create(e,t,n,r=void 0){var i;let o=t,a=n?(0,$e.normalizeGuid)(n,"id"):(0,ez.newId)(),s=GW(a,o,void 0);if(XW(e,s),QW(e,a,o),r)return r.reached({effects:JW(a,s),attemptsWrite:!0},()=>(0,Bl.existsByKey)(e,r,{collection:`/${Mo}`,key:Kd,id:a,componentName:"uxagentproject",headers:{..._u}}));let u=YW(o),l=[],c=!0;jW(e,s)?await WW(e,a,s,o,u):{warnings:l,turnRecorded:c}=await zW(e,a,s,o,u);let d=new Set(((i=o.files)!==null&&i!==void 0?i:[]).map(p=>(0,$e.normalizeGuid)(p.id,"file id"))),f=await HW(e,a,s,o,d,void 0,l);return c?f:{...f,intentPending:!0}},async update(e,t,n,r,i,o=void 0,a){var s,u;let l=n,c=(0,$e.normalizeGuid)(t,"id"),d={componentName:"uxagentproject",componentId:c},f=R=>({componentName:"uxagentprojectfile",componentId:R});if(!Array.isArray(l.files))throw new tn.SdkError("GENPAGE_FILES_REQUIRED",`Refusing to update generative page '${c}': 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 p=await PAe(e,c,l);QW(e,c,p);let m;try{m=await Fm(e,c)}catch(R){throw a?.observe({guard:"membership",...d,status:"readFailed",detail:(0,Bl.failureDetail)(R)}),R}let h;try{h=await oI(e,Mo,c,xm)}catch(R){throw a?.observe({guard:"parentToken",...d,held:r,status:(0,Bl.failedReadStatus)(R),detail:(0,Bl.failureDetail)(R)}),R}let{row:g,etag:y}=h;if(a?.observe({guard:"parentToken",...d,held:r,server:y,status:(0,Bl.compareTokens)(r,y)}),r&&y&&r!==y)throw new tn.SdkError(Ft.VERSION_CONFLICT_CODE,`Generative page '${c}' changed on the server after it was fetched (baseline ${r}, server ${y}) \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(!r||!y)throw new tn.SdkError(Ft.VERSION_CONFLICT_CODE,`Cannot verify generative page '${c}' before writing: ${r?"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 b=new Map(m.map(({row:R})=>{var x,G;return[(0,$e.normalizeGuid)(String((x=R[cr])!==null&&x!==void 0?x:""),cr),{filename:String((G=R.filename)!==null&&G!==void 0?G:""),filetype:Number(R.filetype)}]})),E=new Set(b.keys()),w=new Set(((s=p.files)!==null&&s!==void 0?s:[]).map(R=>(0,$e.normalizeGuid)(R.id,"file id")));if(!i)throw a?.observe({guard:"membership",...d,status:"missingHeld",detail:"no child baseline recorded"}),new tn.SdkError(Ft.VERSION_CONFLICT_CODE,`Cannot verify the files of generative page '${c}' 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 _=new Set(Object.keys(i).map(R=>R.toLowerCase()));for(let R of w)if(!E.has(R)&&_.has(R))throw a?.observe({guard:"membership",...f(R),status:"goneOnServer"}),new tn.SdkError(Ft.VERSION_CONFLICT_CODE,`Generative-page file '${R}' 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 R of E)if(!_.has(R))throw a?.observe({guard:"membership",...f(R),status:"addedOnServer"}),new tn.SdkError(Ft.VERSION_CONFLICT_CODE,`Generative-page file '${R}' 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.`);a?.observe({guard:"membership",...d,status:"equal"});let I=new Map(m.map(({row:R,etag:x})=>{var G;return[(0,$e.normalizeGuid)(String((G=R[cr])!==null&&G!==void 0?G:""),cr),x]}));for(let[R,x]of Object.entries(i)){let G=R.toLowerCase();if(!E.has(G))continue;let U=I.get(G);if(a?.observe({guard:"memberToken",...f(G),held:x,server:U??null,status:(0,Bl.compareTokens)(x,U)}),!x||!U)throw new tn.SdkError(Ft.VERSION_CONFLICT_CODE,`Cannot verify generative-page file '${G}' before writing: ${x?"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(x!==U)throw new tn.SdkError(Ft.VERSION_CONFLICT_CODE,`Generative-page file '${G}' changed on the server after this page was fetched (baseline ${x}, server ${U}) \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 T=GW(c,p,{rows:b,name:String((u=g.name)!==null&&u!==void 0?u:"")});if(XW(e,T),a)return a.reached({effects:JW(c,T),attemptsWrite:T.length>0});if(T.length===0)return{id:c,etag:y,memberEtags:Object.fromEntries(m.map(({row:R,etag:x})=>{var G;return[(0,$e.normalizeGuid)(String((G=R[cr])!==null&&G!==void 0?G:""),cr),x]}))};let O=YW(p),v=[],N=!0;jW(e,T)?await WW(e,c,T,p,O):{warnings:v,turnRecorded:N}=await zW(e,c,T,p,O);let S=await HW(e,c,T,p,w,I,v);return N?S:{...S,intentPending:!0}},planPush(e,t,n){return(0,Bl.planPushThrough)(Bm.genPageApi,e,t,n)},async delete(e,t){var n;let r=(0,$e.normalizeGuid)(t,"id"),i=await rI(e,r);await(0,Ft.deleteRecord)(e,Mo,r);let o=new Set(i.map(u=>{var l;return String((l=u[jl])!==null&&l!==void 0?l:"")}).filter(u=>u!=="")),a=!1;try{for(let u of await rI(e,r)){let l=String((n=u[jl])!==null&&n!==void 0?n:"");l!==""&&o.add(l)}}catch{a=!0}let s=[];for(let u of o)try{await(0,Ft.deleteRecord)(e,Um,u)}catch(l){l instanceof tn.ConnectionError&&l.statusCode===404||s.push(u)}if(s.length>0||a)throw new tn.SdkError("GENPAGE_HISTORY_NOT_DELETED",`Generative page '${r}' 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 ${Um} rows regarding '${r}'.`)}};function JW(e,t){let n=new Map,r=(i,o,a)=>{let s=`${i}:${o}`;n.has(s)||n.set(s,{componentName:i,componentId:o,identity:"known",operation:a})};for(let i of t)i.kind==="createProject"?r("uxagentproject",e,"create"):i.kind==="patchProject"?r("uxagentproject",e,"update"):i.kind==="createRow"?r("uxagentprojectfile",(0,$e.normalizeGuid)(i.file.id,"file id"),"create"):i.kind==="renameRow"?r("uxagentprojectfile",(0,$e.normalizeGuid)(i.file.id,"file id"),"update"):i.kind==="content"?r("uxagentprojectfile",(0,$e.normalizeGuid)(i.file.id,"file id"),i.existing?"update":"create"):i.kind==="deleteRow"&&r("uxagentprojectfile",i.fileId,"delete");return[...n.values()]}function YW(e){var t,n;return((n=(t=e.messages)===null||t===void 0?void 0:t.length)!==null&&n!==void 0?n:0)>0&&e.turnId!==void 0?`uxagentproject_${(0,$e.normalizeGuid)(e.turnId,"newTurn.id")}`:`uxagentproject_${(0,ez.newId)()}`}function RAe(e,t){var n;return t.length===0?e:{...e,warnings:[...(n=e.warnings)!==null&&n!==void 0?n:[],...t]}}function QW(e,t,n){var r,i;if(((i=(r=n.messages)===null||r===void 0?void 0:r.length)!==null&&i!==void 0?i:0)>1&&!e.supportsAtomicBatch)throw new tn.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 XW(e,t){let n=t.filter(i=>i.kind==="content");if(n.length>0&&!e.supportsBinaryPatch&&!e.supportsAtomicBatch)throw new tn.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.some(i=>aI(i.data)===void 0)&&!e.supportsBinaryPatch)throw new tn.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 wz=C(Yd=>{"use strict";Object.defineProperty(Yd,"__esModule",{value:!0});Yd.genPageRegistration=Yd.GenPageAdapter=void 0;var kAe=iz(),$Ae=mo(),lt=Vi(),bb=ft(),vb=ia(),mz=ae(),Iu=Y(),uI=gC(),sI=yE(),Tu=2e8,hz=200000001,As={source:{name:"src/pages/page.tsx",fileType:Tu},output:{name:"src/pages/page.compiled",fileType:hz},config:{name:"config.json",fileType:Tu},prompt:{name:"firstPrompt.json",fileType:Tu}},gz=Object.keys(As),LAe=["dataSources","model","connectorBindings","actionBindings"],MAe=["userMessage","agentMessage"];function lI(e){if(typeof e!="string")throw new Iu.InvalidArgumentError(`newTurn.id must be a valid GUID (got ${JSON.stringify(e)})`);return(0,mz.normalizeGuid)(e,"newTurn.id")}function xAe(e){try{return lI(e)}catch{return}}var FAe={source:"6f1c2a4e9b3d47a1b85c0e2f7d914a63",output:"a8e53d17c2f64b09a1d7e4b8c3f2069d",config:"3b97f0c64e2a4d8f95b1c7a0e6d3f814",prompt:"d24e8b51f7a34c6e8b09d5f1a2c7e3b6"},UAe="9c3e7a15d2b84f6e8a01c5d7b3f9e240";function yz(e,t,n){let r=(0,mz.normalizeGuid)(e,n).replace(/-/g,""),i=[];for(let a=0;a<32;a+=1)i.push(parseInt(r[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 mb(e,t){return yz(e,FAe[t],"id")}function qAe(e,t){let n=yz(e,UAe,"newTurn.id"),r=parseInt(n.slice(24),16)%2**47+(t==="agent"?1:0);return`${n.slice(0,24)}${r.toString(16).padStart(12,"0")}`}function oz(e){return typeof e=="string"&&e.trim()!==""?e:(0,bb.newId)()}function Es(e){return(0,lt.isJsonObject)(e)?e:{}}function Jd(e,t){return JSON.stringify(e??null)===JSON.stringify(t??null)}function hb(e){return JSON.parse(JSON.stringify(e))}function BAe(e){let t=Es(e);return t.status==="available"&&typeof t.data=="string"?{status:"available",data:t.data}:{status:"unavailable",reason:t.reason==="unpublished"?"unpublished":"missing"}}function Gm(e){if(!e||e.status!=="available")return;let t=(0,vb.base64ToUtf8)(e.data);return(0,vb.utf8ToBase64)(t)===e.data?t:void 0}function bz(e,t,n){var r,i,o,a;return e.source!==void 0&&t!==void 0&&t?.source===e.source&&Jd((r=t?.dataSources)!==null&&r!==void 0?r:[],(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,uI.isLoadableGenPageOutput)(n)}function VAe(e,t){var n;try{return bz(e,t,Gm((n=e.bag)===null||n===void 0?void 0:n.output))}catch{return!1}}function gb(e){if(e!==void 0)try{let t=JSON.parse(e.replace(/^\uFEFF/,""));return(0,lt.isJsonObject)(t)?t:void 0}catch{return}}function az(e,t){if(t===Tu&&e.includes("page.tsx"))return"source";if(t===hz&&e.includes(".compiled"))return"output";if(t===Tu&&e===As.config.name)return"config";if(t===Tu&&e===As.prompt.name)return"prompt"}function sz(e){let t=e.toLowerCase();return gz.some(n=>As[n].name.toLowerCase()===t)}function cI(e){return Object.fromEntries(e)}function vz(e,t,n,r){let i=[],o=new Set,a=new Set(t),s=u=>{if(o.has(u))return;let l=a.has(u)?e[u]:n&&Object.prototype.hasOwnProperty.call(n,u)?n[u]:void 0;l!==void 0&&(o.add(u),i.push([u,l]))};return(r??[]).forEach(s),t.forEach(s),Object.keys(n??{}).forEach(s),cI(i)}function uz(e){var t,n,r;return vz({dataSources:(t=e.dataSources)!==null&&t!==void 0?t:[],model:e.model,connectorBindings:e.connectorBindings,actionBindings:e.actionBindings},LAe,(n=e.bag)===null||n===void 0?void 0:n.config,(r=e.bag)===null||r===void 0?void 0:r.configKeys)}function lz(e){var t,n;return vz({userMessage:e.firstPrompt,agentMessage:e.firstAgentMessage},MAe,(t=e.bag)===null||t===void 0?void 0:t.prompt,(n=e.bag)===null||n===void 0?void 0:n.promptKeys)}function cz(e,t,n){let r=[];for(let[i,o]of Object.entries(n))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:r.push([i,o]);return t.configKeys=Object.keys(n),r.length>0&&(t.config=cI(r)),!0}function dz(e,t,n){let r=[];for(let[i,o]of Object.entries(n))if(i==="userMessage"||i==="agentMessage"){if(typeof o!="string")return!1;i==="userMessage"?e.firstPrompt=o:e.firstAgentMessage=o}else r.push([i,o]);return t.promptKeys=Object.keys(n),r.length>0&&(t.prompt=cI(r)),!0}function jm(e){var t,n;return e.source!==void 0||Object.keys((n=(t=e.bag)===null||t===void 0?void 0:t.rows)!==null&&n!==void 0?n:{}).length>0}var GAe=["dataSources","model","connectorBindings","actionBindings","firstPrompt","firstAgentMessage"];function fz(e){return jm(e)?[]:GAe.filter(t=>e[t]!==void 0).map(t=>(0,lt.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 pz(){return(0,lt.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 yb(e){return{status:"available",data:(0,vb.utf8ToBase64)(e)}}function Vm(e,t){var n,r;return{id:String((n=e.uxagentprojectid)!==null&&n!==void 0?n:""),name:String((r=e.name)!==null&&r!==void 0?r:""),files:t}}var wb=class{toArtifact(t){return t}fromArtifact(t){return t}fromApiResponse(t){let n=t,r=Es(n?.project),i=(Array.isArray(n?.files)?n.files:[]).map(g=>{var y,b,E;let w=Es(g);return{id:String((y=w.uxagentprojectfileid)!==null&&y!==void 0?y:""),name:String((b=w.filename)!==null&&b!==void 0?b:""),fileType:Number((E=w.filetype)!==null&&E!==void 0?E:Tu),content:BAe(w.content)}}),o=Array.isArray(n?.conversation)?n.conversation.map(g=>{var y,b;let E=Es(g);return{sender:Number(E.messagesender)===200000001?"agent":"user",message:String((y=E.message)!==null&&y!==void 0?y:""),createdOn:String((b=E.createdon)!==null&&b!==void 0?b:"")}}):void 0,a=g=>o?{...g,conversation:o}:g,s=new Map,u=[],l=!0;for(let g of i){let y=az(g.name,g.fileType);y?((s.has(y)||g.name!==As[y].name)&&(l=!1),s.set(y,g)):(sz(g.name)&&(l=!1),u.push(g))}if(!l||s.size===0)return a(Vm(r,i));let c=Vm(r,u),d={rows:{}};for(let[g,y]of s)d.rows[g]=y.id;let f=s.get("source");if(f){let g=Gm(f.content);if(g===void 0)return a(Vm(r,i));c.source=g}let p=s.get("output");p&&(d.output=p.content);let m=s.get("config");if(m){let g=gb(Gm(m.content));if(!g||!cz(c,d,g))return a(Vm(r,i))}let h=s.get("prompt");if(h){let g=gb(Gm(h.content));if(!g||!dz(c,d,g))return a(Vm(r,i))}return c.bag=d,a(c)}async toApiPayload(t,n,r){var i,o,a,s,u,l,c,d,f,p,m,h,g;if(n&&!Jd((i=t.conversation)!==null&&i!==void 0?i:[],(o=n.conversation)!==null&&o!==void 0?o:[]))throw new Iu.ValidationError("genPage",t.id,[(0,lt.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 y=fz(t);if(y.length>0)throw new Iu.ValidationError("genPage",t.id,y);let b=[],E=n===void 0,w=E&&t.firstPrompt===void 0&&t.newTurn?{...t,firstPrompt:t.newTurn.prompt,...t.newTurn.agentMessage!==void 0?{firstAgentMessage:t.newTurn.agentMessage}:{}}:t;if(jm(w)){let O=(s=(a=w.bag)===null||a===void 0?void 0:a.rows)!==null&&s!==void 0?s:{},v=U=>{var M;return(M=O[U])!==null&&M!==void 0?M:mb(w.id,U)},N=(U,M,q)=>{b.push({id:v(U),name:As[U].name,fileType:As[U].fileType,content:M,unchanged:q})};if(w.source!==void 0){N("source",yb(w.source),!E&&n?.source===w.source&&O.source!==void 0);let U=Gm((u=w.bag)===null||u===void 0?void 0:u.output);bz(w,n,U)?N("output",{status:"retain"},!0):N("output",yb(await this.compile(w,w.source,r)),!1)}else{if(O.source!==void 0)throw new Iu.ValidationError("genPage",w.id,[pz()]);if(O.output!==void 0){if(!E&&!Jd((l=n?.dataSources)!==null&&l!==void 0?l:[],(c=w.dataSources)!==null&&c!==void 0?c:[]))throw new Iu.ValidationError("genPage",w.id,[(0,lt.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.")]);N("output",{status:"retain"},!0)}}let S=uz(w),R=!E&&n!==void 0&&Jd(uz(n),S);(E||O.config!==void 0||!R)&&N("config",yb(JSON.stringify(S)),R&&O.config!==void 0);let x=lz(w),G=!E&&n!==void 0&&Jd(lz(n),x);(O.prompt!==void 0||Object.keys(x).length>0&&!G)&&N("prompt",yb(JSON.stringify(x)),G&&O.prompt!==void 0)}for(let O of(d=w.files)!==null&&d!==void 0?d:[]){let v=(f=n?.files)===null||f===void 0?void 0:f.find(N=>N.id===O.id);b.push({id:O.id,name:O.name,fileType:O.fileType,content:O.content,unchanged:v!==void 0&&Jd(v,O)})}let _=[],I;if(w.newTurn){I=w.newTurn.id===void 0?void 0:lI(w.newTurn.id);let O=v=>I===void 0?{}:{id:qAe(I,v)};_.push({...O("user"),sender:"user",message:w.newTurn.prompt}),w.newTurn.agentMessage&&_.push({...O("agent"),sender:"agent",message:w.newTurn.agentMessage})}let T=(m=(p=w.bag)===null||p===void 0?void 0:p.config)!==null&&m!==void 0?m:{};return{name:w.name,files:b,..._.length>0?{messages:_,messageContext:{dataSources:(h=w.dataSources)!==null&&h!==void 0?h:[],model:(g=w.model)!==null&&g!==void 0?g:"",enabledTools:Array.isArray(T.enabledTools)?T.enabledTools:[],configurableTools:Array.isArray(T.configurableTools)?T.configurableTools:[]},...I!==void 0?{turnId:I}:{}}:{}}}committed(t,n,r={intentPending:!1}){let i=this.serverState(t,n);return r.intentPending&&t.newTurn!==void 0?{artifact:{...i,newTurn:hb(t.newTurn)},baseline:i}:{artifact:i,baseline:i}}serverState(t,n){var r,i,o,a,s,u;if(!jm(t)&&!t.newTurn)return t;let l=hb(t);if(delete l.newTurn,!jm(t))return l;let c={...(r=l.bag)!==null&&r!==void 0?r:{},rows:{...(o=(i=l.bag)===null||i===void 0?void 0:i.rows)!==null&&o!==void 0?o:{}}};for(let d of(a=n.files)!==null&&a!==void 0?a:[]){let f=gz.find(m=>As[m].name===d.name&&As[m].fileType===d.fileType);if(!f||l.files.some(m=>m.id===d.id)||(c.rows[f]=d.id,d.content.status!=="available"))continue;let p=(0,vb.base64ToUtf8)(d.content.data);f==="output"?c.output={status:"available",data:d.content.data}:f==="config"?(delete c.config,delete l.dataSources,delete l.model,delete l.connectorBindings,delete l.actionBindings,cz(l,c,(s=gb(p))!==null&&s!==void 0?s:{})):f==="prompt"&&(delete c.prompt,delete l.firstPrompt,delete l.firstAgentMessage,dz(l,c,(u=gb(p))!==null&&u!==void 0?u:{}))}return l.bag=c,l}baselineContent(t){var n;let r={...t};return delete r.conversation,delete r.newTurn,r.files=[...(n=t.files)!==null&&n!==void 0?n:[]].sort((i,o)=>i.id<o.id?-1:i.id>o.id?1:0),r}normalize(t){let n=t.newTurn;if(!(0,lt.isJsonObject)(n))return t;if(n.id===void 0)return{...t,newTurn:{...n,id:(0,bb.newId)()}};let r=lI(n.id);return r===n.id?t:{...t,newTurn:{...n,id:r}}}async compile(t,n,r){var i,o;let a=(i=t.dataSources)!==null&&i!==void 0?i:[],s=[],u=[];if(a.forEach((p,m)=>{var h;let g=(h=r?.resolveEntity)===null||h===void 0?void 0:h.call(r,p);g&&g.columnDetailComplete===!0?s.push(g):u.push((0,lt.issue)(`/dataSources/${m}`,g?"genpage-data-source-incomplete":"genpage-data-source-unresolved",g?`the column metadata of data source '${p}' 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 '${p}' could not be read, so the page cannot be compiled with its enums. Check the table's logical name and that it exists in this environment.`))}),u.length>0)throw new Iu.ValidationError("genPage",t.id,u);if(!r?.loadTypeScript)throw new Iu.ValidationError("genPage",t.id,[(0,lt.issue)("/source","genpage-compiler-unavailable","no TypeScript compiler is available to compile the page")]);let l=await r.loadTypeScript(),c=s.length>0?(0,sI.buildGenPageRuntimeTypes)(s):void 0,d=s.length>0?(0,sI.buildGenPageLegacyEnums)(s):void 0,f=(0,uI.compileGenPage)(l,n,c,d,{iteration:(o=r.genPageIteration)!==null&&o!==void 0?o:uI.GENPAGE_ITERATION_DEFAULT});if(f.diagnostics.length>0)throw new Iu.ValidationError("genPage",t.id,f.diagnostics.map(jAe));return f.code}metadataNeeds(t,n){if(t.source===void 0||!Array.isArray(t.dataSources))return[];let r=VAe(t,n)?{fetchRequired:!1}:{};return t.dataSources.filter(i=>typeof i=="string"&&i!=="").map(i=>({entityLogicalName:i,fieldName:"",needsColumnDetail:!0,...r}))}createDefault(t){var n,r;let i=oz(t.id),o={id:i,name:(n=t.name)!==null&&n!==void 0?n:"New page",files:((r=t.files)!==null&&r!==void 0?r:[]).map(a=>{var s,u,l;return{id:oz(a.id),name:(s=a.name)!==null&&s!==void 0?s:"index.tsx",fileType:(u=a.fileType)!==null&&u!==void 0?u:Tu,content:(l=a.content)!==null&&l!==void 0?l:{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=hb(t.connectorBindings)),t.actionBindings!==void 0&&(o.actionBindings=hb(t.actionBindings)),o.source!==void 0&&(o.bag={rows:{source:mb(i,"source"),output:mb(i,"output"),config:mb(i,"config")}}),o}assignMissingIds(t){if(t==null)return{id:(0,bb.newId)()};if(!(0,lt.isJsonObject)(t))return t;let n=t;return(Object.keys(n).length===0||"id"in n||"content"in n||"fileType"in n||Array.isArray(n.files))&&(typeof n.id!="string"||n.id.trim()==="")&&(n.id=(0,bb.newId)()),n}validate(t){let n=[],r=t;for(let s of["source","model","firstPrompt","firstAgentMessage"])r[s]!==void 0&&typeof r[s]!="string"&&n.push((0,lt.issue)(`/${s}`,"genpage-field-type",`${s} must be a string, got ${typeof r[s]}`));if(r.source===void 0&&Es(Es(r.bag).rows).source!==void 0&&n.push(pz()),n.push(...fz(t)),r.newTurn!==void 0){let s=Es(r.newTurn);(!(0,lt.isJsonObject)(r.newTurn)||typeof s.prompt!="string"||s.prompt.trim()==="")&&n.push((0,lt.issue)("/newTurn/prompt","genpage-turn-prompt","newTurn needs a non-empty prompt")),s.agentMessage!==void 0&&typeof s.agentMessage!="string"&&n.push((0,lt.issue)("/newTurn/agentMessage","genpage-field-type","newTurn.agentMessage must be a string")),s.id!==void 0&&xAe(s.id)===void 0&&n.push((0,lt.issue)("/newTurn/id","genpage-turn-id","newTurn.id must be a GUID (case-insensitive, optionally brace-wrapped), or omitted so the SDK mints one. Reuse it only for the same page and intended turn."))}if(r.dataSources!==void 0)if(!Array.isArray(r.dataSources))n.push((0,lt.issue)("/dataSources","genpage-data-sources-array","dataSources must be an array of table logical names"));else{let s=new Set;r.dataSources.forEach((u,l)=>{typeof u!="string"||!sI.TABLE_LOGICAL_NAME.test(u)?n.push((0,lt.issue)(`/dataSources/${l}`,"genpage-data-source-name",`a data source must be a table logical name (lowercase, e.g. 'account'), got '${String(u)}'`)):s.has(u)?n.push((0,lt.issue)(`/dataSources/${l}`,"genpage-data-source-duplicate",`data source '${u}' is listed twice`)):s.add(u)})}r.conversation!==void 0&&!Array.isArray(r.conversation)&&n.push((0,lt.issue)("/conversation","genpage-conversation-array","conversation must be an array"));let i=r.files;if(i!==void 0&&!Array.isArray(i))return n.push((0,lt.issue)("/files","files-must-be-array",`files must be an array, got ${typeof i}`)),n;let o=jm(t),a=new Map;return(Array.isArray(i)?i:[]).forEach((s,u)=>{let l=`/files/${u}`,c=Es(s),d=typeof c.id=="string"?c.id.trim().toLowerCase():"";if(d==="")n.push((0,lt.issue)(l,"file-id-required","a generative-page file needs an id"));else{let g=a.get(d);g!==void 0?n.push((0,lt.issue)(l,"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,u)}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==="..")?n.push((0,lt.issue)(l+"/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&&(sz(f)||az(f,Number(c.fileType))!==void 0)&&n.push((0,lt.issue)(l+"/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){n.push((0,lt.issue)(l+"/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=Es(m);h.status==="available"?typeof h.data!="string"&&n.push((0,lt.issue)(l+"/content/data","file-content-data-invalid","available content needs base64 `data`")):h.status!=="unavailable"&&n.push((0,lt.issue)(l+"/content/status","file-content-status-invalid",`content.status must be 'available' or 'unavailable', got ${String(h.status)}`))}),n}};Yd.GenPageAdapter=wb;function jAe(e){let t=`line ${e.line}, column ${e.column}`;return e.rule==="genpage-source-syntax"?(0,lt.issue)("/source",e.rule,`${t}: ${e.message} (TS${e.code}) \u2014 the page cannot run, so it was not pushed`):(0,lt.issue)("/source",e.rule,`${t}: ${e.message}`)}function WAe(){return{adapter:new wb,api:kAe.genPageApi,publish:(e,t)=>(0,$Ae.publishGenPageById)(e,t),publishScope:e=>({envelope:"uxagentproject",targetIds:[e]}),rebaselineAfterPublish:"snapshot"}}Yd.genPageRegistration=WAe});var Az=C(Ab=>{"use strict";Object.defineProperty(Ab,"__esModule",{value:!0});Ab.reconcileBpfSecurityRoles=void 0;var Ez=Ke(),fI=Y(),Eb=pe(),Wm=ae(),zAe="Global",dI={create:"Create",read:"Read",write:"Write",delete:"Delete"};async function HAe(e,t){var n;let r=`/EntityDefinitions(LogicalName='${(0,Wm.odataPathLiteral)(t)}')?$select=LogicalName,Privileges`,i=(0,Eb.ensureSuccess)(await e.get(r),e.apiUrl(r)),o=(n=i.body)===null||n===void 0?void 0:n.Privileges;if(!Array.isArray(o))throw new fI.ConnectionError(e.apiUrl(r),i.status,`reading the privileges of business process flow table '${t}' returned no 'Privileges' array (got ${(0,Ez.describeMalformedValue)(o)}), so which access it can grant is unknown.`);let a=o,s={},u=new Set;return Object.keys(dI).forEach(l=>{let c=a.find(d=>d.PrivilegeType===dI[l]);if(c){let d=(0,Wm.normalizeGuid)(c.PrivilegeId,"PrivilegeId");s[l]=d,u.add(d)}}),{byAccess:s,all:u}}async function KAe(e,t){var n;let r=`/RetrieveRolePrivilegesRole(RoleId=${t})`,i=(0,Eb.ensureSuccess)(await e.get(r),e.apiUrl(r)),o=(n=i.body)===null||n===void 0?void 0:n.RolePrivileges;if(!Array.isArray(o))throw new fI.ConnectionError(e.apiUrl(r),i.status,`reading the privileges of role '${t}' returned no 'RolePrivileges' array (got ${(0,Ez.describeMalformedValue)(o)}), so what it holds is unknown.`);return new Set(o.map(a=>(0,Wm.normalizeGuid)(a.PrivilegeId,"PrivilegeId")))}async function JAe(e,t,n){if(n.length===0)return;let r={Privileges:n.map(o=>({Depth:zAe,PrivilegeId:o}))},i=`/roles(${t})/Microsoft.Dynamics.CRM.AddPrivilegesRole`;(0,Eb.ensureSuccess)(await e.post(i,r),e.apiUrl(i))}async function YAe(e,t,n){let r={Privilege:{"@odata.type":"Microsoft.Dynamics.CRM.privilege",privilegeid:n}},i=`/roles(${t})/Microsoft.Dynamics.CRM.RemovePrivilegeRole`;(0,Eb.ensureSuccess)(await e.post(i,r),e.apiUrl(i))}async function QAe(e,t,n){var r,i,o;if(!n||n.length===0)return;let a=await HAe(e,t.toLowerCase());for(let s of n){let u=(0,Wm.normalizeGuid)(s.roleId,"roleId"),l=((r=s.access)!==null&&r!==void 0?r:[]).find(c=>!a.byAccess[c]);if(l!==void 0)throw new fI.InvalidArgumentError(`Cannot grant '${l}' access to role '${u}' on business process flow table '${t.toLowerCase()}': its metadata lists no '${(i=dI[l])!==null&&i!==void 0?i:l}' privilege. No security role was changed.`)}for(let s of n){let u=(0,Wm.normalizeGuid)(s.roleId,"roleId"),l=new Set(((o=s.access)!==null&&o!==void 0?o:[]).map(m=>a.byAccess[m]).filter(m=>!!m)),c=await KAe(e,u),d=new Set([...c].filter(m=>a.all.has(m))),f=[...l].filter(m=>!d.has(m)),p=[...d].filter(m=>!l.has(m));await JAe(e,u,f);for(let m of p)await YAe(e,u,m)}}Ab.reconcileBpfSecurityRoles=QAe});var Lz=C(Hm=>{"use strict";Object.defineProperty(Hm,"__esModule",{value:!0});Hm.bpfApi=void 0;var Hr=Ds(),Cz=Zo(),XAe=Ke(),nn=Y(),pI=qi(),Gt=pe(),uo=ae(),ZAe=Az(),eCe=Dv(),zm=Rv(),tCe={"Content-Type":"application/json",Accept:"application/json"},mI={...tCe,Prefer:"return=representation"},nCe=`category eq ${Hr.WorkflowCategory.BusinessProcessFlow} and type eq ${Hr.WorkflowTypeCode.Definition} and businessprocesstype eq ${Hr.BusinessProcessType.BusinessFlow}`,rCe="workflowid,name,description,primaryentity,statecode,category,type,businessprocesstype,processorder",iCe="workflowid,name,uniquename,description,primaryentity,statecode,statuscode,category,type,businessprocesstype,processorder,xaml,clientdata",oCe=["xaml","name","description","processorder"];async function Cb(e,t){var n;if(t.status!=="Active"||!t.securityRoles||t.securityRoles.length===0)return;let r=String((n=t.record.uniquename)!==null&&n!==void 0?n:"");r!==""&&await(0,ZAe.reconcileBpfSecurityRoles)(e,r,t.securityRoles)}async function gI(e,t,n){let r={statecode:Hr.StateCode.Activated,statuscode:Hr.StatusCode.Activated},i=`/workflows(${t})`,{response:o,resent:a}=await $z(e,i,r,n,null);try{return(0,Gt.ensureSuccess)(o,e.apiUrl(i))}catch(s){throw a?Rz(s):s}}var Pz=new WeakSet;function Rz(e){return typeof e=="object"&&e!==null&&Pz.add(e),e}function kz(e){return typeof e=="object"&&e!==null&&Pz.has(e)}function Sz(e){return e instanceof nn.ConnectionError&&(e.statusCode===0||Gt.AMBIGUOUS_WRITE_STATUSES.has(e.statusCode))}async function $z(e,t,n,r,i){let o=r??i,a=0;try{return{response:await(0,Gt.resendWhile)(Gt.isConcurrencyLockRefusal,()=>{a+=1;let u=a===1?r:o,l={...mI};return u&&(l["If-Match"]=u),e.patch(t,n,{headers:l})},o?Gt.LOCK_BACKOFF_MS:[]),resent:a>1}}catch(s){throw a>1?Rz(s):s}}async function Nz(e,t,n){return(0,Gt.readEtag)(await gI(e,t,n))}function _z(e,t){return new nn.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. `+Sb(e))}async function Km(e,t){var n;let r=`/workflows(${t})${(0,uo.odataQuery)([["$select","statecode"]])}`,i=(0,Gt.ensureSuccess)(await e.get(r),e.apiUrl(r)),o=(n=i.body)===null||n===void 0?void 0:n.statecode,a=Number(o);if(o==null||o===""||!Number.isFinite(a))throw new nn.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 hI(e,t,n,r,i=null){if((r??await Km(e,t))!==Hr.StateCode.Activated)return{deactivated:!1,etag:null};let o={statecode:Hr.StateCode.Draft,statuscode:Hr.StatusCode.Draft},a=`/workflows(${t})`,s,u;try{({response:s,resent:u}=await $z(e,a,o,n,i))}catch(c){return await Iz(e,t,c,kz(c))}if(Gt.AMBIGUOUS_WRITE_STATUSES.has(s.status))return await Iz(e,t,new nn.SdkError("BPF_DEACTIVATE_OUTCOME_UNKNOWN",`Deactivating business process flow '${t}' answered HTTP ${s.status} from an intermediary, so whether it committed is unknown.`),u);let l=(0,Gt.ensureSuccess)(s,e.apiUrl(a));return{deactivated:!0,etag:(0,Gt.readEtag)(l)}}async function Iz(e,t,n,r){let i;try{i=await Km(e,t)}catch{i=void 0}if(i===Hr.StateCode.Draft&&!r)return{deactivated:!0,etag:null,uncertainCause:n};if(i===Hr.StateCode.Activated)throw n;let o=new nn.SdkError("BPF_DEACTIVATE_OUTCOME_UNKNOWN",i===Hr.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: ${n instanceof Error?n.message:String(n)}`:`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: ${n instanceof Error?n.message:String(n)}`);throw(0,nn.attachCause)(o,n),o}async function aCe(e,t){let n=(0,uo.normalizeGuid)(t,"workflowid");try{return await gI(e,n,null),"restored"}catch{return yI(e,n)}}async function sCe(e,t,n){let r=(0,uo.normalizeGuid)(t,"workflowid");try{let i=await gI(e,r,n);return{outcome:"restored",acknowledged:!0,echo:(0,Gt.readEtag)(i)}}catch(i){return i instanceof nn.SdkError&&i.code===Gt.VERSION_CONFLICT_CODE?{outcome:"changed",acknowledged:!1,echo:null}:{outcome:await yI(e,r),acknowledged:!1,echo:null}}}async function yI(e,t){try{let n=await Km(e,t);return n===Hr.StateCode.Activated?"restored":n===Hr.StateCode.Draft?"disabled":"unknown"}catch{return"unknown"}}async function Tz(e,t,n,r){return n?{...await sCe(e,t,n),attempted:!0}:r?{outcome:await yI(e,(0,uo.normalizeGuid)(t,"workflowid")),attempted:!1,acknowledged:!1,echo:null}:{outcome:await aCe(e,t),attempted:!0,acknowledged:!1,echo:null}}function uCe(e,t){let n=new nn.SdkError(zm.WORKFLOW_DELETE_UNSETTLED_CODE,`Deleting business process flow '${e}' failed${(0,zm.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,nn.attachCause)(n,t),n}function Oz(e,t,n,r,i=!0){let o=`Original failure: ${r instanceof Error?r.message:String(r)}`,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 n==="changed"?s=new nn.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}`):n==="disabled"?s=new nn.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 nn.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,nn.attachCause)(s,r),s}async function lCe(e,t){try{return await Km(e,t),"survived"}catch(n){return n instanceof nn.ConnectionError&&n.statusCode===404?"removed":"unknown"}}async function cCe(e,t,n){if(n)try{let{deactivated:r,etag:i}=await hI(e,t,n),o=r?i:n;if(o)return await(0,zm.deleteWorkflowResending)(e,t,{bindingToken:o,kindName:"business process flow",resendDeadlockVictim:!0,ifMatchOnFirst:!0}),"removed"}catch{}return lCe(e,t)}function Sb(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 Dz(e,t){return new nn.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. ${Sb(e)}`)}function dCe(e,t){let n=new nn.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.) ${Sb(e)} Or delete it. Original failure: ${t instanceof Error?t.message:String(t)}`);return(0,nn.attachCause)(n,t),n}function fCe(e,t){let n=new nn.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. ${Sb(e)} Or delete it. Original failure: ${t instanceof Error?t.message:String(t)}`);return(0,nn.attachCause)(n,t),n}function pCe(e,t){let n=new nn.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,nn.attachCause)(n,t),n}function bI(e){let t={};for(let n of oCe)e[n]!==void 0&&(t[n]=e[n]);return t}var mCe=["name,processorder","description,name,processorder"];function hCe(e){let{xaml:t,...n}=bI(e);return typeof t=="string"&&mCe.includes(Object.keys(n).sort().join(","))}async function gCe(e,t,n,r){let{xaml:i,...o}=bI(n),[,a]=await(0,Cz.sendChangeSet)(e,[{method:"PATCH",path:`/workflows(${t})`,body:o,etag:r},{method:"PATCH",path:`/workflows(${t})${(0,uo.odataQuery)([["$select","workflowid"]])}`,body:{xaml:i},headers:{Prefer:"return=representation"}}],`business process flow '${t}'`,{resendWhileLockRefused:!0});return(0,Gt.readEtag)((0,Cz.partResponse)(a))}Hm.bpfApi={async get(e,t){let r=`/workflows(${(0,uo.normalizeGuid)(t,"id")})${(0,uo.odataQuery)([["$select",iCe]])}`,i=(0,Gt.ensureSuccess)(await e.get(r),e.apiUrl(r));return{raw:i.body,etag:(0,Gt.readEtag)(i)}},async list(e,t){let n=[nCe];t?.entityLogicalName&&n.push(`primaryentity eq '${(0,uo.odataLiteral)(t.entityLogicalName)}'`);let r=`/workflows${(0,uo.odataQuery)([["$select",rCe],["$filter",n.join(" and ")]])}`;return(await(0,XAe.collectPages)(e,r,"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,n=void 0,r){let i=t,o=(0,uo.normalizeGuid)(i.record.workflowid,"workflowid"),a="/workflows";if(r)return r.reached({effects:[{componentName:"Workflow",componentId:o,identity:"known",operation:"create"}],attemptsWrite:!0},()=>(0,pI.existsByKey)(e,r,{collection:"/workflows",key:"workflowid",id:o,componentName:"Workflow"}));let s=(0,Gt.ensureSuccess)(await e.post(a,i.record,{headers:mI}),e.apiUrl(a)),u=(0,Gt.readEtag)(s);if(!u)throw Dz(o,i.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 l=u;try{i.status==="Active"&&(l=await Nz(e,o,u)),await Cb(e,i)}catch(c){let d=await cCe(e,o,l);throw d==="survived"?dCe(o,c):d==="unknown"?fCe(o,c):c instanceof nn.SdkError&&c.code===Gt.VERSION_CONFLICT_CODE?pCe(o,c):c}if(!l)throw Dz(o,"The process EXISTS and IS Active, but its activation returned no token.");return{id:o,etag:l}},async update(e,t,n,r,i=void 0,o,a){let s=n,u=(0,uo.normalizeGuid)(t,"id");a&&!(0,Gt.isVersionToken)(r)&&a.observe({guard:"ifMatch",componentName:"Workflow",componentId:u,held:r,status:"missingHeld"});let l=(0,Gt.requireEtag)(r,"bpf",u),c=await Km(e,u);if(a)return await(0,pI.observeIfMatch)(e,a,{entitySet:"workflows",idColumn:"workflowid",id:u,componentName:"Workflow",held:l}),a.reached({effects:[{componentName:"Workflow",componentId:u,identity:"known",operation:"update"}],attemptsWrite:!0});if(c===Hr.StateCode.Activated&&s.status==="Active"&&e.supportsAtomicBatch&&hCe(s.record)){let y=await gCe(e,u,s.record,l);return await Cb(e,s),{id:u,etag:y}}let{deactivated:d,etag:f,uncertainCause:p}=await hI(e,u,l,c),m=f,h=!1,g=!1;try{if(p!==void 0)throw p;let y=l;if(d){if(!f)throw _z(u,"deactivation");y=f}let b=`/workflows(${u})`,E;try{E=(0,Gt.ensureSuccess)(await e.patch(b,bI(s.record),{headers:{...mI,"If-Match":y}}),e.apiUrl(b))}catch(_){throw Sz(_)&&(m=null),_}let w=(0,Gt.readEtag)(E);if(m=w,s.status==="Active"){if(!w)throw _z(u,"definition write");try{w=await Nz(e,u,w)}catch(_){throw Sz(_)&&(m=null),g=(0,Gt.isConcurrencyLockRefusalError)(_),_}h=!0}return await Cb(e,s),{id:u,etag:w}}catch(y){if(d&&!h){let{outcome:b,attempted:E,acknowledged:w,echo:_}=await Tz(e,u,m,kz(y));if(g&&w)return h=!0,await Cb(e,s),{id:u,etag:_};if(b!=="restored")throw Oz(u,"to apply an edit, the edit failed",b,y,E)}throw y}},planPush(e,t,n){return(0,pI.planPushThrough)(Hm.bpfApi,e,t,n)},async delete(e,t){let n=(0,uo.normalizeGuid)(t,"id"),r=await(0,eCe.assertWorkflowKind)(e,n,Hr.WorkflowCategory.BusinessProcessFlow),{deactivated:i,etag:o}=await hI(e,n,null,void 0,r);try{await(0,zm.deleteWorkflowResending)(e,n,{bindingToken:i?o:r,kindName:"business process flow",deactivated:i,resendDeadlockVictim:!0})}catch(a){if(i&&!(0,zm.isWorkflowDeleteUnsettled)(a)){let{outcome:s,attempted:u}=await Tz(e,n,o,!1);if(s==="changed")throw uCe(n,a);if(s!=="restored")throw Oz(n,"so it could be deleted, the delete failed",s,a,u)}throw a}}}});var b9=C(Xd=>{"use strict";Object.defineProperty(Xd,"__esModule",{value:!0});Xd.bpfRegistration=Xd.BpfAdapter=void 0;var Nb=Ds(),yCe=Lz(),vI=Us(),Wl=ja(),Kz=Ga(),Mi=Vi(),Ai=ft(),Fo=Y(),bCe=100,wI='<?xml version="1.0" encoding="utf-16"?>',Mz=1033,Jz="mxswa:Workflow",vCe="mxswa:ActivityReference.Properties",wCe="mcwo:StepLabel",ECe="mcwb:Control",xz="mcwb:Control.ControlDisplayName",Yz="mcwb:Control.DataFieldName",Qz="DataFieldName",Fz="ControlDisplayName",Xz="Literal",Ib="x:Null",Uz="x:String",EI="x:Key",AI="DisplayName",Ob="Activities",ACe="StepLabels",Zz="StageId",e9="StageCategory",t9="NextStageId",n9="ProcessStepId",_b="IsProcessRequired",r9="EntityComposite",i9="StageComposite",o9="StepComposite";function Jm(e){return(0,Mi.isJsonObject)(e)?e:{}}function Na(e){if(!e)return[];let t=[],n=e.childNodes;for(let r=0;r<n.length;r+=1){let i=n[r];i.nodeType===1&&t.push(i)}return t}function zl(e,t){var n;return(n=Na(e).find(r=>r.tagName===t))!==null&&n!==void 0?n:null}function Ia(e){return zl(e,vCe)}function Kr(e,t){var n;return(n=Na(e).find(r=>r.getAttribute(EI)===t))!==null&&n!==void 0?n:null}function Qd(e,t){var n;return((n=e.getAttribute("AssemblyQualifiedName"))!==null&&n!==void 0?n:"").includes(t)}function _a(e){var t;return!e||!e.firstChild?"":(t=e.firstChild.nodeValue)!==null&&t!==void 0?t:""}function a9(e,t,n){e.firstChild?e.firstChild.nodeValue=n:e.appendChild(t.createTextNode(n))}function Ym(e){var t;let n=(t=e.getAttribute(AI))!==null&&t!==void 0?t:"",r=n.indexOf(": ");return r>=0?n.slice(r+2):n}function s9(e,t){var n;let r=(n=e.getAttribute(AI))!==null&&n!==void 0?n:"",i=r.indexOf(": ");e.setAttribute(AI,i>=0?r.slice(0,i+2)+t:t)}function u9(e,t){let n=Kr(e,ACe),r=zl(n,wCe);r&&r.setAttribute("Description",t)}function CCe(e){let t=Kr(e,e9);if(!t||t.tagName===Ib)return;let n=_a(t).trim();return n===""?void 0:Number(n)}function SCe(e){let t=Kr(e,t9);if(!t||t.tagName===Ib)return;let n=_a(t).trim();return n===""?void 0:n}function l9(e){let t=c9(e);if(!t)return;let n=f9(t,Qz,Yz);return n===""?void 0:n}function CI(e,t){let n=Na(e);for(;n.length>0;){let r=n.pop();if(r.tagName===t)return r;for(let i of Na(r))n.push(i)}return null}function c9(e){let t=Kr(Ia(e),Ob);return t?CI(t,ECe):null}function d9(e,t){let n=e.attributes;for(let r=0;r<n.length;r+=1)if(n[r].name===t)return!0;return!1}function f9(e,t,n){var r;return d9(e,t)?(r=e.getAttribute(t))!==null&&r!==void 0?r:"":OCe(e,n)}function qz(e,t,n,r){if(d9(e,t)){e.setAttribute(t,r);return}if(zl(e,n)){NCe(e,n,r);return}throw new Fo.InvalidArgumentError(`BPF step control exposes neither a '${t}' attribute nor a <${n}> wrapper to bind a column`)}function NCe(e,t,n){let r=zl(e,t),i=r?CI(r,Xz):null;if(!i)throw new Fo.InvalidArgumentError(`BPF step control's <${t}> wrapper holds no <Literal> to bind a column`);i.setAttribute("Value",n)}function p9(e){return Ym(e)}function Db(e){let t=zl(e,Jz),n=[];for(let r of Na(t).filter(i=>Qd(i,r9))){let i=Kr(Ia(r),Ob);for(let o of Na(i).filter(a=>Qd(a,i9)))n.push({el:o,entity:p9(r)})}return n}function SI(e){let t=Kr(Ia(e),Ob);return Na(t).filter(n=>Qd(n,o9))}function _Ce(e){let t=Ia(e),n=_a(Kr(t,_b)).trim().toLowerCase(),r=l9(e),i={id:_a(Kr(t,n9)),name:Ym(e)};return r!==void 0&&(i.fieldName=r),n==="true"&&(i.required=!0),i}function ICe(e,t){let n=Ia(e),r=CCe(n),i=SCe(n),o={id:_a(Kr(n,Zz)),name:Ym(e),entityLogicalName:t,steps:SI(e).map(_Ce)};return r!==void 0&&(o.category=r),i!==void 0&&(o.nextStageId=i),o}function TCe(e){return Db(e).map(({el:t,entity:n})=>ICe(t,n))}function Sa(e){return new Fo.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 OCe(e,t){var n;let r=zl(e,t),i=r?CI(r,Xz):null;return(n=i?.getAttribute("Value"))!==null&&n!==void 0?n:""}function NI(e,t){var n;let r=e.createElement(t.tagName),i=t.attributes;for(let a=0;a<i.length;a+=1)r.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?r.appendChild(NI(e,s)):s.nodeType===3&&r.appendChild(e.createTextNode((n=s.nodeValue)!==null&&n!==void 0?n:""))}return r}function m9(e){return Kr(Ia(e),Ob)}function DCe(e,t,n){var r;let i=t.entityLogicalName&&t.entityLogicalName.trim()!==""?t.entityLogicalName:n,o=!((r=t.steps[0])===null||r===void 0)&&r.id&&t.steps[0].id.trim()!==""?t.steps[0].id:(0,Ai.newId)(),{body:a}=Pb(_I(i,(0,Ai.newId)(),t.id,o));return NI(e,Db((0,Wl.parseXmlRoot)(a,"<Activity/>"))[0].el)}function PCe(e,t){let{body:n}=Pb(_I("account",(0,Ai.newId)(),(0,Ai.newId)(),t.id));return NI(e,SI(Db((0,Wl.parseXmlRoot)(n,"<Activity/>"))[0].el)[0])}function h9(e,t){for(;e.firstChild;)e.removeChild(e.firstChild);for(let n of t)e.appendChild(n)}function g9(e,t,n,r){let i=Kr(e,n);if(!i||!i.parentNode){if(r!==void 0&&r!=="")throw Sa(`setting '${n}' on a stage whose xaml does not expose that slot`);return}let o=i.parentNode;if(r===void 0||r===""){if(i.tagName!==Ib&&_a(i).trim()!==""){let s=t.createElement(Ib);s.setAttribute(EI,n),o.replaceChild(s,i)}return}if(i.tagName===Uz){_a(i).trim()!==r&&a9(i,t,r);return}let a=t.createElement(Uz);a.setAttribute(EI,n),a.appendChild(t.createTextNode(r)),o.replaceChild(a,i)}function RCe(e,t,n){g9(e,t,e9,n===void 0?void 0:String(n))}function kCe(e,t,n){g9(e,t,t9,n)}function y9(e,t,n){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r+=1)if(n(e[r])!==t[r])return!1;return!0}function Bz(e){return _a(Kr(Ia(e),Zz))}function Vz(e){return _a(Kr(Ia(e),n9))}function Gz(e,t,n){var r,i,o,a;let s=Ia(e);n.name!==Ym(e)&&(s9(e,n.name),u9(s,n.name));let u=_a(Kr(s,_b)).trim().toLowerCase()==="true";if(((r=n.required)!==null&&r!==void 0?r:!1)!==u){let l=Kr(s,_b);if(!l)throw Sa(`setting '${_b}' on a step whose xaml does not expose that slot`);a9(l,t,n.required?"True":"False")}if(((i=n.fieldName)!==null&&i!==void 0?i:"")!==((o=l9(e))!==null&&o!==void 0?o:"")){let l=c9(e);if(!l)throw new Fo.InvalidArgumentError("BPF step has no <mcwb:Control> element to bind a column to");let c=(a=n.fieldName)!==null&&a!==void 0?a:"";qz(l,Qz,Yz,c),c!==""&&f9(l,Fz,xz)===""&&qz(l,Fz,xz,c)}}function jz(e,t,n,r){var i;let o=Ia(e);if(!o)throw new Fo.InvalidArgumentError("BPF stage composite has no <\u2026ActivityReference.Properties>");if(n.name!==Ym(e)&&(s9(e,n.name),u9(o,n.name)),RCe(o,t,n.category),kCe(o,t,r),n.relationshipName&&n.relationshipName.trim()!=="")throw Sa("a stage relationship / table change (multi-table authoring)");if(n.actions&&n.actions.length>0||n.branch)throw Sa("stage actions or conditional branching");let a=m9(e);if(!a)throw new Fo.InvalidArgumentError("BPF stage has no [Activities] collection");let s=(i=n.steps)!==null&&i!==void 0?i:[];if(s.length===0)throw new Fo.InvalidArgumentError(`BPF stage '${n.name}' must have at least one step`);let u=SI(e);if(y9(u,s.map(d=>d.id),Vz)){u.forEach((d,f)=>Gz(d,t,s[f]));return}let l=new Map(u.map(d=>[Vz(d),d]));if(Na(a).some(d=>!Qd(d,o9)))throw Sa("adding, removing or reordering steps on a stage that also contains branching or actions");let c=s.map(d=>{var f;return(f=l.get(d.id))!==null&&f!==void 0?f:PCe(t,d)});h9(a,c),c.forEach((d,f)=>Gz(d,t,s[f]))}function $Ce(e,t,n){let r=zl(e,Jz);if(!r)throw new Fo.InvalidArgumentError("BPF xaml has no <mxswa:Workflow> root activity");if(n.globalActions&&n.globalActions.length>0)throw Sa("global (process-completed/abandoned) actions");if(!n.stages||n.stages.length===0)throw new Fo.InvalidArgumentError("a BPF must have at least one stage");let i=Db(e),o=i.map(f=>f.el);if(y9(o,n.stages.map(f=>f.id),Bz)){i.forEach(({el:f,entity:p},m)=>{let h=n.stages[m];if(h.entityLogicalName&&h.entityLogicalName.trim()!==""&&h.entityLogicalName!==p)throw Sa(`changing a stage's table ('${h.entityLogicalName}' vs the process's '${p}')`);jz(f,t,h,h.nextStageId)});return}let a=Na(r).filter(f=>Qd(f,r9));if(a.length!==1)throw Sa("adding, removing or reordering stages on a multi-table process");let s=a[0],u=p9(s),l=m9(s);if(!l)throw new Fo.InvalidArgumentError("BPF primary entity composite has no [Activities] collection");if(Na(l).some(f=>!Qd(f,i9)))throw Sa("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 n.stages)if(f.entityLogicalName&&f.entityLogicalName.trim()!==""&&f.entityLogicalName!==u)throw Sa(`a stage on a different table ('${f.entityLogicalName}') than the process primary ('${u}')`);let c=new Map(o.map(f=>[Bz(f),f])),d=n.stages.map(f=>{var p;return(p=c.get(f.id))!==null&&p!==void 0?p:DCe(t,f,u)});h9(l,d),d.forEach((f,p)=>{let m=p<d.length-1?n.stages[p+1].id:void 0;jz(f,t,n.stages[p],m)})}function Pb(e){let t=e.match(/^<\?xml[^>]*\?>\s*/),n=t?t[0]:"";return{prolog:n,body:e.slice(n.length)}}function LCe(e){var t,n,r,i,o,a;(0,Kz.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,vI.mergeAttrs)(s.a,[]),c:(0,vI.spliceChildren)(s.c,[])};return{root:(0,vI.rebuildRaw)(p,(0,Wl.domEngine)(f),null),prolog:(r=(n=e.bag)===null||n===void 0?void 0:n.xamlProlog)!==null&&r!==void 0?r:wI,eol:(o=(i=e.bag)===null||i===void 0?void 0:i.xamlEol)!==null&&o!==void 0?o:"lf"}}let u=e.stages[0],l=(a=u?.steps)===null||a===void 0?void 0:a[0],c=_I(e.entityLogicalName,(0,Ai.newId)(),u?.id&&u.id.trim()!==""?u.id:(0,Ai.newId)(),l?.id&&l.id.trim()!==""?l.id:(0,Ai.newId)()),{body:d}=Pb(c);return{root:(0,Wl.parseXmlRoot)(d,"<Activity/>"),prolog:wI,eol:"lf"}}function MCe(e){let{root:t,prolog:n,eol:r}=LCe(e);$Ce(t,t.ownerDocument,e);let i=(0,Wl.serializeNode)(t);return r==="crlf"&&(i=i.replace(/\n/g,`\r+`)),n+i}function xCe(e){return e.uniqueName&&e.uniqueName.trim()!==""?e.uniqueName:`new_${(e.name||"businessprocessflow").toLowerCase().replace(/[^a-z0-9]/g,"")||"businessprocessflow"}`}var Tb=class{toArtifact(t){return t}fromArtifact(t){return t}fromApiResponse(t){var n,r;(0,Kz.installDomShim)();let i=t,o=typeof i.xaml=="string"?i.xaml:"",a={id:i.workflowid?String(i.workflowid):null,name:String((n=i.name)!==null&&n!==void 0?n:""),entityLogicalName:String((r=i.primaryentity)!==null&&r!==void 0?r:""),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:u}=Pb(o),l=(0,Wl.parseXmlRoot)(u,"<Activity/>");a.stages=TCe(l),a.bag={xaml:(0,Wl.projectElementBag)(l),xamlProlog:s,xamlEol:/\r\n/.test(o)?"crlf":"lf"}}return a}toApiPayload(t){var n;let r={workflowid:t.id&&t.id.trim()!==""?t.id:(0,Ai.newId)(),name:t.name,uniquename:xCe(t),primaryentity:t.entityLogicalName,xaml:MCe(t),category:Nb.WorkflowCategory.BusinessProcessFlow,type:Nb.WorkflowTypeCode.Definition,businessprocesstype:Nb.BusinessProcessType.BusinessFlow,scope:Nb.WorkflowScope.Organization,processorder:(n=t.order)!==null&&n!==void 0?n:bCe};t.description!==void 0&&(r.description=t.description);let i={record:r,status:t.status};if(t.securityRoles&&t.securityRoles.length>0){if(t.status!=="Active")throw new Fo.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 n,r,i;let o=t.stages&&t.stages.length>0?t.stages.map(zz):[zz({id:(0,Ai.newId)(),name:"New Stage",steps:[]})],a={id:t.id&&t.id.trim()!==""?t.id:(0,Ai.newId)(),name:(n=t.name)!==null&&n!==void 0?n:"New business process flow",entityLogicalName:(r=t.entityLogicalName)!==null&&r!==void 0?r:"",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 n=Jm(t);(typeof n.id!="string"||n.id.trim()==="")&&(n.id=(0,Ai.newId)());for(let r of["stages","steps","actions","globalActions"]){let i=n[r];Array.isArray(i)&&i.forEach(o=>this.assignMissingIds(o))}return n}validate(t){let n=[],r=t.stages;if(r!==void 0&&!Array.isArray(r))return n.push((0,Mi.issue)("/stages","stages-must-be-array",`stages must be an array, got ${typeof r}`)),n;let i=Array.isArray(r)?r:[];i.length>30&&n.push((0,Mi.issue)("/stages","too-many-stages",`a BPF allows at most 30 stages, got ${i.length}`));let o=new Set,a=new Map;i.forEach((u,l)=>{let c=`/stages/${l}`,d=Jm(u),f=typeof d.id=="string"?d.id.trim():"";f===""?n.push((0,Mi.issue)(`${c}/id`,"stage-id-required","a stage needs an id")):a.has(f.toLowerCase())?n.push((0,Mi.issue)(`${c}/id`,"stage-id-duplicate",`two stages share the id '${d.id}' (also at /stages/${a.get(f.toLowerCase())})`)):a.set(f.toLowerCase(),l),typeof d.entityLogicalName=="string"&&d.entityLogicalName!==""&&o.add(d.entityLogicalName);let p=Array.isArray(d.steps)?d.steps:[];p.length===0&&n.push((0,Mi.issue)(`${c}/steps`,"stage-needs-step","a BPF stage must have at least one step")),p.length>30&&n.push((0,Mi.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 y=`${c}/steps/${g}`,b=typeof Jm(h).id=="string"?h.id.trim():"";b===""?n.push((0,Mi.issue)(`${y}/id`,"step-id-required","a step needs an id")):m.has(b.toLowerCase())?n.push((0,Mi.issue)(`${y}/id`,"step-id-duplicate",`two steps in this stage share the id '${h.id}'`)):m.set(b.toLowerCase(),g)}),d.branch&&!Wz(i,d.branch.nextStageId)&&n.push((0,Mi.issue)(`${c}/branch/nextStageId`,"branch-target-unknown",`branch nextStageId '${d.branch.nextStageId}' does not match any stage id`)),typeof d.nextStageId=="string"&&d.nextStageId!==""&&!Wz(i,d.nextStageId)&&n.push((0,Mi.issue)(`${c}/nextStageId`,"next-stage-unknown",`nextStageId '${d.nextStageId}' does not match any stage id`))}),o.size>5&&n.push((0,Mi.issue)("/stages","too-many-tables",`a BPF spans at most 5 tables, got ${o.size}`));let s=FCe(i);return s>=0&&n.push((0,Mi.issue)(`/stages/${s}/nextStageId`,"next-stage-cycle","the stage nextStageId links form a cycle; the flow must be acyclic")),n}};Xd.BpfAdapter=Tb;function FCe(e){let t=new Map(e.map(n=>[Jm(n).id,n]));for(let n=0;n<e.length;n+=1){let r=new Set,i=e[n];for(;i&&typeof i.nextStageId=="string"&&i.nextStageId!=="";){if(r.has(i.id))return n;r.add(i.id),i=t.get(i.nextStageId)}}return-1}function Wz(e,t){return e.some(n=>Jm(n).id===t)}function zz(e){var t,n;let r=e.steps&&e.steps.length>0?e.steps.map(Hz):[Hz({id:(0,Ai.newId)(),name:"New Step"})],i={id:e.id&&e.id.trim()!==""?e.id:(0,Ai.newId)(),name:(t=e.name)!==null&&t!==void 0?t:"New Stage",entityLogicalName:(n=e.entityLogicalName)!==null&&n!==void 0?n:"",steps:r};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 Hz(e){var t;let n={id:e.id&&e.id.trim()!==""?e.id:(0,Ai.newId)(),name:(t=e.name)!==null&&t!==void 0?t:"New Step"};return e.fieldName!==void 0&&(n.fieldName=e.fieldName),e.required!==void 0&&(n.required=e.required),n}function _I(e,t,n,r){return`${wI}<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="${r}" LanguageCode="${Mz}" /></sco:Collection><x:String x:Key="ProcessStepId">${r}</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="${n}" LanguageCode="${Mz}" /></sco:Collection><x:String x:Key="StageId">${n}</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 UCe(){return{adapter:new Tb,api:yCe.bpfApi,languageSensitive:!0}}Xd.bpfRegistration=UCe});var E9=C(Zd=>{"use strict";Object.defineProperty(Zd,"__esModule",{value:!0});Zd.environmentVariableRegistration=Zd.EnvironmentVariableAdapter=void 0;var Qm=cp(),OI=Jc(),TI=Y(),II=Eu(),qCe=Rs(),v9=ft(),Xm=ae(),BCe=new Map(Object.entries(OI.ENVIRONMENT_VARIABLE_TYPE_CODES).map(([e,t])=>[t,e]));function w9(e){var t,n,r,i,o;let a=new Map((n=(t=e.bag)===null||t===void 0?void 0:t.a)!==null&&n!==void 0?n:[]);return{displayname:e.name,description:e.description,defaultvalue:e.defaultValue,isrequired:e.isRequired,valueschema:(r=e.valueSchema)!==null&&r!==void 0?r:null,apiid:(i=e.connectorId)!==null&&i!==void 0?i:null,parameterkey:(o=e.parameterKey)!==null&&o!==void 0?o:null,"[email protected]":e.parentId?`/environmentvariabledefinitions(${(0,Xm.normalizeGuid)(e.parentId,"parentId")})`:null,...Object.fromEntries(Qm.ENVIRONMENT_VARIABLE_BAG_COLUMNS.map(s=>{var u;return[s,(u=a.get(s))!==null&&u!==void 0?u:null]}))}}var VCe=["displayname","description","defaultvalue","isrequired","valueschema"],Rb=class{toArtifact(t){return t}fromArtifact(t){return t}fromApiResponse(t){var n,r,i,o,a,s,u,l,c,d,f;let p=t??{},m=BCe.get(Number(p.type));if(m===void 0)throw new TI.InvalidArgumentError(`Unknown environment variable type ${JSON.stringify(p.type)}`);let h=(n=p.environmentvariabledefinition_environmentvariablevalue)===null||n===void 0?void 0:n[0],g=String((r=p.schemaname)!==null&&r!==void 0?r:"");return{id:(0,Xm.normalizeGuid)(String((i=p.environmentvariabledefinitionid)!==null&&i!==void 0?i:""),"environmentvariabledefinitionid"),schemaName:g,name:(o=p.displayname)!==null&&o!==void 0?o:g,description:(a=p.description)!==null&&a!==void 0?a:null,type:m,defaultValue:(s=p.defaultvalue)!==null&&s!==void 0?s:null,currentValue:h?{value:(u=h.value)!==null&&u!==void 0?u:null,id:(0,Xm.normalizeGuid)(String((l=h.environmentvariablevalueid)!==null&&l!==void 0?l:""),"environmentvariablevalueid")}:null,isRequired:p.isrequired===!0,valueSchema:(c=p.valueschema)!==null&&c!==void 0?c:null,connectorId:(d=p.apiid)!==null&&d!==void 0?d:null,parameterKey:(f=p.parameterkey)!==null&&f!==void 0?f:null,parentId:p._parentdefinitionid_value?(0,Xm.normalizeGuid)(p._parentdefinitionid_value,"_parentdefinitionid_value"):null,bag:{a:Qm.ENVIRONMENT_VARIABLE_BAG_COLUMNS.filter(y=>p[y]!==void 0&&p[y]!==null).map(y=>[y,p[y]])}}}toApiPayload(t,n){var r,i;let o=[...(0,Qm.environmentVariableShapeIssues)(t),...(0,Qm.environmentVariablePushIssues)(t,n)];if(o.length>0)throw new TI.ValidationError("environmentVariable",t.id,o);let a=GCe(t.currentValue,(r=n?.currentValue)!==null&&r!==void 0?r:null),s=!((i=n?.currentValue)===null||i===void 0)&&i.id?(0,Xm.normalizeGuid)(n.currentValue.id,"currentValue.id"):null,u=w9(t);if(!n){let f={schemaname:t.schemaName,type:OI.ENVIRONMENT_VARIABLE_TYPE_CODES[t.type]};for(let[p,m]of Object.entries(u))(m!==null||p==="isrequired")&&(f[p]=m);return{schemaName:t.schemaName,definition:f,heldRowId:s,value:a}}let l=w9(n),c=Object.keys(u).filter(f=>!(0,qCe.deepEqual)(u[f],l[f])),d;return c.length>0?d=Object.fromEntries(c.map(f=>[f,u[f]])):a.op==="none"&&(d=Object.fromEntries(VCe.map(f=>[f,u[f]]))),{schemaName:t.schemaName,...d?{definition:d}:{},heldRowId:s,value:a}}createDefault(t){var n,r,i,o,a,s,u,l,c,d,f,p;return{id:(n=t.id)!==null&&n!==void 0?n:(0,v9.newId)(),schemaName:(r=t.schemaName)!==null&&r!==void 0?r:"",name:(o=(i=t.name)!==null&&i!==void 0?i:t.schemaName)!==null&&o!==void 0?o:"",description:(a=t.description)!==null&&a!==void 0?a:null,type:(s=t.type)!==null&&s!==void 0?s:"string",defaultValue:(u=t.defaultValue)!==null&&u!==void 0?u:null,currentValue:t.currentValue?(0,II.cloneJson)(t.currentValue):null,isRequired:(l=t.isRequired)!==null&&l!==void 0?l:!1,valueSchema:(c=t.valueSchema)!==null&&c!==void 0?c:null,connectorId:(d=t.connectorId)!==null&&d!==void 0?d:null,parameterKey:(f=t.parameterKey)!==null&&f!==void 0?f:null,parentId:(p=t.parentId)!==null&&p!==void 0?p:null,bag:t.bag?(0,II.cloneJson)(t.bag):{a:[]}}}assignMissingIds(t){return t}validate(t,n){return(0,Qm.environmentVariableMutationIssues)(t,n)}normalize(t,n){var r,i;let o=t.currentValue;return!o||o.id!==void 0&&o.id!==null?t:{...t,currentValue:{...o,id:(i=(r=n?.currentValue)===null||r===void 0?void 0:r.id)!==null&&i!==void 0?i:(0,v9.newId)()}}}committed(t,n,r){let i=n.value;if(i.op==="none")return{artifact:t,baseline:t};if(r.intentPending){let o=i.op==="create"?null:(0,II.cloneJson)(i.baseline);return{artifact:t,baseline:{...t,currentValue:o}}}if(i.op==="delete"){let o={...t,currentValue:null};return{artifact:o,baseline:o}}return{artifact:t,baseline:t}}};Zd.EnvironmentVariableAdapter=Rb;function GCe(e,t){if(e===null)return t?{op:"delete",id:t.id,baseline:t}:{op:"none"};if(t===null){if(!e.id)throw new TI.InvalidArgumentError("environment variable value row has no id: normalize must run before the payload");return{op:"create",id:e.id,value:e.value}}return e.value===t.value?{op:"none"}:{op:"update",id:t.id,value:e.value,baseline:t}}function jCe(){return{adapter:new Rb,api:OI.environmentVariableApi,guardedDelete:!0}}Zd.environmentVariableRegistration=jCe});var DI=C(Pu=>{"use strict";Object.defineProperty(Pu,"__esModule",{value:!0});Pu.findConnectionReference=Pu.resolveConnectionReferences=Pu.connectionReferenceApi=void 0;var kb=Ke(),WCe=Jc(),zCe=il(),Ou=Y(),Tr=pe(),Du=ae(),HCe="connectionreferenceid,connectionreferencelogicalname,connectionreferencedisplayname,description,connectorid,connectionid,_customconnectorid_value,connectionparametersconfig,connectionparametersetconfig,promptingbehavior",ef="connectionreferences";async function KCe(e,t,n){var r,i,o;let a=(0,Du.normalizeGuid)(t,"id"),s=(r=n?.token)!==null&&r!==void 0?r:null;if(!(0,Tr.isVersionToken)(s))throw new Ou.SdkError(Tr.DELETE_NO_ETAG_CODE,`Refusing to delete connectionReference '${a}': no usable concurrency token is held for it, so the delete could not be made conditional and could remove what another writer changed. Fetch it first (fetchArtifact).`);let u=`/connectioninstances${(0,Du.odataQuery)([["$select","connectioninstanceid"],["$filter",`_connectionreferenceid_value eq ${a}`],["$top","1"]])}`,l=e.apiUrl(u),c=(0,Tr.ensureSuccess)(await e.get(u),l).body,d=c?.value;if(!Array.isArray(d)||!(0,kb.boundedPageComplete)(c,d.length))throw new Ou.ConnectionError(l,200,"the reference's connection instances could not be read, so whether the delete would cascade is unknown");if(d.length>0)throw new Ou.ArtifactInUseError("connectionReference",a,`Refusing to delete connectionReference '${a}': connection instances use it, and the platform would delete them with it. Nothing was deleted.`,d.map(h=>{var g;return{table:"connectioninstance",id:String((g=h.connectioninstanceid)!==null&&g!==void 0?g:"").toLowerCase()}}));let f=`/${ef}(${a})`,p=await e.delete(f,{headers:{"If-Match":s}});if(p.status===412)throw new Ou.VersionConflictError("connectionReference",a,s,null,"Another writer changed it since it was fetched; nothing was deleted.");let m=(o=(i=p.body)===null||i===void 0?void 0:i.error)===null||o===void 0?void 0:o.code;if(typeof m=="string"&&m.toLowerCase()==="0x8004f01f"){let h;try{h=await(0,zCe.resolveConnectionReferenceComponentType)(e)}catch{h=void 0}throw new Ou.ArtifactInUseError("connectionReference",a,`Refusing to delete connectionReference '${a}': another component (a flow, an app) depends on it; nothing was deleted. Remove the dependency first.`,await(0,WCe.readDeleteDependents)(e,a,h))}(0,Tr.ensureSuccess)(p,e.apiUrl(f))}Pu.connectionReferenceApi={async get(e,t){let n=(0,Du.normalizeGuid)(t,"id"),r=`/${ef}(${n})${(0,Du.odataQuery)([["$select",HCe]])}`,i=(0,Tr.ensureSuccess)(await e.get(r),e.apiUrl(r));return{raw:i.body,etag:(0,Tr.readEtag)(i)}},async list(e){let t=`/${ef}${(0,Du.odataQuery)([["$select","connectionreferenceid,connectionreferencelogicalname,connectionreferencedisplayname"]])}`;return(await(0,kb.collectPages)(e,t,"listArtifacts('connectionReference')")).map(r=>{var i,o,a;return{type:"connectionReference",id:String((i=r.connectionreferenceid)!==null&&i!==void 0?i:""),name:String((a=(o=r.connectionreferencedisplayname)!==null&&o!==void 0?o:r.connectionreferencelogicalname)!==null&&a!==void 0?a:""),isDirty:!1}})},async create(e,t,n){let r=t,i=(0,Tr.echoWrite)("connectionreferenceid"),o=`/${ef}${i.query}`,a=(0,Tr.ensureSuccess)(await e.post(o,(0,Tr.withClientMintedId)(r.columns,"connectionreferenceid",n),i.options),e.apiUrl(o));return{id:(0,Tr.resolveCreatedId)(a,"connectionreferenceid","connection reference",n),etag:(0,Tr.readEtag)(a)}},async update(e,t,n,r){let i=n,o=(0,Du.normalizeGuid)(t,"id"),a=(0,Tr.echoWrite)("connectionreferenceid",{"If-Match":(0,Tr.requireEtag)(r,"connectionReference",o)}),s=`/${ef}(${o})${a.query}`,u=(0,Tr.ensureSuccess)(await e.patch(s,i.columns,a.options),e.apiUrl(s));return{id:o,etag:(0,Tr.readEtag)(u)}},delete(e,t,n){return KCe(e,t,n)}};async function A9(e,t,n){let r=`/${ef}${(0,Du.odataQuery)([["$select","connectionreferenceid,connectionreferencelogicalname"],["$filter",`connectionreferencelogicalname eq '${(0,Du.odataLiteral)(t)}'`],...n!==void 0?[["$top",String(n)]]:[]])}`,i=e.apiUrl(r),o;if(n===void 0)o=await(0,kb.collectPages)(e,r,"resolveArtifact('connectionReference')");else{let a=(0,Tr.ensureSuccess)(await e.get(r),i).body;if(o=a?.value,Array.isArray(o)&&!(0,kb.boundedPageComplete)(a,o.length,n))throw new Ou.ConnectionError(i,200,"the list of connection references is incomplete (the answer says more rows exist), so it proves neither absence nor a single match")}if(!Array.isArray(o))throw new Ou.ConnectionError(i,200,"the response could not be read as a list of connection references");return o.map(a=>({id:String(a.connectionreferenceid),name:String(a.connectionreferencelogicalname)}))}Pu.resolveConnectionReferences=A9;async function JCe(e,t){let n=await A9(e,t,2);if(n.length>1)throw new Ou.AmbiguousArtifactError("connectionReference",t,n.length);return n.length===1?n[0].id:null}Pu.findConnectionReference=JCe});var N9=C(Uo=>{"use strict";Object.defineProperty(Uo,"__esModule",{value:!0});Uo.connectionReferenceRegistration=Uo.ConnectionReferenceAdapter=Uo.CONNECTION_REFERENCE_BAG_COLUMNS=void 0;var Zm=cp(),YCe=DI(),QCe=Y(),XCe=Eu(),ZCe=Rs(),eSe=ft(),PI=ae();Uo.CONNECTION_REFERENCE_BAG_COLUMNS=["connectionparametersconfig","connectionparametersetconfig","promptingbehavior"];var tSe=["connectionreferencedisplayname","description","connectorid","connectionid"];function tf(e,t,n){return{pointer:e,rule:t,message:n}}function C9(e){let t=e,n=[];return(0,Zm.isGuidText)(t.id)||n.push(tf("/id","guid","must be a GUID")),(typeof t.logicalName!="string"||t.logicalName.trim()==="")&&n.push(tf("/logicalName","required","must be a non-empty string (with a publisher prefix)")),typeof t.name!="string"&&n.push(tf("/name","type","must be a string")),n.push(...(0,Zm.requiredStringOrNull)(t.description,"/description")),(typeof t.connectorId!="string"||t.connectorId.trim()==="")&&n.push(tf("/connectorId","required","must be a non-empty string, e.g. /providers/Microsoft.PowerApps/apis/shared_sharepointonline")),n.push(...(0,Zm.requiredStringOrNull)(t.connectionId,"/connectionId","a connection id (a string)")),t.customConnectorId!==null&&t.customConnectorId!==void 0&&!(0,Zm.isGuidText)(t.customConnectorId)&&n.push(tf("/customConnectorId","guid","must be a GUID or null")),n.push(...(0,Zm.rowBagIssues)(t.bag,Uo.CONNECTION_REFERENCE_BAG_COLUMNS)),n}function S9(e){var t,n;let r=new Map((n=(t=e.bag)===null||t===void 0?void 0:t.a)!==null&&n!==void 0?n:[]);return{connectionreferencedisplayname:e.name,description:e.description,connectorid:e.connectorId,connectionid:e.connectionId,"[email protected]":e.customConnectorId?`/connectors(${(0,PI.normalizeGuid)(e.customConnectorId,"customConnectorId")})`:null,...Object.fromEntries(Uo.CONNECTION_REFERENCE_BAG_COLUMNS.map(i=>{var o;return[i,(o=r.get(i))!==null&&o!==void 0?o:null]}))}}var $b=class{toArtifact(t){return t}fromArtifact(t){return t}fromApiResponse(t){var n,r,i,o,a,s;let u=t??{},l=String((n=u.connectionreferencelogicalname)!==null&&n!==void 0?n:"");return{id:(0,PI.normalizeGuid)(String((r=u.connectionreferenceid)!==null&&r!==void 0?r:""),"connectionreferenceid"),logicalName:l,name:(i=u.connectionreferencedisplayname)!==null&&i!==void 0?i:l,description:(o=u.description)!==null&&o!==void 0?o:null,connectorId:String((a=u.connectorid)!==null&&a!==void 0?a:""),connectionId:(s=u.connectionid)!==null&&s!==void 0?s:null,customConnectorId:u._customconnectorid_value?(0,PI.normalizeGuid)(u._customconnectorid_value,"_customconnectorid_value"):null,bag:{a:Uo.CONNECTION_REFERENCE_BAG_COLUMNS.filter(c=>u[c]!==void 0&&u[c]!==null).map(c=>[c,u[c]])}}}toApiPayload(t,n){let r=C9(t);if(n&&t.logicalName!==n.logicalName&&r.push(tf("/logicalName","immutable-after-create","logicalName is fixed once the reference exists (the platform ignores a change)")),r.length>0)throw new QCe.ValidationError("connectionReference",t.id,r);let i=S9(t);if(!n){let u={connectionreferencelogicalname:t.logicalName};for(let[l,c]of Object.entries(i))c!==null&&(u[l]=c);return{columns:u}}let o=S9(n),a=Object.keys(i).filter(u=>!(0,ZCe.deepEqual)(i[u],o[u])),s=a.length>0?a:tSe;return{columns:Object.fromEntries(s.map(u=>[u,i[u]]))}}createDefault(t){var n,r,i,o,a,s,u,l;return{id:(n=t.id)!==null&&n!==void 0?n:(0,eSe.newId)(),logicalName:(r=t.logicalName)!==null&&r!==void 0?r:"",name:(o=(i=t.name)!==null&&i!==void 0?i:t.logicalName)!==null&&o!==void 0?o:"",description:(a=t.description)!==null&&a!==void 0?a:null,connectorId:(s=t.connectorId)!==null&&s!==void 0?s:"",connectionId:(u=t.connectionId)!==null&&u!==void 0?u:null,customConnectorId:(l=t.customConnectorId)!==null&&l!==void 0?l:null,bag:t.bag?(0,XCe.cloneJson)(t.bag):{a:[]}}}assignMissingIds(t){return t}validate(t){return C9(t)}};Uo.ConnectionReferenceAdapter=$b;function nSe(){return{adapter:new $b,api:YCe.connectionReferenceApi,guardedDelete:!0}}Uo.connectionReferenceRegistration=nSe});var T9=C(Ta=>{"use strict";Object.defineProperty(Ta,"__esModule",{value:!0});Ta.fieldSecurityProfilePushIssues=Ta.fieldSecurityProfileShapeIssues=Ta.permissionIdentity=Ta.permissionKey=void 0;var RI=cp(),rSe=o0(),iSe=/^[a-z_][a-z0-9_]*$/,_9=["none","oneRecord","allRecords"],oSe=["read","create","update"];function Ci(e,t,n){return{pointer:e,rule:t,message:n}}function nf(e){return`${e.table}\0${e.column}`}Ta.permissionKey=nf;function eh(e){var t;return(t=(0,rSe.canonicalGuid)(e))!==null&&t!==void 0?t:String(e??"").toLowerCase()}Ta.permissionIdentity=eh;function I9(e){let t=e,n=[];if((0,RI.isGuidText)(t.id)||n.push(Ci("/id","guid","must be a GUID")),typeof t.name!="string"&&n.push(Ci("/name","type","must be a string")),n.push(...(0,RI.requiredStringOrNull)(t.description,"/description")),!Array.isArray(t.permissions))return n.push(Ci("/permissions","type","must be an array of permissions")),n;let r=new Map;return t.permissions.forEach((i,o)=>{let a=`/permissions/${o}`;if(!i||typeof i!="object"||Array.isArray(i)){n.push(Ci(a,"type","must be a permission object"));return}let s=i;for(let u of["table","column"])s[u]!==void 0&&(typeof s[u]!="string"||!iSe.test(s[u]))&&n.push(Ci(`${a}/${u}`,"logical-name",`must be a lower-case logical name, e.g. contoso_${u==="table"?"employee":"salary"}`));for(let u of oSe)s[u]!==void 0&&typeof s[u]!="boolean"&&n.push(Ci(`${a}/${u}`,"type","must be true or false"));if(s.readUnmasked!==void 0&&!_9.includes(s.readUnmasked)&&n.push(Ci(`${a}/readUnmasked`,"type",`must be one of ${_9.join(", ")}`)),s.id!==void 0&&!(0,RI.isGuidText)(s.id)&&n.push(Ci(`${a}/id`,"guid","must be a GUID")),typeof s.table=="string"&&typeof s.column=="string"){let u=nf(s);r.has(u)?n.push(Ci(a,"duplicate-permission",`${s.table}.${s.column} already has a permission at /permissions/${r.get(u)}; a profile holds one per column`)):r.set(u,o)}}),n}Ta.fieldSecurityProfileShapeIssues=I9;function aSe(e,t){var n;let r=I9(e);if((typeof e.name!="string"||e.name.trim()==="")&&r.push(Ci("/name","name-required","a field security profile needs a non-empty name")),!Array.isArray(e.permissions))return r;let i=((n=t?.permissions)!==null&&n!==void 0?n:[]).filter(s=>s&&typeof s.id=="string"),o=new Map(i.map(s=>[eh(s.id),s])),a=new Map(i.map(s=>[nf(s),s]));return e.permissions.forEach((s,u)=>{var l,c;let d=`/permissions/${u}`;if(!s||typeof s!="object")return;if(typeof s.table!="string"||typeof s.column!="string"){r.push(Ci(d,"permission-key-required","every permission needs its table and column"));return}let f=typeof s.id=="string"?o.get(eh(s.id)):void 0;f&&nf(f)!==nf(s)&&r.push(Ci(d,"permission-key-immutable",`this permission is ${f.table}.${f.column} on the server; its table and column cannot change (the platform would ignore it). Remove it and add a new permission instead.`));let p=a.get(nf(s));p&&typeof s.id=="string"&&eh(s.id)!==eh(p.id)&&r.push(Ci(`${d}/id`,"permission-id-conflict",`${s.table}.${s.column} is the server row '${p.id}'; remove the id (the SDK manages it) instead of setting another`));let m=(l=p?.readUnmasked)!==null&&l!==void 0?l:"none";((c=s.readUnmasked)!==null&&c!==void 0?c:"none")!==m&&r.push(Ci(`${d}/readUnmasked`,"read-unmasked-not-authored","the read-unmasked level is carried as fetched, not authored: it needs a masking rule on the column, which this SDK does not manage. Leave it as fetched (absent for a new permission)."))}),r}Ta.fieldSecurityProfilePushIssues=aSe});var D9=C(rf=>{"use strict";Object.defineProperty(rf,"__esModule",{value:!0});rf.fieldSecurityProfileRegistration=rf.FieldSecurityProfileAdapter=void 0;var qo=T9(),sSe=s0(),$I=o0(),uSe=Y(),kI=ft(),O9=ae(),lo=e=>e===!0?$I.ALLOWED:$I.NOT_ALLOWED;function lSe(e,t){return e.table<t.table?-1:e.table>t.table?1:e.column<t.column?-1:e.column>t.column?1:0}var Lb=class{toArtifact(t){return t}fromArtifact(t){return t}fromApiResponse(t){var n;let r=t??{},i=(0,O9.normalizeGuid)(String((n=r.fieldsecurityprofileid)!==null&&n!==void 0?n:""),"fieldsecurityprofileid"),a=(Array.isArray(r.lk_fieldpermission_fieldsecurityprofileid)?r.lk_fieldpermission_fieldsecurityprofileid:[]).map(s=>{var u,l,c;return(0,$I.toFieldPermission)({id:(0,O9.normalizeGuid)(String((u=s.fieldpermissionid)!==null&&u!==void 0?u:""),"fieldpermissionid"),token:"",table:String((l=s.entityname)!==null&&l!==void 0?l:""),column:String((c=s.attributelogicalname)!==null&&c!==void 0?c:""),canread:s.canread,cancreate:s.cancreate,canupdate:s.canupdate,canreadunmasked:s.canreadunmasked},{profileId:i})}).sort(lSe);return{id:i,name:typeof r.name=="string"?r.name:"",description:typeof r.description=="string"?r.description:null,permissions:a}}toApiPayload(t,n){let r=(0,qo.fieldSecurityProfilePushIssues)(t,n);if(r.length>0)throw new uSe.ValidationError("fieldSecurityProfile",t.id,r);let i=l=>{var c;return{id:(0,qo.permissionIdentity)((c=l.id)!==null&&c!==void 0?c:(0,kI.newId)()),table:l.table,column:l.column,canread:lo(l.read),cancreate:lo(l.create),canupdate:lo(l.update)}};if(!n)return{profile:{name:t.name,description:t.description},creates:t.permissions.map(i),updates:[],deletes:[]};let o={};t.name!==n.name&&(o.name=t.name),t.description!==n.description&&(o.description=t.description);let a=new Map(n.permissions.map(l=>[(0,qo.permissionKey)(l),l])),s=new Set(t.permissions.map(l=>(0,qo.permissionKey)(l))),u={profile:o,creates:[],updates:[],deletes:[]};for(let l of t.permissions){let c=a.get((0,qo.permissionKey)(l));if(!c){u.creates.push(i(l));continue}let d={};lo(l.read)!==lo(c.read)&&(d.canread=lo(l.read)),lo(l.create)!==lo(c.create)&&(d.cancreate=lo(l.create)),lo(l.update)!==lo(c.update)&&(d.canupdate=lo(l.update)),Object.keys(d).length>0&&u.updates.push({id:(0,qo.permissionIdentity)(c.id),table:l.table,column:l.column,set:d})}for(let l of n.permissions)s.has((0,qo.permissionKey)(l))||u.deletes.push({id:(0,qo.permissionIdentity)(l.id),table:l.table,column:l.column});return u}createDefault(t){var n,r,i,o;return{id:(n=t.id)!==null&&n!==void 0?n:(0,kI.newId)(),name:(r=t.name)!==null&&r!==void 0?r:"",description:(i=t.description)!==null&&i!==void 0?i:null,permissions:((o=t.permissions)!==null&&o!==void 0?o:[]).map(a=>{var s,u,l;return{...a,read:(s=a.read)!==null&&s!==void 0?s:!1,create:(u=a.create)!==null&&u!==void 0?u:!1,update:(l=a.update)!==null&&l!==void 0?l:!1}})}}assignMissingIds(t){return t}validate(t){return(0,qo.fieldSecurityProfileShapeIssues)(t)}normalize(t,n){var r;if(!Array.isArray(t.permissions))return t;let i=new Map(((r=n?.permissions)!==null&&r!==void 0?r:[]).filter(s=>s&&typeof s.id=="string").map(s=>[(0,qo.permissionKey)(s),s.id])),o=!1,a=t.permissions.map(s=>{var u;return!s||typeof s!="object"||typeof s.table!="string"||typeof s.column!="string"||s.id!==void 0&&s.id!==null&&s.id!==""?s:(o=!0,{...s,id:(u=i.get((0,qo.permissionKey)(s)))!==null&&u!==void 0?u:(0,kI.newId)()})});return o?{...t,permissions:a}:t}};rf.FieldSecurityProfileAdapter=Lb;function cSe(){return{adapter:new Lb,api:sSe.fieldSecurityProfileApi,guardedDelete:!0}}rf.fieldSecurityProfileRegistration=cSe});var k9=C(of=>{"use strict";Object.defineProperty(of,"__esModule",{value:!0});of.customApiPushIssues=of.customApiMutationIssues=void 0;var Oa=v0(),LI=/^\{?[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}\}?$/,xI=["requestParameters","responseProperties"];function jt(e,t,n){return{pointer:e,rule:t,message:n}}var MI=(e,t)=>typeof t=="string"&&Object.prototype.hasOwnProperty.call(e,t),dSe=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),P9=e=>e==null||typeof e=="string";function R9(e){let t=e,n=[];t.id!==void 0&&(typeof t.id!="string"||!LI.test(t.id))&&n.push(jt("/id","guid","must be a GUID"));for(let r of["uniqueName","name","displayName","description"])t[r]!==void 0&&typeof t[r]!="string"&&n.push(jt(`/${r}`,"type","must be a string"));for(let r of["boundEntityLogicalName","executePrivilegeName"])P9(t[r])||n.push(jt(`/${r}`,"type","must be a string or null"));t.pluginTypeId!==void 0&&t.pluginTypeId!==null&&(typeof t.pluginTypeId!="string"||!LI.test(t.pluginTypeId))&&n.push(jt("/pluginTypeId","guid","must be a GUID or null")),t.binding!==void 0&&!MI(Oa.CUSTOM_API_BINDING_CODES,t.binding)&&n.push(jt("/binding","enum",`must be one of ${Object.keys(Oa.CUSTOM_API_BINDING_CODES).join(", ")}`)),t.allowedProcessingSteps!==void 0&&!MI(Oa.CUSTOM_API_STEP_CODES,t.allowedProcessingSteps)&&n.push(jt("/allowedProcessingSteps","enum",`must be one of ${Object.keys(Oa.CUSTOM_API_STEP_CODES).join(", ")}`));for(let r of["isFunction","isPrivate","enabledForWorkflow"])t[r]!==void 0&&typeof t[r]!="boolean"&&n.push(jt(`/${r}`,"type","must be true or false"));for(let r of xI){let i=t[r];if(i===void 0)continue;if(!Array.isArray(i)){n.push(jt(`/${r}`,"type","must be an array"));continue}let o=new Map;i.forEach((a,s)=>{let u=`/${r}/${s}`;if(!dSe(a)){n.push(jt(u,"type","must be an object"));return}a.id!==void 0&&(typeof a.id!="string"||!LI.test(a.id))&&n.push(jt(`${u}/id`,"guid","must be a GUID (or omitted, and the SDK mints one)")),a.uniqueName!==void 0&&typeof a.uniqueName!="string"&&n.push(jt(`${u}/uniqueName`,"type","must be a string")),a.type!==void 0&&!MI(Oa.CUSTOM_API_TYPE_CODES,a.type)&&n.push(jt(`${u}/type`,"enum",`must be one of ${Object.keys(Oa.CUSTOM_API_TYPE_CODES).join(", ")}`)),a.isOptional!==void 0&&typeof a.isOptional!="boolean"&&n.push(jt(`${u}/isOptional`,"type","must be true or false"));for(let l of["entityLogicalName","name","displayName","description"])P9(a[l])||n.push(jt(`${u}/${l}`,"type","must be a string or null"));if(typeof a.uniqueName=="string"&&a.uniqueName!==""){let l=a.uniqueName.toLowerCase(),c=o.get(l);c!==void 0?n.push(jt(`${u}/uniqueName`,"duplicate-unique-name",`'${a.uniqueName}' is already used by ${r}/${c} (names compare ignoring case)`)):o.set(l,s)}})}return n}function fSe(e,t){return R9(e)}of.customApiMutationIssues=fSe;var pSe=["uniqueName","binding","boundEntityLogicalName","isFunction","allowedProcessingSteps","enabledForWorkflow"],mSe=["uniqueName","type","isOptional","entityLogicalName"];function hSe(e,t){var n,r,i,o;let a=R9(e);for(let u of["uniqueName","name","displayName","description"])(typeof e[u]!="string"||e[u].trim()==="")&&a.push(jt(`/${u}`,"required","must be a non-empty string"));e.binding!=="global"&&(!e.boundEntityLogicalName||e.boundEntityLogicalName.trim()==="")&&a.push(jt("/boundEntityLogicalName","bound-entity-required",`an '${e.binding}' binding needs a table`));for(let u of xI)((n=e[u])!==null&&n!==void 0?n:[]).forEach((l,c)=>{(typeof l.uniqueName!="string"||l.uniqueName.trim()==="")&&a.push(jt(`/${u}/${c}/uniqueName`,"required","must be a non-empty string")),l.type===void 0&&a.push(jt(`/${u}/${c}/type`,"required","must be set (the platform would default it to boolean)"))});if((t?e.pluginTypeId!==t.pluginTypeId:((r=e.pluginTypeId)!==null&&r!==void 0?r:null)!==null)&&a.push(jt("/pluginTypeId","plugin-type-read-only","the plug-in type is read-only in this SDK (definitions only); bind a plug-in with the Plug-in Registration tool or the maker portal")),!t)return a;(0,Oa.canonicalGuid)(e.id)!==(0,Oa.canonicalGuid)(t.id)&&a.push(jt("/id","immutable-after-create","is the id of the API this artifact was fetched from and cannot change; to work on another API, fetch it"));for(let u of pSe)e[u]!==t[u]&&a.push(jt(`/${String(u)}`,"immutable-after-create","cannot be changed once the API exists (the platform ignores the change). Deleting and re-creating the API makes a different API for its callers and for anything attached to it; the SDK does not do it for you"));for(let u of xI){let l=new Map(((i=t[u])!==null&&i!==void 0?i:[]).map(c=>[(0,Oa.canonicalGuid)(c.id),c]));((o=e[u])!==null&&o!==void 0?o:[]).forEach((c,d)=>{var f,p;let m=l.get((0,Oa.canonicalGuid)(c.id));if(!(!m||c.id===void 0))for(let h of mSe){let g=(f=c[h])!==null&&f!==void 0?f:null,y=(p=m[h])!==null&&p!==void 0?p:null;(h==="isOptional"?!!g!=!!y:g!==y)&&a.push(jt(`/${u}/${d}/${h}`,"immutable-after-create","cannot be changed once the row exists (the platform ignores the change): remove it and add a new one \u2014 the push deletes and re-creates it in one change set"))}})}return a}of.customApiPushIssues=hSe});var U9=C(Da=>{"use strict";Object.defineProperty(Da,"__esModule",{value:!0});Da.customApiRegistration=Da.CustomApiAdapter=Da.CUSTOM_API_CHILDREN=void 0;var $9=k9(),gSe=C0(),xi=v0(),ySe=Y(),L9=Eu(),FI=Rs(),Mb=ft(),Hl=ae();Da.CUSTOM_API_CHILDREN=[{list:"requestParameters",kind:"requestParameter",nav:"CustomAPIRequestParameters",set:"customapirequestparameters",pk:"customapirequestparameterid"},{list:"responseProperties",kind:"responseProperty",nav:"CustomAPIResponseProperties",set:"customapiresponseproperties",pk:"customapiresponsepropertyid"}];var bSe=["name","displayname","description","isprivate","executeprivilegename"],vSe=["name","isprivate","executeprivilegename"],M9=new Set(["displayname","description"]),wSe=["name","displayname","description"];function x9(e,t){let n=e.uniqueName.toLowerCase(),r=t.uniqueName.toLowerCase();if(n!==r)return n<r?-1:1;let i=String(e.id),o=String(t.id);return i<o?-1:i>o?1:0}var Cs=e=>typeof e=="string"?e:null;function F9(e,t,n){var r,i;return{id:(0,Hl.normalizeGuid)(String((r=e[t])!==null&&r!==void 0?r:""),t),uniqueName:String((i=e.uniquename)!==null&&i!==void 0?i:""),type:(0,xi.optionName)(xi.CUSTOM_API_TYPE_CODES,e.type),...n?{isOptional:e.isoptional===!0}:{},entityLogicalName:Cs(e.logicalentityname),name:Cs(e.name),displayName:Cs(e.displayname),description:Cs(e.description)}}function UI(e){var t,n;return{uniquename:e.uniqueName,name:e.name,displayname:e.displayName,description:e.description,bindingtype:xi.CUSTOM_API_BINDING_CODES[e.binding],boundentitylogicalname:(t=e.boundEntityLogicalName)!==null&&t!==void 0?t:null,isfunction:e.isFunction,isprivate:e.isPrivate,allowedcustomprocessingsteptype:xi.CUSTOM_API_STEP_CODES[e.allowedProcessingSteps],workflowsdkstepenabled:e.enabledForWorkflow,executeprivilegename:(n=e.executePrivilegeName)!==null&&n!==void 0?n:null}}function xb(e,t){var n,r,i,o;return{uniquename:e.uniqueName,name:(n=e.name)!==null&&n!==void 0?n:null,displayname:(r=e.displayName)!==null&&r!==void 0?r:null,description:(i=e.description)!==null&&i!==void 0?i:null,type:xi.CUSTOM_API_TYPE_CODES[e.type],logicalentityname:(o=e.entityLogicalName)!==null&&o!==void 0?o:null,...t==="requestParameters"?{isoptional:e.isOptional===!0}:{}}}var Fb=class{toArtifact(t){return t}fromArtifact(t){return t}fromApiResponse(t){var n,r,i,o,a,s,u;let l=t??{},c=String((n=l.uniquename)!==null&&n!==void 0?n:"");return{id:(0,Hl.normalizeGuid)(String((r=l.customapiid)!==null&&r!==void 0?r:""),"customapiid"),uniqueName:c,name:(i=Cs(l.name))!==null&&i!==void 0?i:c,displayName:(o=Cs(l.displayname))!==null&&o!==void 0?o:"",description:(a=Cs(l.description))!==null&&a!==void 0?a:"",binding:(0,xi.optionName)(xi.CUSTOM_API_BINDING_CODES,l.bindingtype),boundEntityLogicalName:Cs(l.boundentitylogicalname),isFunction:l.isfunction===!0,isPrivate:l.isprivate===!0,allowedProcessingSteps:(0,xi.optionName)(xi.CUSTOM_API_STEP_CODES,l.allowedcustomprocessingsteptype),enabledForWorkflow:l.workflowsdkstepenabled===!0,executePrivilegeName:Cs(l.executeprivilegename),pluginTypeId:l._plugintypeid_value?(0,Hl.normalizeGuid)(l._plugintypeid_value,"_plugintypeid_value"):null,requestParameters:((s=l.CustomAPIRequestParameters)!==null&&s!==void 0?s:[]).map(d=>F9(d,"customapirequestparameterid",!0)).sort(x9),responseProperties:((u=l.CustomAPIResponseProperties)!==null&&u!==void 0?u:[]).map(d=>F9(d,"customapiresponsepropertyid",!1)).sort(x9)}}toApiPayload(t,n){var r,i;let o=(0,$9.customApiPushIssues)(t,n);if(o.length>0)throw new ySe.ValidationError("customApi",t.id,o);let a=t.isFunction&&t.responseProperties.length===0?[`customApi '${t.uniqueName}' is a function with no response property: a function needs at least one response property to be callable (it is not listed in $metadata and a call answers 404); right after the last one is removed, a call may still succeed for a while.`]:[],s={deletes:[],posts:[],patches:[],held:{requestParameters:((r=n?.requestParameters)!==null&&r!==void 0?r:[]).map(d=>(0,xi.canonicalGuid)(String(d.id))),responseProperties:((i=n?.responseProperties)!==null&&i!==void 0?i:[]).map(d=>(0,xi.canonicalGuid)(String(d.id)))},labelEdits:[],warnings:a};if(!n)return s.create={customapiid:(0,Hl.normalizeGuid)(t.id,"id"),...UI(t),...Object.fromEntries(Da.CUSTOM_API_CHILDREN.map(({list:d,nav:f,pk:p})=>[f,t[d].map(m=>({[p]:(0,Hl.normalizeGuid)(String(m.id),`${d}.id`),...xb(m,d)}))]))},s;let u=UI(t),l=UI(n),c=bSe.filter(d=>!(0,FI.deepEqual)(u[d],l[d]));c.length>0&&(s.api=Object.fromEntries(c.map(d=>[d,u[d]])),s.labelEdits.push(...c.filter(d=>M9.has(d)).map(d=>`/${d==="displayname"?"displayName":"description"}`)));for(let{list:d,kind:f}of Da.CUSTOM_API_CHILDREN){let p=new Map(n[d].map(h=>[(0,xi.canonicalGuid)(String(h.id)),h])),m=new Map;t[d].forEach((h,g)=>{let y=(0,xi.canonicalGuid)((0,Hl.normalizeGuid)(String(h.id),`${d}.id`));m.set(y,h);let b=p.get(y);if(!b){s.posts.push({kind:f,id:y,body:{[f==="requestParameter"?"customapirequestparameterid":"customapiresponsepropertyid"]:y,...xb(h,d),"[email protected]":`/customapis(${(0,Hl.normalizeGuid)(t.id,"id")})`}});return}let E=xb(h,d),w=xb(b,d),_=wSe.filter(I=>!(0,FI.deepEqual)(E[I],w[I]));_.length>0&&(s.patches.push({kind:f,id:y,body:Object.fromEntries(_.map(I=>[I,E[I]]))}),s.labelEdits.push(..._.filter(I=>M9.has(I)).map(I=>`/${d}/${g}/${I==="displayname"?"displayName":"description"}`)))});for(let h of p.keys())m.has(h)||s.deletes.push({kind:f,id:h})}return!s.api&&s.posts.length+s.patches.length+s.deletes.length===0&&(s.api=Object.fromEntries(vSe.map(d=>[d,u[d]]))),s}createDefault(t){var n,r,i,o,a,s,u,l,c,d,f,p,m,h,g;let y=(n=t.uniqueName)!==null&&n!==void 0?n:"",b=(r=t.displayName)!==null&&r!==void 0?r:y;return{id:(i=t.id)!==null&&i!==void 0?i:(0,Mb.newId)(),uniqueName:y,name:(o=t.name)!==null&&o!==void 0?o:y,displayName:b,description:(a=t.description)!==null&&a!==void 0?a:b,binding:(s=t.binding)!==null&&s!==void 0?s:"global",boundEntityLogicalName:(u=t.boundEntityLogicalName)!==null&&u!==void 0?u:null,isFunction:(l=t.isFunction)!==null&&l!==void 0?l:!1,isPrivate:(c=t.isPrivate)!==null&&c!==void 0?c:!1,allowedProcessingSteps:(d=t.allowedProcessingSteps)!==null&&d!==void 0?d:"none",enabledForWorkflow:(f=t.enabledForWorkflow)!==null&&f!==void 0?f:!1,executePrivilegeName:(p=t.executePrivilegeName)!==null&&p!==void 0?p:null,pluginTypeId:(m=t.pluginTypeId)!==null&&m!==void 0?m:null,requestParameters:(0,L9.cloneJson)((h=t.requestParameters)!==null&&h!==void 0?h:[]),responseProperties:(0,L9.cloneJson)((g=t.responseProperties)!==null&&g!==void 0?g:[])}}assignMissingIds(t){return(0,Mb.assignMissingIds)(t)}validate(t,n){return(0,$9.customApiMutationIssues)(t,n)}normalize(t){var n,r;let i=!1,o=t.id?t.id:(i=!0,(0,Mb.newId)()),a=(l,c)=>{let d={...l};return d.id||(d.id=(0,Mb.newId)()),d.name===void 0&&(d.name=`${t.uniqueName}.${l.uniqueName}`),d.displayName===void 0&&(d.displayName=l.uniqueName),d.description===void 0&&(d.description=d.displayName),c==="requestParameters"&&d.isOptional===void 0&&(d.isOptional=!1),(0,FI.deepEqual)(d,l)||(i=!0),d},s=((n=t.requestParameters)!==null&&n!==void 0?n:[]).map(l=>a(l,"requestParameters")),u=((r=t.responseProperties)!==null&&r!==void 0?r:[]).map(l=>a(l,"responseProperties"));return(!t.requestParameters||!t.responseProperties)&&(i=!0),i?{...t,id:o,requestParameters:s,responseProperties:u}:t}};Da.CustomApiAdapter=Fb;function ESe(){return{adapter:new Fb,api:gSe.customApiApi,guardedDelete:!0}}Da.customApiRegistration=ESe});var B9=C(Pa=>{"use strict";Object.defineProperty(Pa,"__esModule",{value:!0});Pa.pushIssues=Pa.shapeIssues=Pa.MATCHES=void 0;Pa.MATCHES=["exact","firstCharacters","lastCharacters","sameDate","sameDateAndTime","exactChoiceLabel","exactChoiceValue"];var ASe=["published","unpublished","publishing"],q9=/^\{?[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}\}?$/,af=e=>e.toLowerCase().replace(/^\{|\}$/g,"");function Ut(e,t,n){return{pointer:e,rule:t,message:n}}var th=e=>typeof e=="string"&&e.trim()!=="";function CSe(e){let t=e,n=[];(typeof t.id!="string"||!q9.test(t.id))&&n.push(Ut("/id","guid","must be the rule's GUID (adapter-managed)")),th(t.name)||n.push(Ut("/name","required",'must be a non-empty string, e.g. "Contacts with the same email"')),th(t.entityLogicalName)||n.push(Ut("/entityLogicalName","required",'must be a table logical name, e.g. "contact"')),t.description!==void 0&&t.description!==null&&typeof t.description!="string"&&n.push(Ut("/description","type","must be a string or null")),t.matchingEntityLogicalName!==void 0&&!th(t.matchingEntityLogicalName)&&n.push(Ut("/matchingEntityLogicalName","type","must be a table logical name, or omitted"));for(let i of["caseSensitive","excludeInactiveRecords"])t[i]!==void 0&&typeof t[i]!="boolean"&&n.push(Ut(`/${i}`,"type","must be a boolean"));if(ASe.includes(t.status)||n.push(Ut("/status","enum","must be 'published' or 'unpublished'")),!Array.isArray(t.conditions))return n.push({...Ut("/conditions","type","must be an array of conditions"),fatal:!0}),n;let r=new Set;return t.conditions.forEach((i,o)=>{let a=`/conditions/${o}`;if(i===null||typeof i!="object"||Array.isArray(i)){n.push(Ut(a,"type","must be an object { column, match }"));return}let s=i;s.id!==void 0&&(typeof s.id!="string"||!q9.test(s.id)?n.push(Ut(`${a}/id`,"guid","must be a GUID (adapter-managed \u2014 omit it)")):r.has(af(s.id))?n.push(Ut(`${a}/id`,"duplicate-condition-id","another condition has the same id")):r.add(af(s.id))),th(s.column)||n.push(Ut(`${a}/column`,"required",'must be a column logical name, e.g. "emailaddress1"')),s.matchingColumn!==void 0&&!th(s.matchingColumn)&&n.push(Ut(`${a}/matchingColumn`,"type","must be a column logical name, or omitted")),Pa.MATCHES.includes(s.match)||n.push(Ut(`${a}/match`,"enum",`must be one of ${Pa.MATCHES.join(", ")}`)),s.characters!==void 0&&s.characters!==null&&!(typeof s.characters=="number"&&Number.isInteger(s.characters)&&s.characters>0)&&n.push(Ut(`${a}/characters`,"type","must be a positive integer, or null")),s.ignoreBlankValues!==void 0&&typeof s.ignoreBlankValues!="boolean"&&n.push(Ut(`${a}/ignoreBlankValues`,"type","must be a boolean"))}),n}Pa.shapeIssues=CSe;function SSe(e,t){var n,r,i,o;let a=[],s=e.entityLogicalName,u=(n=e.matchingEntityLogicalName)!==null&&n!==void 0?n:s;if(e.conditions.forEach((l,c)=>{let d=`/conditions/${c}`;(l.match==="firstCharacters"||l.match==="lastCharacters")&&!(typeof l.characters=="number"&&l.characters>0)&&a.push(Ut(`${d}/characters`,"characters-required",`'${l.match}' needs how many characters, e.g. 3`)),u===s&&l.matchingColumn!==void 0&&l.matchingColumn!==l.column&&a.push(Ut(`${d}/matchingColumn`,"matching-column-same-table","a same-table rule compares a column with itself"))}),e.status==="published"&&e.conditions.length===0&&a.push(Ut("/status","published-without-conditions","a published rule needs at least one condition")),(e.status==="publishing"||t?.status==="publishing")&&a.push(Ut("/status","status-publishing","'publishing' is never authored, and a rule fetched while it was publishing must be re-fetched before a push")),t){af(String((r=e.id)!==null&&r!==void 0?r:""))!==af(String((i=t.id)!==null&&i!==void 0?i:""))&&a.push(Ut("/id","immutable-after-create","the rule's id is fixed once it exists \u2014 to copy a rule, create a new one")),e.entityLogicalName!==t.entityLogicalName&&a.push(Ut("/entityLogicalName","immutable-after-create","the table is fixed once the rule exists")),u!==((o=t.matchingEntityLogicalName)!==null&&o!==void 0?o:t.entityLogicalName)&&a.push(Ut("/matchingEntityLogicalName","immutable-after-create","the matching table is fixed once the rule exists"));let l=new Set(t.conditions.map(d=>{var f;return af((f=d.id)!==null&&f!==void 0?f:"")})),c=e.conditions.some(d=>!d.id||!l.has(af(d.id)));e.name!==t.name&&t.conditions.length===0&&!c&&a.push(Ut("/name","rename-empty-rule","a rule with no condition can be renamed only in a push that also adds one"))}return a}Pa.pushIssues=SSe});var G9=C(uf=>{"use strict";Object.defineProperty(uf,"__esModule",{value:!0});uf.duplicateRuleRegistration=uf.DuplicateRuleAdapter=void 0;var qI=B9(),NSe=S0(),sf=lC(),_Se=Y(),ISe=Eu(),GI=ft(),V9=e=>e.toLowerCase().replace(/^\{|\}$/g,""),TSe="Microsoft.Dynamics.CRM.duplicaterule",OSe="Microsoft.Dynamics.CRM.duplicaterulecondition";function DSe(e){var t,n,r;return{...e,id:e.id?V9(e.id):(0,GI.newId)(),matchingColumn:(t=e.matchingColumn)!==null&&t!==void 0?t:e.column,characters:(n=e.characters)!==null&&n!==void 0?n:null,ignoreBlankValues:(r=e.ignoreBlankValues)!==null&&r!==void 0?r:!1}}function BI(e){var t,n,r,i;return{...e,description:(t=e.description)!==null&&t!==void 0?t:null,matchingEntityLogicalName:(n=e.matchingEntityLogicalName)!==null&&n!==void 0?n:e.entityLogicalName,caseSensitive:(r=e.caseSensitive)!==null&&r!==void 0?r:!1,excludeInactiveRecords:(i=e.excludeInactiveRecords)!==null&&i!==void 0?i:!1,conditions:e.conditions.map(DSe)}}function nh(e){var t,n;return{duplicateruleconditionid:e.id,baseattributename:e.column,matchingattributename:(t=e.matchingColumn)!==null&&t!==void 0?t:e.column,operatorcode:sf.MATCH_CODES[e.match],...e.characters!==null&&e.characters!==void 0?{operatorparam:e.characters}:{},ignoreblankvalues:(n=e.ignoreBlankValues)!==null&&n!==void 0?n:!1}}var PSe=(e,t)=>JSON.stringify(nh(e))===JSON.stringify(nh(t)),VI=(e,t)=>e.id<t.id?-1:e.id>t.id?1:0,Ub=class{toArtifact(t){return t}fromArtifact(t){return t}fromApiResponse(t){var n;return(0,sf.projectAggregate)(t,String((n=t?.duplicateruleid)!==null&&n!==void 0?n:""))}toApiPayload(t,n){let r=(0,qI.shapeIssues)(t);if(r.length===0&&r.push(...(0,qI.pushIssues)(t,n)),r.length>0)throw new _Se.ValidationError("duplicateRule",t.id,r);let i=BI(t),o=V9(i.id);if(!n)return{desired:i,ops:[{method:"POST",path:`/${sf.DUPLICATE_RULE_SET}`,body:{duplicateruleid:o,name:i.name,...i.description!==null?{description:i.description}:{},baseentityname:i.entityLogicalName,matchingentityname:i.matchingEntityLogicalName,iscasesensitive:i.caseSensitive,excludeinactiverecords:i.excludeInactiveRecords,[sf.CONDITIONS_NAV]:i.conditions.map(nh)}}],statusAfterContent:"unpublished"};let a=BI(n),s=a.status==="published"?"published":"unpublished",u=new Map(a.conditions.map(I=>[I.id,I])),l=new Set(i.conditions.map(I=>I.id)),c=i.conditions.filter(I=>!u.has(I.id)).sort(VI),d=i.conditions.filter(I=>u.has(I.id)).sort(VI),f=a.conditions.filter(I=>!l.has(I.id)),p=d.some(I=>!PSe(I,u.get(I.id))),m=i.name!==a.name,h={...i.description!==a.description?{description:i.description}:{},...i.caseSensitive!==a.caseSensitive?{iscasesensitive:i.caseSensitive}:{},...i.excludeInactiveRecords!==a.excludeInactiveRecords?{excludeinactiverecords:i.excludeInactiveRecords}:{}},g="iscasesensitive"in h||"excludeinactiverecords"in h,y=c.length>0||f.length>0||p,b=I=>({method:"PATCH",path:`/${sf.DUPLICATE_RULE_SET}(${o})`,body:I,etag:"*"}),E=I=>({method:"POST",path:"/duplicateruleconditions",body:{...nh(I),"[email protected]":`/${sf.DUPLICATE_RULE_SET}(${o})`}}),w=I=>({method:"POST",path:"/CompoundUpdateDuplicateDetectionRule",body:{Entity:{"@odata.type":TSe,duplicateruleid:o,...m?{name:i.name}:{},...h},ChildEntities:I.map(T=>{let O=u.get(T.id);return{"@odata.type":OSe,...nh(T),...(T.characters===null||T.characters===void 0)&&O&&O.characters!==null?{operatorparam:null}:{}}})}});if(!m&&!y&&(!g||s==="unpublished")){let I=g?h:{description:i.description};return{desired:i,heldStatus:s,ops:[b(I)],statusAfterContent:g?"unpublished":s}}if(a.conditions.length>0){let I=d.length===0?[...a.conditions].sort(VI)[0]:void 0,T=[w(I?[I]:d)];return I&&T.push({method:"DELETE",path:`/duplicateruleconditions(${I.id})`}),T.push(...c.map(E)),{desired:i,heldStatus:s,ops:T,statusAfterContent:"unpublished"}}if(m)return{desired:i,heldStatus:s,ops:[...c.map(E),w(c)],statusAfterContent:"unpublished"};let _=Object.keys(h).length>0?[b(h)]:[];return _.push(...c.map(E)),{desired:i,heldStatus:s,ops:_,statusAfterContent:"unpublished"}}createDefault(t){var n,r,i,o,a,s,u,l,c;return{id:(n=t.id)!==null&&n!==void 0?n:(0,GI.newId)(),name:(r=t.name)!==null&&r!==void 0?r:"",description:(i=t.description)!==null&&i!==void 0?i:null,entityLogicalName:(o=t.entityLogicalName)!==null&&o!==void 0?o:"",matchingEntityLogicalName:(s=(a=t.matchingEntityLogicalName)!==null&&a!==void 0?a:t.entityLogicalName)!==null&&s!==void 0?s:"",caseSensitive:(u=t.caseSensitive)!==null&&u!==void 0?u:!1,excludeInactiveRecords:(l=t.excludeInactiveRecords)!==null&&l!==void 0?l:!1,status:(c=t.status)!==null&&c!==void 0?c:"published",conditions:t.conditions?(0,ISe.cloneJson)(t.conditions):[]}}assignMissingIds(t){if(t===null||typeof t!="object"||Array.isArray(t))return t;let n=t;return Array.isArray(n.conditions)?{...n,conditions:n.conditions.map(r=>this.assignMissingIds(r))}:"column"in n&&n.id===void 0?{...n,id:(0,GI.newId)()}:t}validate(t){return(0,qI.shapeIssues)(t)}normalize(t){return Array.isArray(t.conditions)?t.description!==void 0&&t.matchingEntityLogicalName!==void 0&&t.caseSensitive!==void 0&&t.excludeInactiveRecords!==void 0&&t.conditions.every(r=>r!==null&&typeof r=="object"&&r.id!==void 0&&r.matchingColumn!==void 0&&r.characters!==void 0&&r.ignoreBlankValues!==void 0)?t:BI(t):t}committed(t,n,r){let i=r.serverState;return(i==="published"||i==="unpublished")&&i!==t.status?{artifact:t,baseline:{...t,status:i}}:{artifact:t,baseline:t}}};uf.DuplicateRuleAdapter=Ub;function RSe(){return{adapter:new Ub,api:NSe.duplicateRuleApi,guardedDelete:!0,publishesOnPush:e=>{var t;let n=e;return((t=n?.desired)===null||t===void 0?void 0:t.status)==="published"&&n.statusAfterContent==="unpublished"}}}uf.duplicateRuleRegistration=RSe});var j9=C(qb=>{"use strict";Object.defineProperty(qb,"__esModule",{value:!0});qb.buildRegistrations=void 0;var kSe=r4(),$Se=_4(),LSe=uj(),MSe=Nj(),xSe=Hj(),FSe=fW(),USe=FW(),qSe=wz(),BSe=b9(),VSe=E9(),GSe=N9(),jSe=D9(),WSe=U9(),zSe=G9();function HSe(e){let t=new Map;return t.set("form",(0,kSe.formRegistration)(e)),t.set("view",(0,$Se.viewRegistration)()),t.set("businessRule",(0,LSe.businessRuleRegistration)()),t.set("app",(0,MSe.appRegistration)(e)),t.set("command",(0,xSe.commandRegistration)()),t.set("chart",(0,FSe.chartRegistration)()),t.set("dashboard",(0,USe.dashboardRegistration)(e)),t.set("genPage",(0,qSe.genPageRegistration)()),t.set("bpf",(0,BSe.bpfRegistration)()),t.set("environmentVariable",(0,VSe.environmentVariableRegistration)()),t.set("connectionReference",(0,GSe.connectionReferenceRegistration)()),t.set("fieldSecurityProfile",(0,jSe.fieldSecurityProfileRegistration)()),t.set("customApi",(0,WSe.customApiRegistration)()),t.set("duplicateRule",(0,zSe.duplicateRuleRegistration)()),t}qb.buildRegistrations=HSe});var X9=C(lf=>{"use strict";Object.defineProperty(lf,"__esModule",{value:!0});lf.findArtifact=lf.resolveArtifact=void 0;var dr=ae(),Ss=p0(),KSe=vc(),W9=Ke(),JSe=pe(),jI=Y(),z9=Jc(),H9=DI(),K9=s0(),J9=C0(),Y9=S0();async function Q9(e,t,n){let r="/uxagentprojects"+(0,dr.odataQuery)([["$select","uxagentprojectid,name"],["$filter",`name eq '${(0,dr.odataLiteral)(t)}'`],...n!==void 0?[["$top",String(n)]]:[]]);return(await(0,W9.collectPages)(e,r,"resolveArtifact('genPage')",void 0,{headers:{"MSCRM.IncludeUnpublished":"true"}})).map(o=>({id:String(o.uxagentprojectid),name:String(o.name)}))}async function YSe(e,t,n){var r,i,o,a,s,u,l,c,d,f,p,m,h,g,y,b,E,w;switch(t){case"app":{let _=(0,KSe.unpublishedAppModulesQuery)("appmoduleid,name,appmoduleidunique",`uniquename eq '${(0,dr.odataLiteral)((r=n.uniqueName)!==null&&r!==void 0?r:"")}'`,1),I=(0,JSe.ensureSuccess)(await e.get(_),e.apiUrl(_)),T=(i=I.body)===null||i===void 0?void 0:i.value;if(Array.isArray(T)&&!(0,W9.boundedPageComplete)(I.body,T.length))throw new jI.ConnectionError(e.apiUrl(_),I.status,`the app lookup for '${(o=n.uniqueName)!==null&&o!==void 0?o:""}' answered no app but says more rows exist`);let O=T&&T[0];return O?[{id:String(O.appmoduleid),name:String(O.name),appModuleIdUnique:String(O.appmoduleidunique)}]:[]}case"dashboard":return(await(0,Ss.queryRecords)(e,"systemform",{select:["formid","name"],filter:`name eq '${(0,dr.odataLiteral)((a=n.name)!==null&&a!==void 0?a:"")}' and type eq 0`,top:10})||[]).map(I=>({id:String(I.formid),name:String(I.name)}));case"command":{if(!n.entity)return[];let _=await(0,Ss.queryRecords)(e,"appaction",{select:["appactionid","buttonlabeltext"],filter:`contextvalue eq '${(0,dr.odataLiteral)(n.entity)}'`,top:1});return _&&_.length?[{id:n.entity,entity:n.entity}]:[]}case"form":return(await(0,Ss.queryRecords)(e,"systemform",{select:["formid","name"],filter:`name eq '${(0,dr.odataLiteral)((s=n.name)!==null&&s!==void 0?s:"")}' and objecttypecode eq '${(0,dr.odataLiteral)((u=n.entity)!==null&&u!==void 0?u:"")}'`,top:10})||[]).map(I=>({id:String(I.formid),name:String(I.name)}));case"chart":return(await(0,Ss.queryRecords)(e,"savedqueryvisualization",{select:["savedqueryvisualizationid","name"],filter:`name eq '${(0,dr.odataLiteral)((l=n.name)!==null&&l!==void 0?l:"")}' and primaryentitytypecode eq '${(0,dr.odataLiteral)((c=n.entity)!==null&&c!==void 0?c:"")}'`,top:10})||[]).map(I=>({id:String(I.savedqueryvisualizationid),name:String(I.name)}));case"view":return(await(0,Ss.queryRecords)(e,"savedquery",{select:["savedqueryid","name"],filter:`name eq '${(0,dr.odataLiteral)((d=n.name)!==null&&d!==void 0?d:"")}' and returnedtypecode eq '${(0,dr.odataLiteral)((f=n.entity)!==null&&f!==void 0?f:"")}'`,top:10})||[]).map(I=>({id:String(I.savedqueryid),name:String(I.name)}));case"webResource":return(await(0,Ss.queryRecords)(e,"webresource",{select:["webresourceid","name"],filter:`name eq '${(0,dr.odataLiteral)((p=n.name)!==null&&p!==void 0?p:"")}'`,top:1})||[]).map(I=>({id:String(I.webresourceid),name:String(I.name)}));case"solution":return(await(0,Ss.queryRecords)(e,"solution",{select:["solutionid","uniquename"],filter:`uniquename eq '${(0,dr.odataLiteral)((m=n.uniqueName)!==null&&m!==void 0?m:"")}'`,top:1})||[]).map(I=>({id:String(I.solutionid),name:String(I.uniquename)}));case"genPage":return Q9(e,(h=n.name)!==null&&h!==void 0?h:"");case"environmentVariable":return(0,z9.resolveEnvironmentVariables)(e,(g=n.uniqueName)!==null&&g!==void 0?g:"");case"connectionReference":return(0,H9.resolveConnectionReferences)(e,(y=n.uniqueName)!==null&&y!==void 0?y:"");case"fieldSecurityProfile":return(0,K9.resolveFieldSecurityProfiles)(e,(b=n.name)!==null&&b!==void 0?b:"");case"customApi":return(0,J9.resolveCustomApis)(e,(E=n.uniqueName)!==null&&E!==void 0?E:"");case"duplicateRule":return(0,Y9.resolveDuplicateRules)(e,(w=n.name)!==null&&w!==void 0?w:"",n.entity);default:return[]}}lf.resolveArtifact=YSe;async function QSe(e,t,n){var r,i,o,a,s,u,l,c,d,f,p;let m=(0,dr.odataLiteral)((r=n.name)!==null&&r!==void 0?r:""),h=(0,dr.odataLiteral)((i=n.entity)!==null&&i!==void 0?i:"");if(t==="command"){if(!n.entity)return null;let w=await(0,Ss.queryRecords)(e,"appaction",{select:["appactionid"],filter:`contextvalue eq '${(0,dr.odataLiteral)(n.entity)}'`,top:1});return w&&w.length?n.entity:null}if(t==="genPage"){let w=await Q9(e,(o=n.name)!==null&&o!==void 0?o:"",2);if(w.length>1)throw new jI.AmbiguousArtifactError(t,(a=n.name)!==null&&a!==void 0?a:"",w.length);return w.length===1?w[0].id:null}if(t==="environmentVariable")return(0,z9.findEnvironmentVariable)(e,(s=n.uniqueName)!==null&&s!==void 0?s:"");if(t==="connectionReference")return(0,H9.findConnectionReference)(e,(u=n.uniqueName)!==null&&u!==void 0?u:"");if(t==="fieldSecurityProfile")return(0,K9.findFieldSecurityProfile)(e,(l=n.name)!==null&&l!==void 0?l:"");if(t==="customApi")return(0,J9.findCustomApi)(e,(c=n.uniqueName)!==null&&c!==void 0?c:"");if(t==="duplicateRule")return(0,Y9.findDuplicateRule)(e,(d=n.name)!==null&&d!==void 0?d:"",n.entity);let g=XSe(t,m,h,n),y=t!=="app",b=await(0,Ss.queryRecords)(e,g.set,{select:[g.idField],filter:g.filter,top:y?2:1});if(y&&b&&b.length>1)throw new jI.AmbiguousArtifactError(t,(p=(f=n.name)!==null&&f!==void 0?f:n.uniqueName)!==null&&p!==void 0?p:"",b.length);let E=b&&b[0]&&b[0][g.idField];return E!=null?String(E):null}lf.findArtifact=QSe;function XSe(e,t,n,r){var i;switch(e){case"view":return{set:"savedquery",idField:"savedqueryid",filter:`returnedtypecode eq '${n}' and name eq '${t}'`};case"chart":return{set:"savedqueryvisualization",idField:"savedqueryvisualizationid",filter:`primaryentitytypecode eq '${n}' and name eq '${t}'`};case"form":return{set:"systemform",idField:"formid",filter:`objecttypecode eq '${n}' and name eq '${t}'`};case"app":return{set:"appmodule",idField:"appmoduleid",filter:`uniquename eq '${(0,dr.odataLiteral)((i=r.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 e8=C(Vb=>{"use strict";Object.defineProperty(Vb,"__esModule",{value:!0});Vb.seedRecordGraph=void 0;var Z9=p0(),ZSe=u0(),Bb=ae(),eNe=Y();async function tNe(e,t,n={}){var r,i,o,a,s;let u=(r=n.createdIds)!==null&&r!==void 0?r:{},l=(i=n.entitySetFor)!==null&&i!==void 0?i:(f=>(0,ZSe.resolveEntitySetName)(e,f)),c={},d=f=>{var p;return(p=c[f])!==null&&p!==void 0?p:u[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 I of f.records){let T={...I.body};for(let O of(a=I.binds)!==null&&a!==void 0?a:[]){let v=O.parentEntity.toLowerCase(),N=(s=d(v))===null||s===void 0?void 0:s[O.parentIndex];if(!N)throw new eNe.InvalidArgumentError(`Cannot resolve bind '${O.navProperty}' on a '${p}' record: parent '${O.parentEntity}'[${O.parentIndex}] has no created id. Seed the parent group before the child, or supply it via options.createdIds.`);let S=(0,Bb.assertODataName)(await l(v),`entity set for parent '${O.parentEntity}'`),R=(0,Bb.normalizeGuid)(N,`parent id for bind '${O.navProperty}'`);T[`${O.navProperty}@odata.bind`]=`/${S}(${R})`}h.push(T)}let g=m?h.map(I=>{let T=I[m];return T!=null&&T!==""?String(T):null}):h.map(()=>null),y=new Map;if(m){let I=(0,Bb.assertODataName)(m,"RecordGraph matchOn key"),T=[...new Set(g.filter(O=>O!==null))];if(T.length){let O=T.map(N=>`${I} eq '${(0,Bb.odataLiteral)(N)}'`).join(" or "),v=await(0,Z9.queryRecords)(e,p,{select:[I,`${p}id`],filter:O,top:5e3});for(let N of v??[]){let S=N[I];S!=null&&y.set(String(S).toLowerCase(),String(N[`${p}id`]))}}}let b=[],E=new Map,w=h.map((I,T)=>{let O=g[T];if(O&&y.has(O.toLowerCase()))return null;if(O){let v=O.toLowerCase(),N=E.get(v);if(N!==void 0)return N;let S=b.push(I)-1;return E.set(v,S),S}return b.push(I)-1}),_=b.length?await(0,Z9.createRecordsBulk)(e,p,b):[];c[p]=h.map((I,T)=>{let O=g[T];return O&&y.has(O.toLowerCase())?y.get(O.toLowerCase()):_[w[T]]})}return{createdIds:c}}Vb.seedRecordGraph=tNe});var i8=C(St=>{"use strict";Object.defineProperty(St,"__esModule",{value:!0});St.encodeValue=St.hasPlanShape=St.validateRequested=St.decodeValue=St.readKey=St.sameValue=St.isGuid=St.isNumericKind=St.kindOf=St.inSafeDomain=St.MAX_TEXT_LENGTH=void 0;St.MAX_TEXT_LENGTH=1048576;var nNe=[1e15,1e14,1e13,1e12,1e11,1e10,1e9,1e8,1e7,1e6,1e5],rNe=1e-6;function cf(e,t){if(typeof e!="number"||!Number.isFinite(e)||!Number.isInteger(t)||t<0||t>10)return!1;let n=Math.abs(e);return n>=nNe[t]||e!==0&&n<rNe?!1:Number(e.toFixed(t))===e}St.inSafeDomain=cf;function iNe(e,t){switch(e){case"String":return"string";case"Memo":return"memo";case"Integer":return"integer";case"Decimal":return"decimal";case"Double":return"double";case"Money":return"money";case"Boolean":return"boolean";case"Picklist":return"choice";case"State":return"state";case"Status":return"status";case"DateTime":return"dateTime";case"Lookup":return"lookup";case"Virtual":return t==="MultiSelectPicklistType"?"multiSelect":void 0;default:return}}St.kindOf=iNe;function oNe(e){return e==="decimal"||e==="double"||e==="money"}St.isNumericKind=oNe;var aNe=/^[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 jb(e){return typeof e=="string"&&aNe.test(e)}St.isGuid=jb;var n8=/^(\d{4})-(\d{2})-(\d{2})$/,sNe=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(|:\d{2}|:\d{2}\.\d{1,7})(Z|[+-]\d{2}:\d{2})$/;function rh(e){let t=n8.exec(e);if(!t)return!1;let n=new Date(Date.UTC(Number(t[1]),Number(t[2])-1,Number(t[3])));return n.getUTCFullYear()===Number(t[1])&&n.getUTCMonth()===Number(t[2])-1&&n.getUTCDate()===Number(t[3])}function ih(e){return rh(e)||sNe.test(e)&&Number.isFinite(Date.parse(e))&&rh(e.slice(0,10))}function t8(e){let t=n8.test(e)?`${e}T00:00:00Z`:e;return Math.floor(Date.parse(t)/1e3)}function Gb(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let t=Object.keys(e),n=e;return t.length===2&&typeof n.table=="string"&&typeof n.id=="string"}function WI(e){if(e===null)return[];if(Array.isArray(e)&&e.every(t=>Number.isInteger(t)))return[...e].sort((t,n)=>t-n)}function uNe(e,t,n,r){switch(e.kind){case"multiSelect":{let i=WI(t),o=WI(n);return i!==void 0&&o!==void 0&&i.length===o.length&&i.every((a,s)=>a===o[s])}case"lookup":return t===null||n===null?t===null&&n===null:Gb(t)&&Gb(n)&&t.table===n.table&&t.id.toLowerCase()===n.id.toLowerCase();case"decimal":case"double":case"money":return t===null||n===null?t===null&&n===null:r!==void 0&&cf(t,r)&&cf(n,r)&&t.toFixed(r)===n.toFixed(r);case"dateTime":return t===null||n===null?t===null&&n===null:typeof t!="string"||typeof n!="string"?!1:e.dateTimeBehavior==="DateOnly"?t===n:e.dateTimeBehavior==="UserLocal"||e.dateTimeBehavior==="TimeZoneIndependent"?ih(t)&&ih(n)&&t8(t)===t8(n):!1;default:return t===n}}St.sameValue=uNe;function r8(e){return e.kind==="lookup"?`_${e.logicalName}_value`:e.logicalName}St.readKey=r8;function lNe(e,t,n){var r;let i=r8(e);if(!Object.prototype.hasOwnProperty.call(t,i))return{ok:!1,reason:"incompleteRead"};let o=t[i],a={ok:!1,reason:"unsafeValue"};if(o===null)return e.kind==="boolean"||e.kind==="state"||e.kind==="status"?a:{ok:!0,value:null};switch(e.kind){case"string":case"memo":return typeof o=="string"?{ok:!0,value:o}:a;case"integer":return Number.isSafeInteger(o)?{ok:!0,value:o}:a;case"decimal":case"double":case"money":return n!==void 0&&cf(o,n)?{ok:!0,value:o}:a;case"boolean":return typeof o=="boolean"?{ok:!0,value:o}:a;case"choice":case"state":case"status":return Number.isInteger(o)?{ok:!0,value:o}:a;case"multiSelect":return typeof o!="string"||!o.split(",").every(s=>/^-?\d+$/.test(s))?a:{ok:!0,value:o.split(",").map(Number).sort((s,u)=>s-u)};case"dateTime":return typeof o!="string"?a:e.dateTimeBehavior==="DateOnly"?rh(o)?{ok:!0,value:o}:a:ih(o)?{ok:!0,value:o}:a;case"lookup":{let s=t[`${i}@Microsoft.Dynamics.CRM.lookuplogicalname`];return!jb(o)||typeof s!="string"||s!==((r=e.lookupTarget)===null||r===void 0?void 0:r.table)?a:{ok:!0,value:{table:s,id:o.toLowerCase()}}}default:return a}}St.decodeValue=lNe;function cNe(e,t,n,r){var i,o,a;if(n===null)return e.kind==="boolean"||e.kind==="state"||e.kind==="status"?"invalidValue":void 0;let s=u=>(t.min===void 0||u>=t.min)&&(t.max===void 0||u<=t.max);switch(e.kind){case"string":case"memo":return typeof n=="string"&&n.length<=((i=t.maxLength)!==null&&i!==void 0?i:St.MAX_TEXT_LENGTH)?void 0:"invalidValue";case"integer":return Number.isSafeInteger(n)&&s(n)?void 0:"invalidValue";case"decimal":case"double":case"money":return typeof n!="number"||!Number.isFinite(n)||!s(n)?"invalidValue":r===void 0||cf(n,r)?void 0:"invalidValue";case"boolean":return typeof n=="boolean"?void 0:"invalidValue";case"choice":case"state":case"status":return Number.isInteger(n)&&((o=t.options)!==null&&o!==void 0?o:[]).includes(n)?void 0:"invalidValue";case"multiSelect":return!Array.isArray(n)||new Set(n).size!==n.length?"invalidValue":n.every(u=>{var l;return Number.isInteger(u)&&((l=t.options)!==null&&l!==void 0?l:[]).includes(u)})?void 0:"invalidValue";case"dateTime":return typeof n!="string"?"invalidValue":e.dateTimeBehavior==="DateOnly"?rh(n)?void 0:"invalidValue":ih(n)?void 0:"invalidValue";case"lookup":return Gb(n)&&n.table===((a=e.lookupTarget)===null||a===void 0?void 0:a.table)&&jb(n.id)?void 0:"invalidLookupTarget";default:return"invalidValue"}}St.validateRequested=cNe;function dNe(e,t,n){var r;if(t===null)return e.kind!=="boolean"&&e.kind!=="state"&&e.kind!=="status";switch(e.kind){case"string":case"memo":return typeof t=="string"&&t.length<=St.MAX_TEXT_LENGTH;case"integer":return Number.isSafeInteger(t);case"decimal":case"double":case"money":return n!==void 0&&cf(t,n);case"boolean":return typeof t=="boolean";case"choice":case"state":case"status":return Number.isInteger(t);case"multiSelect":return Array.isArray(t)&&new Set(t).size===t.length&&t.every(i=>Number.isInteger(i));case"dateTime":return typeof t!="string"?!1:e.dateTimeBehavior==="DateOnly"?rh(t):ih(t);case"lookup":return Gb(t)&&t.table===((r=e.lookupTarget)===null||r===void 0?void 0:r.table)&&jb(t.id);default:return!1}}St.hasPlanShape=dNe;function fNe(e,t){var n;if(e.kind==="lookup"){let r=e.lookupTarget;return{[`${r.navigationProperty}@odata.bind`]:t===null?null:`/${r.entitySetName}(${t.id.toLowerCase()})`}}if(e.kind==="multiSelect"){let r=(n=WI(t))!==null&&n!==void 0?n:[];return{[e.logicalName]:r.length===0?null:r.join(",")}}return{[e.logicalName]:t}}St.encodeValue=fNe});var v8=C(ku=>{"use strict";Object.defineProperty(ku,"__esModule",{value:!0});ku.applyDataFix=ku.planDataFix=ku.getOnlyDataverse=void 0;var zI=Zo(),Wt=i8(),YI=Ke(),Qe=Y(),Bo=pe(),f8=ft(),Si=ae(),pNe=5e3,Ru=5e4,mNe=5e3,Wb=100,ff=40,hNe=100,o8=1e3,gNe=4*1024*1024,yNe=512,bNe=3e5,a8=36e5,vNe=10,p8="Microsoft.Dynamics.CRM.lookuplogicalname",wNe="0x80040216",ENe="0x80040217";function QI(e){return{apiUrl:t=>e.apiUrl(t),get:(t,n)=>e.get(t,n),getAbsolute:(t,n)=>e.getAbsolute(t,n)}}ku.getOnlyDataverse=QI;function Qn(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}var Kl=e=>typeof e=="string"&&/^[A-Za-z_][A-Za-z0-9_]*$/.test(e);function KI(e){if(Array.isArray(e))return e.map(KI);if(Qn(e)){let t={};for(let n of Object.keys(e))Object.defineProperty(t,n,{value:KI(e[n]),enumerable:!0,writable:!0,configurable:!0});return t}return e}var ANe="transactioncurrencyid";function m8(e,t){let n=Object.keys(e??{}).find(r=>r.toLowerCase()===t);return n===void 0?void 0:e[n]}function h8(e){return new URL(e.apiUrl("/")).origin}async function XI(e,t,n){let r;try{r=await t()}catch(i){throw(0,Qe.attachCause)(new Qe.DataFixError("DATA_FIX_READ_FAILED",`Reading ${e} for the data fix failed in transport.`,0),i)}try{(0,Bo.ensureSuccess)(r,n)}catch(i){throw(0,Qe.attachCause)(new Qe.DataFixError("DATA_FIX_READ_FAILED",`Reading ${e} for the data fix failed: HTTP ${r.status}.`,r.status),i)}return r}function Jl(e,t,n,r){return XI(t,()=>e.get(n,r),e.apiUrl(n))}function pf(e,t){var n;let r=(n=e.body)===null||n===void 0?void 0:n.value;if(!Array.isArray(r)||!r.every(Qn))throw new Qe.DataFixError("DATA_FIX_READ_FAILED",`Reading ${t} for the data fix returned a malformed page.`,e.status);return r}async function s8(e,t,n,r,i){let o=[];for(let a=0;a<r.length;a+=ff){let s=r.slice(a,a+ff).map(l=>`LogicalName eq '${(0,Si.odataLiteral)(l)}'`).join(" or "),u=`${t}${(0,Si.odataQuery)([["$select",n],["$expand",i],["$filter",s]])}`;o.push(...pf(await Jl(e,"the column metadata",u),"the column metadata"))}return o}function u8(e,t){if(!Qn(e)||Object.keys(e).length===0)throw new Qe.InvalidArgumentError(`${t} must be an object naming at least one column`);return Object.keys(e).forEach((n,r)=>{if(!Kl(n))throw new Qe.InvalidArgumentError(`${t} key #${r+1} must be a column's logical name (letters, digits, underscores)`)}),KI(e)}function CNe(e){if(!Qn(e))throw new Qe.InvalidArgumentError("planDataFix needs a request object");let t=e;if(!Kl(t.table))throw new Qe.InvalidArgumentError("planDataFix `table` must be a table's logical name (letters, digits, underscores)");let n=t.table,r=t.filter!==void 0,i=t.rows!==void 0;if(r===i)throw new Qe.InvalidArgumentError("planDataFix needs exactly one of `filter` (with `set`) and `rows`");if(r){if(typeof t.filter!="string"||t.filter.trim()==="")throw new Qe.InvalidArgumentError('planDataFix `filter` must be a non-blank OData $filter \u2014 there is no "every row"');let u=t.maxRows===void 0?pNe:t.maxRows;if(!Number.isInteger(u)||u<1||u>Ru)throw new Qe.InvalidArgumentError(`planDataFix \`maxRows\` must be an integer 1..${Ru}`);let l=u8(t.set,"planDataFix `set`");return{table:n,filter:t.filter,maxRows:u,set:l,columnNames:Object.keys(l)}}if(!Array.isArray(t.rows)||t.rows.length===0||t.rows.length>Ru)throw new Qe.InvalidArgumentError(`planDataFix \`rows\` must hold 1..${Ru} rows`);let o=new Set,a=[],s=t.rows.map((u,l)=>{if(!Qn(u))throw new Qe.InvalidArgumentError(`planDataFix rows[${l}] must be an object`);let c=typeof u.id=="string"?u.id.replace(/^\{(.*)\}$/,"$1"):"";if(!(0,Wt.isGuid)(c))throw new Qe.InvalidArgumentError(`planDataFix rows[${l}].id must be a GUID`);let d=c.toLowerCase();if(o.has(d))throw new Qe.InvalidArgumentError(`planDataFix rows[${l}].id repeats an earlier row`);if(o.add(d),u.etag!==void 0&&(!(0,Bo.isVersionToken)(u.etag)||/[\u0000-\u001F\u007F]/.test(u.etag)))throw new Qe.InvalidArgumentError(`planDataFix rows[${l}].etag must be a row version token (W/"\u2026")`);let f=u8(u.set,`planDataFix rows[${l}].set`);for(let p of Object.keys(f))a.includes(p)||a.push(p);return{id:d,set:f,etag:u.etag}});return{table:n,maxRows:Ru,rows:s,columnNames:a}}async function g8(e,t){let n=`/EntityDefinitions(LogicalName='${(0,Si.odataPathLiteral)(t)}')`+(0,Si.odataQuery)([["$select","EntitySetName,PrimaryIdAttribute,PrimaryNameAttribute,IsOptimisticConcurrencyEnabled"]]),r;try{r=await e.get(n)}catch(s){throw(0,Qe.attachCause)(new Qe.DataFixError("DATA_FIX_READ_FAILED","Reading the table metadata for the data fix failed in transport.",0),s)}if(r.status===404)throw new Qe.DataFixError("DATA_FIX_TABLE_NOT_FOUND",`The table '${t}' was not found.`,404);await XI("the table metadata",()=>Promise.resolve(r),e.apiUrl(n));let i=r.body,o=[i?.EntitySetName,i?.PrimaryIdAttribute,i?.PrimaryNameAttribute];if(!o.every(s=>typeof s=="string"&&/^[A-Za-z_][A-Za-z0-9_]*$/.test(s)))throw new Qe.DataFixError("DATA_FIX_READ_FAILED","Reading the table metadata for the data fix returned a malformed answer.",r.status);let a=i?.IsOptimisticConcurrencyEnabled;if(a!==!0)throw new Qe.DataFixError("DATA_FIX_CONCURRENCY_UNSUPPORTED",`The table '${t}' does not have optimistic concurrency enabled, so its rows cannot be written conditionally; a data fix refuses it.`);return{logicalName:t,entitySetName:o[0],primaryIdAttribute:o[1],primaryNameAttribute:o[2],concurrency:a}}var SNe={string:{cast:"StringAttributeMetadata",select:"LogicalName,MaxLength"},memo:{cast:"MemoAttributeMetadata",select:"LogicalName,MaxLength"},integer:{cast:"IntegerAttributeMetadata",select:"LogicalName,MinValue,MaxValue"},decimal:{cast:"DecimalAttributeMetadata",select:"LogicalName,Precision,MinValue,MaxValue"},double:{cast:"DoubleAttributeMetadata",select:"LogicalName,Precision,MinValue,MaxValue"},money:{cast:"MoneyAttributeMetadata",select:"LogicalName,Precision,PrecisionSource,MinValue,MaxValue"},dateTime:{cast:"DateTimeAttributeMetadata",select:"LogicalName,DateTimeBehavior"},choice:{cast:"PicklistAttributeMetadata",select:"LogicalName",expand:"OptionSet($select=Options)"},state:{cast:"StateAttributeMetadata",select:"LogicalName",expand:"OptionSet($select=Options)"},status:{cast:"StatusAttributeMetadata",select:"LogicalName",expand:"OptionSet($select=Options)"},multiSelect:{cast:"MultiSelectPicklistAttributeMetadata",select:"LogicalName",expand:"OptionSet($select=Options)"},lookup:{cast:"LookupAttributeMetadata",select:"LogicalName,Targets"}},oh=e=>Number.isInteger(e)&&e>=0&&e<=10,df=e=>typeof e=="number"&&Number.isFinite(e);async function NNe(e,t,n){var r;let i=`/EntityDefinitions(LogicalName='${(0,Si.odataPathLiteral)(t.logicalName)}')`,o=await s8(e,`${i}/Attributes`,"LogicalName,AttributeType,AttributeTypeName,IsValidForRead,IsValidForUpdate,IsSecured",n),a=new Map(o.map(h=>[String(h.LogicalName),h])),s=new Map,u=new Map;for(let h of n){let g=a.get(h);if(h===t.primaryIdAttribute)s.set(h,"primaryKey");else if(!g)s.set(h,"notFound");else if(![g.IsSecured,g.IsValidForRead,g.IsValidForUpdate].every(y=>typeof y=="boolean"))s.set(h,"metadataIncomplete");else if(g.IsSecured===!0)s.set(h,"secured");else if(g.IsValidForRead===!1)s.set(h,"notReadable");else if(g.IsValidForUpdate===!1)s.set(h,"readOnly");else{let y=(0,Wt.kindOf)(g.AttributeType,(r=g.AttributeTypeName)===null||r===void 0?void 0:r.Value);y===void 0?s.set(h,"unsupportedType"):u.set(h,y)}}let l=new Map;for(let h of new Set(u.values())){let g=SNe[h];if(!g)continue;let y=[...u].filter(([,b])=>b===h).map(([b])=>b);for(let b of await s8(e,`${i}/Attributes/Microsoft.Dynamics.CRM.${g.cast}`,g.select,y,g.expand))l.set(String(b.LogicalName),b)}let c=[...u].filter(([,h])=>h==="lookup").map(([h])=>h),d=c.length>0?await _Ne(e,i,c):new Map,p=[...u].some(([h,g])=>{var y;return g==="money"&&((y=l.get(h))===null||y===void 0?void 0:y.PrecisionSource)===1})?await INe(e):void 0,m=new Map;for(let[h,g]of u){let y=await TNe(e,h,g,l.get(h),d,p);"issue"in y?s.set(h,y.issue):m.set(h,y)}return{planned:m,issues:s}}async function _Ne(e,t,n){var r;let i=new Map;for(let o=0;o<n.length;o+=ff){let a=n.slice(o,o+ff).map(u=>`ReferencingAttribute eq '${(0,Si.odataLiteral)(u)}'`).join(" or "),s=`${t}/ManyToOneRelationships${(0,Si.odataQuery)([["$select","ReferencingAttribute,ReferencedEntity,ReferencingEntityNavigationPropertyName"],["$filter",a]])}`;for(let u of pf(await Jl(e,"the lookup relationships",s),"the lookup relationships")){let l=String(u.ReferencingAttribute),c=(r=i.get(l))!==null&&r!==void 0?r:new Map;typeof u.ReferencedEntity=="string"&&typeof u.ReferencingEntityNavigationPropertyName=="string"&&c.set(u.ReferencedEntity,u.ReferencingEntityNavigationPropertyName),i.set(l,c)}}return i}async function INe(e){var t;let n=`/organizations${(0,Si.odataQuery)([["$select","pricingdecimalprecision"]])}`,i=(t=pf(await Jl(e,"the organization precision",n),"the organization precision")[0])===null||t===void 0?void 0:t.pricingdecimalprecision;return oh(i)?i:void 0}async function TNe(e,t,n,r,i,o){var a,s,u,l;let c={issue:"metadataIncomplete"},d={min:r?.MinValue,max:r?.MaxValue};switch(n){case"string":case"memo":return Number.isInteger(r?.MaxLength)?{column:{logicalName:t,kind:n},facts:{maxLength:r?.MaxLength}}:c;case"integer":return df(d.min)&&df(d.max)?{column:{logicalName:t,kind:n},facts:{min:d.min,max:d.max}}:c;case"decimal":case"double":return df(d.min)&&df(d.max)&&oh(r?.Precision)?{column:{logicalName:t,kind:n,precisionSource:"column"},facts:{min:d.min,max:d.max},precision:r?.Precision}:c;case"money":{if(!df(d.min)||!df(d.max))return c;let f={min:d.min,max:d.max};switch(r?.PrecisionSource){case 0:return oh(r.Precision)?{column:{logicalName:t,kind:n,precisionSource:"column"},facts:f,precision:r.Precision}:c;case 1:return o===void 0?c:{column:{logicalName:t,kind:n,precisionSource:"organization"},facts:f,precision:o};case 2:return{column:{logicalName:t,kind:n,precisionSource:"currency"},facts:f,perRowCurrency:!0};default:return c}}case"boolean":return{column:{logicalName:t,kind:n},facts:{}};case"dateTime":{let f=(a=r?.DateTimeBehavior)===null||a===void 0?void 0:a.Value;return f==="UserLocal"||f==="DateOnly"||f==="TimeZoneIndependent"?{column:{logicalName:t,kind:n,dateTimeBehavior:f},facts:{}}:c}case"choice":case"state":case"status":case"multiSelect":{let f=(s=r?.OptionSet)===null||s===void 0?void 0:s.Options,p=Array.isArray(f)?f.map(m=>m?.Value):[];return p.length>0&&p.every(m=>Number.isInteger(m))?{column:{logicalName:t,kind:n},facts:{options:p}}:c}case"lookup":{let f=r?.Targets;if(!Array.isArray(f)||f.length===0||!f.every(y=>typeof y=="string"))return c;if(f.length>1)return{issue:"invalidLookupTarget"};let p=f[0],m=(u=i.get(t))===null||u===void 0?void 0:u.get(p);if(m===void 0||!/^[A-Za-z_][A-Za-z0-9_]*$/.test(m))return c;let h=`/EntityDefinitions(LogicalName='${(0,Si.odataPathLiteral)(p)}')${(0,Si.odataQuery)([["$select","EntitySetName"]])}`,g=(l=(await Jl(e,"the lookup target",h)).body)===null||l===void 0?void 0:l.EntitySetName;return typeof g!="string"||!/^[A-Za-z_][A-Za-z0-9_]*$/.test(g)?c:{column:{logicalName:t,kind:n,lookupTarget:{table:p,entitySetName:g,navigationProperty:m}},facts:{}}}default:return{issue:"unsupportedType"}}}function ZI(e,t){let n=e[t];if(!(0,Wt.isGuid)(n))throw new Qe.DataFixError("DATA_FIX_READ_FAILED","Reading the rows for the data fix returned a row without a readable id.",200);return n.toLowerCase()}function y8(e,t){let n=[...e===void 0?[]:[`odata.maxpagesize=${e}`],...t?[`odata.include-annotations="${p8}"`]:[]];return n.length===0?void 0:{headers:{Prefer:n.join(",")}}}async function ONe(e,t,n,r,i,o){let a=new Map,s=new Set,u=`/${t.entitySetName}${(0,Si.odataQuery)([["$select",n.join(",")],["$filter",r]])}`,l;for(;;){let c=y8(Math.min(i+1-a.size,mNe),o),d=l,f=d===void 0?await Jl(e,"the rows",u,c):await XI("the rows",()=>e.getAbsolute(d,c),d);for(let m of pf(f,"the rows")){let h=ZI(m,t.primaryIdAttribute);a.has(h)||a.set(h,m)}if(a.size>i)throw new Qe.DataFixError("DATA_FIX_TOO_MANY_ROWS",`The filter selects more than ${i} rows of '${t.logicalName}'; narrow it or raise maxRows (at most ${Ru}).`,void 0,void 0,i);let p=(0,YI.pageEnd)(f.body);if(p.kind==="end")return[...a.values()];if(p.kind==="incomplete"||s.has(p.link))throw new Qe.DataFixError("DATA_FIX_READ_FAILED",p.kind==="incomplete"&&p.cause==="claim"?"Reading the rows for the data fix returned a page that says more rows exist and gives no next link.":"Reading the rows for the data fix returned a malformed next link.",f.status);s.add(p.link),l=p.link}}function b8(e,t){return`Microsoft.Dynamics.CRM.In(PropertyName='${e}',PropertyValues=[${t.map(n=>`'${n}'`).join(",")}])`}async function DNe(e,t,n,r,i){let o=new Map;for(let a=0;a<r.length;a+=Wb){let s=r.slice(a,a+Wb),u=`/${t.entitySetName}${(0,Si.odataQuery)([["$select",n.join(",")],["$filter",b8(t.primaryIdAttribute,s)]])}`,l=await Jl(e,"the rows",u,y8(void 0,i));if((0,YI.pageEnd)(l.body).kind!=="end")throw new Qe.DataFixError("DATA_FIX_READ_FAILED","Reading the rows for the data fix returned a partial page.",l.status);for(let c of pf(l,"the rows"))o.set(ZI(c,t.primaryIdAttribute),c)}return o}async function PNe(e,t){let n=new Map;for(let r=0;r<t.length;r+=ff){let i=t.slice(r,r+ff).map(a=>`transactioncurrencyid eq ${a}`).join(" or "),o=`/transactioncurrencies${(0,Si.odataQuery)([["$select","transactioncurrencyid,currencyprecision"],["$filter",i]])}`;try{for(let a of pf(await Jl(e,"the currency precision",o),"the currency precision"))(0,Wt.isGuid)(a.transactioncurrencyid)&&oh(a.currencyprecision)&&n.set(a.transactioncurrencyid.toLowerCase(),a.currencyprecision)}catch{}}return n}async function RNe(e,t){var n,r,i,o,a;let s=CNe(t),u=QI(e),l=await g8(u,s.table),{planned:c,issues:d}=await NNe(u,l,s.columnNames),f=s.set?[s.set]:((n=s.rows)!==null&&n!==void 0?n:[]).map(S=>S.set);for(let S of f)if(Object.prototype.hasOwnProperty.call(S,ANe))for(let R of Object.keys(S))!((r=c.get(R))===null||r===void 0)&&r.perRowCurrency&&!d.has(R)&&d.set(R,"changesWithCurrency");for(let S of f)for(let[R,x]of Object.entries(S)){let G=c.get(R);if(G&&!d.has(R)){let U=(0,Wt.validateRequested)(G.column,G.facts,x,G.precision);U&&d.set(R,U)}}if(d.size>0)throw new Qe.DataFixColumnsInvalidError(s.columnNames.filter(S=>d.has(S)).map(S=>({column:S,reason:d.get(S)})));let p=s.columnNames.map(S=>c.get(S)),m=p.some(S=>S.perRowCurrency),h=p.some(S=>S.column.kind==="lookup"),g=[...new Set([l.primaryIdAttribute,l.primaryNameAttribute,...p.map(S=>(0,Wt.readKey)(S.column)),...m?["_transactioncurrencyid_value"]:[]])],y,b=[],E=new Map(((i=s.rows)!==null&&i!==void 0?i:[]).map(S=>[S.id,S]));if(s.filter!==void 0)y=await ONe(u,l,g,s.filter,s.maxRows,h);else{let S=await DNe(u,l,g,[...E.keys()],h);y=[];for(let R of E.keys()){let x=S.get(R);x?y.push(x):b.push(R)}}let w=m?[...new Set(y.map(S=>S._transactioncurrencyid_value).filter(Wt.isGuid).map(S=>S.toLowerCase()))]:[],_=w.length>0?await PNe(u,w):new Map,I=[],T=[],O=[],v=[],N=new Set;for(let S of y){let R=ZI(S,l.primaryIdAttribute),x=S["@odata.etag"];if(!(0,Bo.isVersionToken)(x)||/[\u0000-\u001F\u007F]/.test(x)){O.push({id:R,column:"@odata.etag",reason:"unsafeValue"});continue}let G=E.get(R);if(G?.etag!==void 0&&G.etag!==x){v.push(R);continue}let U=(o=s.set)!==null&&o!==void 0?o:G?.set,M=(0,Wt.isGuid)(S._transactioncurrencyid_value)?S._transactioncurrencyid_value.toLowerCase():void 0,q={},X={},ye={},Ve;for(let[wt,Fn]of Object.entries(U)){let xe=c.get(wt),Et=(0,Wt.isNumericKind)(xe.column.kind),zt=Et?(a=xe.precision)!==null&&a!==void 0?a:M?_.get(M):void 0:void 0;if(Et&&zt===void 0){Ve={id:R,column:wt,reason:"precisionUnknown"};break}let Ht=(0,Wt.decodeValue)(xe.column,S,zt);if(!Ht.ok){Ve={id:R,column:wt,reason:Ht.reason};break}if(xe.perRowCurrency&&(0,Wt.validateRequested)(xe.column,xe.facts,Fn,zt)!==void 0){Ve={id:R,column:wt,reason:"invalidValue"};break}(0,Wt.sameValue)(xe.column,Ht.value,Fn,zt)||(q[wt]=Ht.value,X[wt]=kNe(xe.column,Fn),Et&&(ye[wt]=zt))}if(Ve){O.push(Ve);continue}if(Object.keys(X).length===0){T.push(R);continue}Object.keys(X).forEach(wt=>N.add(wt));let _e=S[l.primaryNameAttribute];I.push({id:R,etag:x,name:typeof _e=="string"?_e:null,...Object.keys(ye).length>0?{numericPrecision:ye}:{},before:q,after:X})}return{kind:"dataFixPlan",version:1,planId:(0,f8.newId)(),createdAt:(0,Bo.nowIso)(),instanceUrl:h8(e),table:{logicalName:l.logicalName,entitySetName:l.entitySetName,primaryIdAttribute:l.primaryIdAttribute,primaryNameAttribute:l.primaryNameAttribute},selection:s.filter!==void 0?{by:"filter",filter:s.filter,maxRows:s.maxRows,matched:y.length}:{by:"rows",requested:E.size},columns:p.filter(S=>N.has(S.column.logicalName)).map(S=>S.column),rows:I,unchanged:T,excluded:O,missing:b,staleSinceRead:v}}ku.planDataFix=RNe;function kNe(e,t){if(e.kind==="lookup"&&t!==null&&typeof t=="object"&&!Array.isArray(t)){let n=t;return{table:n.table,id:n.id.toLowerCase()}}return Array.isArray(t)?[...t]:t}var l8=(e,t,n)=>Number.isInteger(e)&&e>=t&&e<=n;function $Ne(e){var t,n;if(e!==void 0&&!Qn(e))throw new Qe.InvalidArgumentError("applyDataFix options must be an object");let r=(t=e?.batchSize)!==null&&t!==void 0?t:hNe;if(!l8(r,1,o8))throw new Qe.InvalidArgumentError(`applyDataFix \`batchSize\` must be an integer 1..${o8}`);let i=(n=e?.maxThrottleWaitMs)!==null&&n!==void 0?n:bNe;if(!l8(i,0,a8))throw new Qe.InvalidArgumentError(`applyDataFix \`maxThrottleWaitMs\` must be an integer 0..${a8}`);return{batchSize:r,maxThrottleWaitMs:i}}function rn(e,t){return new Qe.DataFixError("DATA_FIX_PLAN_INVALID",`The data fix plan is invalid at ${e}: ${t}.`,void 0,e)}function JI(e,t){if(e===null||typeof e=="string"||typeof e=="boolean")return e;if(typeof e=="number"){if(!Number.isFinite(e))throw rn(t,"a number that is not finite");return e}if(Array.isArray(e))return e.map((n,r)=>JI(n,`${t}[${r}]`));if(Qn(e)){let n={};for(let r of Object.keys(e))Object.defineProperty(n,r,{value:JI(e[r],t===""?r:`${t}.${r}`),enumerable:!0,writable:!0,configurable:!0});return n}throw rn(t===""?"plan":t,"not a JSON value")}var LNe=new Set(["string","memo","integer","decimal","double","money","boolean","choice","state","status","multiSelect","dateTime","lookup"]);function MNe(e,t){let n=JI(e,"");if(!Qn(n)||n.kind!=="dataFixPlan")throw rn("kind","not 'dataFixPlan'");if(n.version!==1)throw rn("version","not 1");if(typeof n.planId!="string")throw rn("planId","not a string");if(n.instanceUrl!==t)throw new Qe.DataFixError("DATA_FIX_PLAN_OTHER_ORG","The data fix plan was read from another org; plan again on this one.");let r=n.table;for(let a of["logicalName","entitySetName","primaryIdAttribute","primaryNameAttribute"])if(!Qn(r)||!Kl(r[a]))throw rn(`table.${a}`,"not an OData name");if(!Qn(n.selection)||!["filter","rows","revert"].includes(String(n.selection.by)))throw rn("selection","not a selection");if(!Array.isArray(n.columns))throw rn("columns","not an array");let i=new Map;if(n.columns.forEach((a,s)=>{let u=a;if(!Qn(u)||!Kl(u.logicalName)||i.has(u.logicalName))throw rn(`columns[${s}].logicalName`,"not a distinct OData name");if(!LNe.has(String(u.kind)))throw rn(`columns[${s}].kind`,"not a kind a data fix writes");if(u.kind==="dateTime"&&!["UserLocal","DateOnly","TimeZoneIndependent"].includes(String(u.dateTimeBehavior)))throw rn(`columns[${s}].dateTimeBehavior`,"not a measured behaviour");if(u.kind==="lookup"){let l=u.lookupTarget;if(!Qn(l)||!Kl(l.table)||!Kl(l.entitySetName)||!Kl(l.navigationProperty))throw rn(`columns[${s}].lookupTarget`,"not a lookup target of OData names")}i.set(u.logicalName,u)}),!Array.isArray(n.rows)||n.rows.length>Ru)throw rn("rows",`not an array of at most ${Ru} rows`);let o=new Set;return n.rows.forEach((a,s)=>{let u=a,l=`rows[${s}]`;if(!Qn(u)||!(0,Wt.isGuid)(u.id))throw rn(`${l}.id`,"not a GUID");if(o.has(u.id.toLowerCase()))throw rn(`${l}.id`,"repeats an earlier row");if(o.add(u.id.toLowerCase()),!(0,Bo.isVersionToken)(u.etag)||/[\u0000-\u001F\u007F]/.test(u.etag))throw rn(`${l}.etag`,"not a row version token");if(u.name!==null&&typeof u.name!="string")throw rn(`${l}.name`,"not a string or null");let c=u.after;if(!Qn(c)||Object.keys(c).length===0||!Object.keys(c).every(m=>i.has(m)))throw rn(`${l}.after`,"not an object of planned columns");let d=u.before,f=Object.keys(c).sort().join(",");if(!Qn(d)||Object.keys(d).sort().join(",")!==f)throw rn(`${l}.before`,"not the same columns as after");let p=u.numericPrecision;for(let m of Object.keys(c)){let h=i.get(m),g;if((0,Wt.isNumericKind)(h.kind)&&(g=Qn(p)?p[m]:void 0,!oh(g)))throw rn(`${l}.numericPrecision.${m}`,"not an integer 0..10");if(!(0,Wt.hasPlanShape)(h,c[m],g))throw rn(`${l}.after.${m}`,`not a ${h.kind} value`);if(!(0,Wt.hasPlanShape)(h,d[m],g))throw rn(`${l}.before.${m}`,`not a ${h.kind} value`)}}),n}function xNe(e){var t;let n=(t=e.body)===null||t===void 0?void 0:t.error;return{...typeof n?.code=="string"?{code:n.code}:{},...typeof n?.message=="string"?{message:n.message}:{}}}function FNe(e,t,n,r){var i;let o=p=>({id:e.id,status:"applied",verification:"unverified",revertible:!1,diagnostic:p}),a=t.body;if(!Qn(a))return o("echoMissing");let s=a[r];if(!(0,Wt.isGuid)(s)||s.toLowerCase()!==e.id.toLowerCase())return o("echoIdentityMismatch");let u={};for(let p of Object.keys(e.after)){let m=(0,Wt.decodeValue)(n.get(p),a,(i=e.numericPrecision)===null||i===void 0?void 0:i[p]);if(!m.ok)return o(m.reason==="incompleteRead"?"echoFieldMissing":"echoValueUnsafe");u[p]=m.value}let l=a["@odata.etag"],c=m8(t.headers,"etag");if(!(0,Bo.isVersionToken)(l)||/[\u0000-\u001F\u007F]/.test(l)||c!==void 0&&c!==l)return o("echoTokenMissing");let d=Object.keys(e.after),f=(p,m)=>{var h;return(0,Wt.sameValue)(n.get(p),u[p],m[p],(h=e.numericPrecision)===null||h===void 0?void 0:h[p])};return{id:e.id,status:"applied",verification:d.every(p=>f(p,e.after))?"asPlanned":"notAsPlanned",revertible:d.some(p=>!f(p,e.before)),etag:l,stored:u}}function UNe(e,t,n,r){var i;if(t===void 0)return{kind:"outcome",outcome:{id:e.id,status:"unknown"}};let o=t.status,a={id:e.id,httpStatus:o,...xNe(t)};if(o>=200&&o<300)return{kind:"outcome",outcome:FNe(e,t,n,r)};if(o===412)return{kind:"outcome",outcome:{...a,status:"conflict"}};let s=(i=a.code)===null||i===void 0?void 0:i.toLowerCase();return o===400&&s===wNe||o===404&&s===ENe?{kind:"gone?",outcome:{...a,status:"failed"}}:(0,Bo.isServiceProtectionRefusal)(t)?{kind:"throttled",delayMs:(0,Bo.throttleDelayMs)(t)}:o>=400&&o<500?{kind:"outcome",outcome:{...a,status:"failed"}}:{kind:"outcome",outcome:{...a,status:"unknown"}}}function qNe(e,t,n){let i=Object.keys(e.after).map(u=>t.get(u)),o=[n.primaryIdAttribute,...i.map(Wt.readKey)].join(","),a=Object.assign({},...i.map(u=>(0,Wt.encodeValue)(u,e.after[u.logicalName]))),s=i.some(u=>u.kind==="lookup")?`return=representation,odata.include-annotations="${p8}"`:"return=representation";return{method:"PATCH",path:`/${n.entitySetName}(${e.id.toLowerCase()})?$select=${o}`,body:a,etag:e.etag,headers:{Prefer:s}}}function c8(e){let t=0;for(let n=0;n<e.length;n+=1){let r=e.charCodeAt(n);r<128?t+=1:r<2048?t+=2:r>=55296&&r<=56319?(t+=4,n+=1):t+=3}return t}function BNe(e){return c8(JSON.stringify(e.body))+c8(e.path)+yNe}function VNe(e){var t;let n=(t=m8(e.headers,"content-type"))!==null&&t!==void 0?t:"";return/^multipart\//i.test(n)||typeof e.body=="string"&&e.body.trimStart().startsWith("--")}function GNe(e){return new Promise(t=>setTimeout(t,e))}async function jNe(e,t){let{body:n,batchId:r,contentIds:i}=(0,zI.renderChangeSets)(e,t),o;try{o=await e.postBatch(n,r,{headers:{Prefer:"odata.continue-on-error"}})}catch{return{kind:"unknown",status:0}}let a=(0,zI.parseChangeSetsParts)(o.body,i);if(a){let s=new Map(a.map(u=>[u.contentId,(0,zI.partResponse)(u)]));return{kind:"rows",responses:i.map(u=>s.get(u))}}return(0,Bo.isServiceProtectionRefusal)(o)?{kind:"throttled",delayMs:(0,Bo.throttleDelayMs)(o)}:(o.status===401||o.status===403)&&!VNe(o)?{kind:"access",status:o.status}:{kind:"unknown",status:o.status}}async function WNe(e,t){var n;try{return{kind:"rows",responses:[await e.patch(t.path,t.body,{headers:{"If-Match":t.etag,...(n=t.headers)!==null&&n!==void 0?n:{}}})]}}catch{return{kind:"unknown",status:0}}}async function zNe(e,t,n){let r=[];for(let i=0;i<n.length;i+=Wb){let o=n.slice(i,i+Wb),a=new Set(o.map(u=>u.id.toLowerCase())),s;try{let u=`/${t.entitySetName}${(0,Si.odataQuery)([["$select",t.primaryIdAttribute],["$filter",b8(t.primaryIdAttribute,[...a])]])}`,l=await e.get(u),c=l.body,d=c?.value;l.status===200&&Array.isArray(d)&&(0,YI.pageEnd)(c).kind==="end"&&d.every(f=>Qn(f)&&(0,Wt.isGuid)(f[t.primaryIdAttribute])&&a.has(f[t.primaryIdAttribute].toLowerCase()))&&(s=new Set(d.map(f=>f[t.primaryIdAttribute].toLowerCase())))}catch{s=void 0}for(let u of o)s===void 0?r.push({...u,status:"failed",diagnostic:"absenceNotConfirmed"}):r.push({...u,status:s.has(u.id.toLowerCase())?"failed":"gone"})}return r}var HNe={DATA_FIX_REQUEST_UNKNOWN_OUTCOME:"A request ended without a readable answer, so whether its rows were written is unknown; the rest was not sent. Plan again: rows that did apply read back at their target values.",DATA_FIX_ACCESS_REFUSED:"The service refused the request before running it (authentication or authorization); the rest was not sent. Restore access and apply `remaining`.",DATA_FIX_THROTTLE_BUDGET_EXHAUSTED:"Service protection kept refusing the requests and the next wait would exceed the throttle budget; the rest was not sent. Apply `remaining` later.",DATA_FIX_REQUEST_NOT_SENT:"A request could not be built, so it and the rest were not sent."};async function KNe(e,t,n){let r=$Ne(n),i=MNe(t,h8(e)),o=QI(e);await g8(o,i.table.logicalName);let a=new Map(i.columns.map(b=>[b.logicalName,b])),s=i.table.primaryIdAttribute,u=new Map,l=[],c=[...i.rows],d=!e.supportsAtomicBatch,f=0,p=0,m=0,h,g=(b,E)=>{h={code:b,...E?{httpStatus:E}:{},message:HNe[b]}},y=b=>u.set(b.id,{id:b.id,status:"notAttempted"});for(;c.length>0&&h===void 0;){let b=[],E=[],w=0;for(;c.length>0&&b.length<(d?1:r.batchSize);){let O=qNe(c[0],a,i.table),v=BNe(O);if(b.length>0&&w+v>gNe)break;b.push(c.shift()),E.push(O),w+=v}let _;try{_=d?await WNe(e,E[0]):await jNe(e,E)}catch{b.forEach(y),g("DATA_FIX_REQUEST_NOT_SENT");break}let I=[],T=0;if(_.kind==="rows")b.forEach((O,v)=>{let N=UNe(O,_.kind==="rows"?_.responses[v]:void 0,a,s);N.kind==="throttled"?(I.push(O),T=Math.max(T,N.delayMs)):N.kind==="gone?"?l.push(N.outcome):u.set(O.id,N.outcome)});else if(_.kind==="throttled")I=b,T=_.delayMs;else if(_.kind==="access")b.forEach(y),g("DATA_FIX_ACCESS_REFUSED",_.status);else{let O=_.status;b.forEach(v=>u.set(v.id,{id:v.id,status:"unknown",...O?{httpStatus:O}:{}})),g("DATA_FIX_REQUEST_UNKNOWN_OUTCOME",O)}I.length>0&&(m>=vNe||p+T>r.maxThrottleWaitMs?(I.forEach(y),g("DATA_FIX_THROTTLE_BUDGET_EXHAUSTED")):(await GNe(T),p+=T,f+=1,m+=1,c.unshift(...I)))}c.forEach(y);for(let b of await zNe(o,i.table,l))u.set(b.id,b);return JNe(i,a,u,{waits:f,waitedMs:p},h)}ku.applyDataFix=KNe;function d8(e,t,n){let r=new Set(t.flatMap(i=>Object.keys(i.after)));return{...e,planId:(0,f8.newId)(),columns:e.columns.filter(i=>r.has(i.logicalName)),rows:t,unchanged:[],excluded:[],missing:[],staleSinceRead:[],...n}}function HI(e,t){return Object.fromEntries(t.map(n=>[n,e[n]]))}function JNe(e,t,n,r,i){let o=e.rows.map(c=>{var d;return(d=n.get(c.id))!==null&&d!==void 0?d:{id:c.id,status:"unknown"}}),a={applied:0,conflict:0,gone:0,failed:0,unknown:0,notAttempted:0},s={asPlanned:0,notAsPlanned:0,unverified:0};o.forEach(c=>{a[c.status]+=1,c.verification&&(s[c.verification]+=1)});let u=e.rows.filter(c=>{var d;return((d=n.get(c.id))===null||d===void 0?void 0:d.status)==="notAttempted"}),l=[];for(let c of e.rows){let d=n.get(c.id);if(d?.status!=="applied"||!d.revertible||!d.stored||!d.etag)continue;let f=d.stored,p=Object.keys(c.after).filter(h=>{var g;return!(0,Wt.sameValue)(t.get(h),f[h],c.before[h],(g=c.numericPrecision)===null||g===void 0?void 0:g[h])}),m=c.numericPrecision?HI(c.numericPrecision,p.filter(h=>{var g;return h in((g=c.numericPrecision)!==null&&g!==void 0?g:{})})):{};l.push({id:c.id,etag:d.etag,name:c.name,...Object.keys(m).length>0?{numericPrecision:m}:{},before:HI(f,p),after:HI(c.before,p)})}return{planId:e.planId,complete:a.notAttempted===0&&a.unknown===0,counts:a,verification:s,outcomes:o,remaining:u.length>0?d8(e,u,{}):null,revert:l.length>0?d8(e,l,{createdAt:(0,Bo.nowIso)(),selection:{by:"revert",ofPlanId:e.planId}}):null,throttle:r,...i?{stoppedBy:i}:{}}}});var D8=C(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 N8=Ke(),Vo=pe(),Xn=ae(),Jr=Y(),zb={read:"Read",create:"Create",write:"Write",delete:"Delete",append:"Append",appendTo:"AppendTo",assign:"Assign",share:"Share"},tT={user:"Basic",businessUnit:"Local",parentChild:"Deep",organization:"Global"},w8={user:1,businessUnit:2,parentChild:3,organization:4},eT={user:"CanBeBasic",businessUnit:"CanBeLocal",parentChild:"CanBeDeep",organization:"CanBeGlobal"};Or.SDK_ROLE_MARKER="Authored by @maker-studio/cds-maker-sdk (persona/security role).";function YNe(e){return Object.prototype.hasOwnProperty.call(zb,e)?zb[e]:void 0}function QNe(e){return Object.prototype.hasOwnProperty.call(tT,e)}var E8=new WeakMap,A8=new WeakMap;async function _8(e,t){var n,r;(0,Xn.assertODataName)(t,"entity logical name");let i=E8.get(e);i||(i=new Map,E8.set(e,i));let o=i.get(t);if(o)return o;let a=`/EntityDefinitions(LogicalName='${(0,Xn.odataPathLiteral)(t)}')${(0,Xn.odataQuery)([["$select","LogicalName,Privileges"]])}`,u=(r=(n=(0,Vo.ensureSuccess)(await e.get(a),e.apiUrl(a)).body)===null||n===void 0?void 0:n.Privileges)!==null&&r!==void 0?r:[];if(u.length===0)throw new Jr.InvalidArgumentError(`Entity '${t}' exposes no privileges (unknown or non-securable entity).`);return i.set(t,u),u}async function XNe(e){var t,n,r;let i=A8.get(e);if(i)return i;let o=`/businessunits${(0,Xn.odataQuery)([["$select","businessunitid"],["$filter","_parentbusinessunitid_value eq null"],["$top",1]])}`,u=(r=((n=(t=(0,Vo.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||t===void 0?void 0:t.value)!==null&&n!==void 0?n:[])[0])===null||r===void 0?void 0:r.businessunitid;if(!u)throw new Jr.InvalidArgumentError("Could not resolve the root business unit.");let l=(0,Xn.normalizeGuid)(u,"businessUnitId");return A8.set(e,l),l}async function I8(e,t){var n;let r=new Map;for(let i of t){if(!i.access||i.access.length===0)throw new Jr.InvalidArgumentError(`Entity '${i.entity}' privilege request has no access levels.`);let o=(n=i.scope)!==null&&n!==void 0?n:"user";if(!QNe(o))throw new Jr.InvalidArgumentError(`Unknown privilege scope '${o}' for entity '${i.entity}'.`);let a=await _8(e,i.entity);for(let s of i.access){let u=YNe(s);if(!u)throw new Jr.InvalidArgumentError(`Unknown access level '${s}' for entity '${i.entity}'.`);let l=a.find(m=>m.PrivilegeType===u);if(!l)throw new Jr.InvalidArgumentError(`Entity '${i.entity}' does not support '${s}' access.`);let c=eT[o];if(l[c]===!1)throw new Jr.InvalidArgumentError(`Privilege '${l.Name}' on '${i.entity}' does not support the '${o}' scope.`);let d=(0,Xn.normalizeGuid)(l.PrivilegeId,"PrivilegeId"),f=r.get(d);if(!f){r.set(d,{privilegeName:l.Name,privilegeType:u,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 Jr.InvalidArgumentError(`Entities '${m}' and '${i.entity}' share the Dataverse privilege '${l.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=w8[o]>w8[f.scope]?o:f.scope}}return[...r.entries()].map(([i,o])=>({entity:[...o.entities].sort().join(", "),privilegeId:i,privilegeName:o.privilegeName,privilegeType:o.privilegeType,scope:o.scope}))}async function ZNe(e,t,n,r){if(n.length===0&&!r)return;let i={Privileges:n.map(a=>({Depth:tT[a.scope],PrivilegeId:a.privilegeId}))},o=`/roles(${t})/Microsoft.Dynamics.CRM.ReplacePrivilegesRole`;(0,Vo.ensureSuccess)(await e.post(o,i),e.apiUrl(o))}async function C8(e,t,n,r,i){var o,a;let s=`/${t}(${n})/${r}${(0,Xn.odataQuery)([["$select","roleid"],["$filter",`roleid eq ${i}`]])}`,u=(0,Vo.ensureSuccess)(await e.get(s),e.apiUrl(s)),l=(a=(o=u.body)===null||o===void 0?void 0:o.value)!==null&&a!==void 0?a:[];if(!(0,N8.boundedPageComplete)(u.body,l.length))throw new Jr.ConnectionError(e.apiUrl(s),u.status,"the role membership read answered no row but says more rows exist, so whether the role is held is unknown");return l.length>0}async function e_e(e,t,n){var r,i;let o=[],a=[],s={"@odata.id":e.apiUrl(`/roles(${t})`)};for(let u of(r=n?.teams)!==null&&r!==void 0?r:[]){let l=(0,Xn.normalizeGuid)(u,"teamId");if(!await C8(e,"teams",l,"teamroles_association",t)){let c=`/teams(${l})/teamroles_association/$ref`;(0,Vo.ensureSuccess)(await e.post(c,s),e.apiUrl(c))}o.push(l)}for(let u of(i=n?.users)!==null&&i!==void 0?i:[]){let l=(0,Xn.normalizeGuid)(u,"userId");if(!await C8(e,"systemusers",l,"systemuserroles_association",t)){let c=`/systemusers(${l})/systemuserroles_association/$ref`;(0,Vo.ensureSuccess)(await e.post(c,s),e.apiUrl(c))}a.push(l)}return{teams:o,users:a}}async function S8(e,t,n){var r,i;let o=`/roles${(0,Xn.odataQuery)([["$select","roleid,description,ismanaged"],["$filter",`name eq '${(0,Xn.odataLiteral)(t)}' and _businessunitid_value eq ${n}`]])}`,a=(0,Vo.ensureSuccess)(await e.get(o),e.apiUrl(o)),s=(i=(r=a.body)===null||r===void 0?void 0:r.value)!==null&&i!==void 0?i:[];if((0,N8.pageEnd)(a.body).kind!=="end")throw new Jr.ConnectionError(e.apiUrl(o),a.status,`the read of the roles named '${t}' says more rows exist, so whether a role the SDK does not own shares the name is unknown`);let u=s.filter(d=>!!d.roleid);if(u.length===0)return;let l=d=>{var f;return d.ismanaged!==!0&&((f=d.description)!==null&&f!==void 0?f:"")===Or.SDK_ROLE_MARKER};if(u.some(d=>!l(d)))throw new Jr.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(u.length>1)throw new Jr.InvalidArgumentError(`Multiple (${u.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=u[0].roleid;return c?(0,Xn.normalizeGuid)(c,"roleId"):void 0}function t_e(e){var t,n;return{teams:((t=e?.teams)!==null&&t!==void 0?t:[]).map(r=>(0,Xn.normalizeGuid)(r,"teamId")),users:((n=e?.users)!==null&&n!==void 0?n:[]).map(r=>(0,Xn.normalizeGuid)(r,"userId"))}}function T8(e){return e.map(t=>({entity:t.entity,privilegeName:t.privilegeName,privilegeType:t.privilegeType,scope:t.scope}))}async function O8(e,t){var n,r;let i=(n=t.name)===null||n===void 0?void 0:n.trim();if(!i)throw new Jr.InvalidArgumentError("createSecurityRole: a non-empty role name is required.");let o=t.businessUnitId?(0,Xn.normalizeGuid)(t.businessUnitId,"businessUnitId"):await XNe(e),a=await I8(e,(r=t.privileges)!==null&&r!==void 0?r:[]),s=t_e(t.assignTo),u=await S8(e,i,o),l=u!==void 0;if(!u){let d="/roles",f={name:i,description:Or.SDK_ROLE_MARKER,"[email protected]":`/businessunits(${o})`};try{let p=(0,Vo.ensureSuccess)(await e.post(d,f),e.apiUrl(d));u=(0,Xn.normalizeGuid)((0,Vo.requireCreatedId)(p,"roleid","role"),"roleId")}catch(p){let m;try{m=await S8(e,i,o)}catch{m=void 0}if(!m)throw p;u=m}}await ZNe(e,u,a,l);let c=await e_e(e,u,s);return{roleId:u,name:i,reused:l,appliedPrivileges:T8(a),assignedTeams:c.teams,assignedUsers:c.users}}Or.createSecurityRole=O8;async function n_e(e,t){var n,r;let i=(n=t.persona)===null||n===void 0?void 0:n.trim();if(!i)throw new Jr.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:[]}),...(r=t.additionalPrivileges)!==null&&r!==void 0?r:[]];return O8(e,{name:i,businessUnitId:t.businessUnitId,privileges:o,assignTo:t.assignTo})}Or.createPersonaRole=n_e;async function r_e(e,t){let r=`/roles(${(0,Xn.normalizeGuid)(t,"roleId")})`;(0,Vo.ensureSuccess)(await e.delete(r),e.apiUrl(r))}Or.deleteSecurityRole=r_e;async function i_e(e,t,n){let r=(0,Xn.normalizeGuid)(t,"roleId");if(n.length===0)throw new Jr.InvalidArgumentError("addEntityPrivilegesToRole requires at least one entity privilege (an empty grant would be a silent no-op).");let i=await I8(e,n),o={Privileges:i.map(s=>({Depth:tT[s.scope],PrivilegeId:s.privilegeId}))},a=`/roles(${r})/Microsoft.Dynamics.CRM.AddPrivilegesRole`;return(0,Vo.ensureSuccess)(await e.post(a,o),e.apiUrl(a)),T8(i)}Or.addEntityPrivilegesToRole=i_e;var o_e=new Map(Object.keys(zb).map(e=>[zb[e],e]));async function a_e(e,t){return(await _8(e,t)).map(r=>{let i=Object.keys(eT).filter(a=>r[eT[a]]!==!1),o=o_e.get(r.PrivilegeType);return{name:r.Name,privilegeId:r.PrivilegeId,privilegeType:r.PrivilegeType,...o?{access:o}:{},scopes:i}})}Or.getEntityPrivileges=a_e});var J8=C(Pr=>{"use strict";Object.defineProperty(Pr,"__esModule",{value:!0});Pr.createMakerSdk=Pr.MakerSdk=Pr.PUSH_NOT_ATTEMPTED_CODE=Pr.ALREADY_EXISTS_CODE=void 0;var P8=Mv(),R8=mo(),le=Y(),co=ec(),s_e=eD(),W8=sD(),mf=pD(),u_e=Fv(),k8=$D(),l_e=aw(),nT=hk(),hf=wk(),c_e=$k(),d_e=vE(),$8=g$(),L8=AA(),f_e=sM(),p_e=Ya(),M8=mM(),Zn=u0(),m_e=VM(),rT=mg(),iT=KM(),Hb=Sc(),Ns=p0(),Kb=ZE(),gf=Ff(),h_e=h0(),x8=hA(),Mn=il(),g_e=Jc(),y_e=C0(),b_e=S0(),F8=gC(),v_e=Nw(),U8=_w(),w_e=j9(),Jb=ft(),E_e=fl(),Go=Eu(),fo=Rs(),oT=tI(),A_e=3e5,Dr=pe(),Yl=ae(),yf=QE(),q8=X9(),C_e=e8(),B8=v8(),S_e=IN(),ah=D8(),z8=Symbol("cds-maker-sdk.committedWrite");function N_e(e){return typeof e=="object"&&e!==null&&(e[z8]=!0),e}function __e(e){return typeof e=="object"&&e!==null&&e[z8]===!0}var I_e={fileConcurrency:1},aT="SOLUTION_COMPONENT_UNCLASSIFIED",T_e=2,O_e=4,D_e="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 sT(e){return{componentId:e.objectId,componentType:e.componentType,workflowCategory:e.workflowCategory,reason:"unsupported",...e.includesAllSubcomponents?{detail:D_e}:{}}}function sh(e,t){return{componentId:e.objectId,componentType:e.componentType,workflowCategory:e.workflowCategory,reason:"failed",error:$u(t)}}function V8(e,t,n){let r=n;return{type:e,id:t.objectId,name:typeof r.name=="string"?r.name:t.objectId,entityLogicalName:typeof r.entityLogicalName=="string"?r.entityLogicalName:void 0,lastFetched:(0,Dr.nowIso)(),isDirty:!1}}var P_e=new Set(["entity","appmodule","dashboard","uxagentproject"]);function R_e(e){var t;let n={entity:[],appmodule:[],dashboard:[],uxagentproject:[]},r=new Set,i=(s,u)=>{let l=`${s}\0${u.toLowerCase()}`;r.has(l)||(r.add(l),n[s].push(u))};for(let{scope:s}of e)if(s?.envelope==="entity")s.entityLogicalName&&i("entity",s.entityLogicalName);else if(s&&s.envelope!=="webresource")for(let u of(t=s.targetIds)!==null&&t!==void 0?t:[])i(s.envelope,u);let o=(s,u,l)=>l.length>0?`<${s}>${l.map(c=>`<${u}>${(0,Yl.xmlText)(c)}</${u}>`).join("")}</${s}>`:"",a=o("entities","entity",n.entity)+o("appmodules","appmodule",n.appmodule)+o("dashboards","dashboard",n.dashboard)+o("uxagentprojects","uxagentproject",n.uxagentproject);return a?`<importexportxml>${a}</importexportxml>`:void 0}function k_e(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 W8.WorkspaceManager(L_e,e.instanceUrl,(0,u_e.assertStorageContract)(t))}Pr.ALREADY_EXISTS_CODE="ARTIFACT_ALREADY_EXISTS";var $_e="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";Pr.PUSH_NOT_ATTEMPTED_CODE="PUSH_NOT_ATTEMPTED";var L_e="<injected workspaceStorage>",Qb=class e{constructor(t){var n,r;if(this.promotionIssued=new L8.IssuedPlans,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 le.InvalidArgumentError(`createRecovery must be 'adoptExact' or omitted (got '${String(t.createRecovery)}').`);this.createRecovery=t.createRecovery,this.readConcurrency=(0,oT.resolveReadConcurrency)(t.readConcurrency),this.genPageIteration=(0,F8.resolveGenPageIteration)(t.genPageIteration),this.languageCode=(n=t.languageCode)!==null&&n!==void 0?n:E_e.DEFAULT_LCID,this.cacheStalenessMs=(r=t.cacheStalenessMs)!==null&&r!==void 0?r:A_e,this.compiler={load:(0,F8.createGenPageTypeScriptLoader)(t.typescript)},this.workspace=k_e(t),this.versions=new mf.VersionManager(this.workspace),this.dataverse=new k8.DataverseClient(t.instanceUrl,t.httpClient,t.solutionUniqueName,this.readConcurrency),this.connectivity=new $8.ConnectivityRouter(this.dataverse,t.instanceUrl,{powerAppsServiceClient:t.powerAppsServiceClient,powerPlatformApiClient:t.powerPlatformApiClient,connectorRuntimeClient:t.connectorRuntimeClient}),this.registrations=(0,w_e.buildRegistrations)(this.languageCode),this.promotionConnectivity={instanceUrl:t.instanceUrl,clients:{powerAppsServiceClient:t.powerAppsServiceClient,powerPlatformApiClient:t.powerPlatformApiClient}}}async initWorkspace(){await this.workspace.init()}async getManifest(){return this.workspace.getManifest()}async cleanWorkspace(){await this.workspace.clean()}withArtifactLock(t,n,r){var i;let o=this.artifactKey(t,n),s=((i=this.artifactLocks.get(o))!==null&&i!==void 0?i:Promise.resolve()).then(r,r),u=s.then(()=>{},()=>{});return this.artifactLocks.set(o,u),u.then(()=>{this.artifactLocks.get(o)===u&&this.artifactLocks.delete(o)}),s}async fetchArtifact(t,n,r){return this.withArtifactLock(t,n,async()=>{let i=await this.fetchArtifactUnlocked(t,n,r);return await this.acknowledgeRefresh(t,n),i})}async fetchArtifactUnlocked(t,n,r){let i=this.requireRegistration(t,"fetchArtifact"),o=await i.api.get(this.dataverse,n);return this.applyFetchedArtifactUnlocked(t,n,i,o,r)}async applyFetchedArtifactUnlocked(t,n,r,i,o){var a,s,u;let{raw:l,etag:c,memberEtags:d,siblingEtags:f}=i,p=r.adapter.fromApiResponse(l);if(!o?.overwrite&&await this.versions.isDirty(t,n)){let h=(s=(a=await this.versions.getMeta(t,n))===null||a===void 0?void 0:a.etag)!==null&&s!==void 0?s:null;if(h&&c&&h!==c)throw new le.LocalEditsWouldBeLostError(t,n,h,c);let g=await this.workspace.readArtifact(t,n);if(g){let y=await this.versions.getMeta(t,n);if(y&&!y.etag&&c){if(!(0,fo.deepEqual)(y.snapshot,p))throw new le.LocalEditsWouldBeLostError(t,n,h,c);await this.versions.storeMeta(t,n,{...y,etag:c,fetchedAt:(0,Dr.nowIso)()},y)}return(0,Go.cloneJson)(g)}}await this.workspace.writeArtifact(t,n,p);let m=await this.versions.getMeta(t,n);return await this.versions.storeMeta(t,n,{etag:c,languageCode:this.languageCode,projectionVersion:mf.PROJECTION_VERSION,fetchedAt:(0,Dr.nowIso)(),snapshot:(0,Go.cloneJson)(p),...d?{memberEtags:d}:{},...f?{siblingEtags:f}:{},...m?.refreshGeneration?{refreshGeneration:m.refreshGeneration,observedGeneration:(u=m.observedGeneration)!==null&&u!==void 0?u:0}:{}},m),(0,Go.cloneJson)(p)}async fetchArtifactList(t,n){return this.requireRegistration(t,"fetchArtifactList").api.list(this.dataverse,n)}async fetchSolution(t){await this.workspace.ensureReady();let n=await(0,Mn.fetchSolutionComponents)(this.dataverse,t),r=[],i=[],o=await(0,g_e.foldVariableValueComponents)(this.dataverse,n);for(let{component:l,error:c}of o.failed)i.push(sh(l,c));let a=await(0,y_e.foldCustomApiChildComponents)(this.dataverse,o.components);for(let{component:l,error:c}of a.failed)i.push(sh(l,c));let s=await(0,b_e.foldDuplicateRuleConditionComponents)(this.dataverse,a.components);for(let{component:l,error:c}of s.failed)i.push(sh(l,c));for(let{component:l,detail:c}of s.orphaned)i.push({...sT(l),detail:c});let u=s.components;if(this.readConcurrency>1)await this.fetchComponentsOverlapped(u,r,i);else for(let l of u)try{let c=await this.resolveComponentType(l);if(!c){i.push(sT(l));continue}let d=await this.fetchArtifact(c,l.objectId);r.push(V8(c,l,d))}catch(c){i.push(sh(l,c))}return await this.workspace.updateManifest({lastSyncAt:(0,Dr.nowIso)()}),{summaries:r,skipped:i}}async fetchComponentsOverlapped(t,n,r){await(0,oT.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"){r.push(sT(o));return}let s=await this.applyFetchedArtifactUnlocked(a.type,o.objectId,a.reg,a.fetched);await this.acknowledgeRefresh(a.type,o.objectId),n.push(V8(a.type,o,s))}catch(a){r.push(sh(o,a))}})}async beginComponentRead(t){let n=await this.resolveComponentType(t);return n?this.lockedRead(n,t.objectId,async()=>{let r=this.requireRegistration(n,"fetchArtifact"),i=await r.api.get(this.dataverse,t.objectId,I_e);return{kind:"artifact",type:n,reg:r,fetched:i}}):(0,oT.plainRead)(async()=>({kind:"unsupported"}))}lockedRead(t,n,r){let i,o=new Promise(l=>{i=l}),a,s=new Promise(l=>{a=l}),u=this.withArtifactLock(t,n,async()=>{try{i({ok:!0,value:await r()})}catch(c){i({ok:!1,error:c})}let l=await s;await l?.()});return{outcome:o,finish:l=>(a(l),u),discard:async()=>{a(void 0),await u}}}async fetchEntityMetadata(t){return this.fetchEntityMetadataVia(t,this.dataverse)}async fetchEntityMetadataVia(t,n){let r=t.toLowerCase(),i=this.schemaEpoch(r),o=await(0,hf.fetchEntityMetadataFromApi)(n,t);if(this.schemaEpoch(r)!==i)return o;let a=this.workspace.writeEntityMetadata(t,o),s={key:r,settled:a.then(()=>{},()=>{})};this.metadataPublications.add(s);try{await a}finally{this.metadataPublications.delete(s)}return this.schemaEpoch(r)===i&&this.undroppedMetadata.delete(r),o}schemaEpoch(t){var n,r;return`${(n=this.schemaWrites.get("*"))!==null&&n!==void 0?n:0}:${(r=this.schemaWrites.get(t.toLowerCase()))!==null&&r!==void 0?r:0}`}async schemaWrite(t,n){try{return await n()}finally{await this.forgetEntityMetadata(t)}}async forgetEntityMetadata(t){let n=i=>{var o;this.schemaWrites.set(i,((o=this.schemaWrites.get(i))!==null&&o!==void 0?o:0)+1)};if(t===void 0){n("*"),await this.publicationsSettled(void 0),await this.dropCachedMetadata(void 0);return}let r=[...new Set(t.filter(i=>typeof i=="string"&&i!=="").map(i=>i.toLowerCase()))];r.forEach(n),await this.publicationsSettled(r);for(let i of r)await this.dropCachedMetadata(i)}async publicationsSettled(t){let n=t===void 0?void 0:new Set(t);await Promise.all([...this.metadataPublications].filter(r=>n===void 0||n.has(r.key)).map(r=>r.settled))}async dropCachedMetadata(t){try{await this.workspace.dropEntityMetadata(t)}catch(n){n instanceof le.WorkspaceNotInitializedError||n instanceof le.WorkspaceOrgMismatchError||this.undroppedMetadata.add(t??"*");return}t===void 0?this.undroppedMetadata.clear():this.undroppedMetadata.delete(t)}async readCachedEntityMetadata(t){let n=t.toLowerCase();return this.undroppedMetadata.has("*")&&await this.dropCachedMetadata(void 0),this.undroppedMetadata.has(n)&&await this.dropCachedMetadata(n),this.undroppedMetadata.has("*")||this.undroppedMetadata.has(n)?null:this.workspace.readEntityMetadata(t)}loadMissedEntityMetadata(t,n=this.dataverse){let r=this.schemaEpoch(t),i=this.entityMetadataLoads.get(t);if(i&&this.entityMetadataLoadEpochs.get(i)===r)return i;let o=this.fetchEntityMetadataVia(t,n).then(()=>{});this.entityMetadataLoads.set(t,o),this.entityMetadataLoadEpochs.set(o,r);let a=()=>{this.entityMetadataLoads.get(t)===o&&this.entityMetadataLoads.delete(t)};return o.then(a,a),o}generateGenPageRuntimeTypes(t,n){return(0,c_e.generateGenPageRuntimeTypes)(r=>this.fetchEntityMetadata(r),t,n)}findTables(t,n){return(0,hf.findTables)(this.dataverse,t,n)}getEnvironmentLanguages(){return(0,d_e.getEnvironmentLanguages)(this.dataverse)}listConnections(){return this.connectivity.listConnections()}listConnectorOperations(t){return this.connectivity.listConnectorOperations(t)}getConnectorOperationSchema(t,n){return this.connectivity.getConnectorOperationSchema(t,n)}listConnectorTables(t,n,r){return this.connectivity.listConnectorTables(t,n,r)}getConnectorTableSchema(t,n,r,i){return this.connectivity.getConnectorTableSchema(t,n,r,i)}findColumns(t,n,r){return(0,hf.findColumns)(this.dataverse,t,n,r)}createTable(t){return this.schemaWrite([t.schemaName],()=>(0,Zn.createTable)(this.dataverse,t))}createColumn(t,n){return this.schemaWrite([t],()=>(0,Zn.createColumn)(this.dataverse,t,n))}createColumns(t,n){return this.schemaWrite([t],()=>(0,Zn.createColumns)(this.dataverse,t,n))}updateColumn(t,n,r){return this.schemaWrite([t],()=>(0,Zn.updateColumn)(this.dataverse,t,n,r))}deleteColumn(t,n){return this.schemaWrite([t],()=>(0,Zn.deleteColumn)(this.dataverse,t,n))}setFormSecurityRoles(t,n){return(0,rT.setFormSecurityRoles)(this.dataverse,t,n)}getFormSecurityRoles(t){return(0,rT.getFormSecurityRoles)(this.dataverse,t)}setColumnVisualization(t,n,r){return(0,Zn.setColumnVisualization)(this.dataverse,t,n,r)}getColumnVisualization(t,n){return(0,Zn.getColumnVisualization)(this.dataverse,t,n)}createCustomerColumn(t,n){return this.schemaWrite([t,"account","contact"],()=>(0,Zn.createCustomerColumn)(this.dataverse,t,n))}insertStatusValue(t,n){return this.schemaWrite([t],()=>(0,Zn.insertStatusValue)(this.dataverse,t,n))}updateTable(t,n){return this.schemaWrite([t],()=>(0,Zn.updateTable)(this.dataverse,t,n))}async setEntityIcon(t,n){if(await this.schemaWrite([t],()=>(0,Zn.updateTable)(this.dataverse,t,{iconVectorName:n.vector,iconSmallName:n.small,iconMediumName:n.medium,iconLargeName:n.large})),n.publish!==!1){let r=`<importexportxml><entities><entity>${(0,Yl.xmlText)(t)}</entity></entities></importexportxml>`;(0,Dr.ensureSuccess)(await this.dataverse.post("/PublishXml",{ParameterXml:r}),this.dataverse.apiUrl("/PublishXml"))}}createAlternateKey(t,n){return(0,Zn.createAlternateKey)(this.dataverse,t,n)}deleteAlternateKey(t,n){return(0,Zn.deleteAlternateKey)(this.dataverse,t,n)}createRelationship(t){let n=t.type==="ManyToMany"?[t.entity1,t.entity2]:[t.referencedEntity,t.referencingEntity];return this.schemaWrite(n,()=>(0,Zn.createRelationship)(this.dataverse,t))}deleteRelationship(t){return this.schemaWrite(void 0,()=>(0,Zn.deleteRelationship)(this.dataverse,t))}createGlobalOptionSet(t){return(0,Zn.createGlobalOptionSet)(this.dataverse,t)}deleteGlobalOptionSet(t){return(0,Zn.deleteGlobalOptionSet)(this.dataverse,t)}deleteTable(t){return this.schemaWrite(void 0,()=>(0,Zn.deleteTable)(this.dataverse,t))}createSecurityRole(t){return(0,ah.createSecurityRole)(this.dataverse,t)}createPersonaRole(t){return(0,ah.createPersonaRole)(this.dataverse,t)}deleteSecurityRole(t){return(0,ah.deleteSecurityRole)(this.dataverse,t)}addEntityPrivilegesToRole(t,n){return(0,ah.addEntityPrivilegesToRole)(this.dataverse,t,n)}getEntityPrivileges(t){return(0,ah.getEntityPrivileges)(this.dataverse,t)}createRecord(t,n){return(0,Ns.createRecord)(this.dataverse,t,n)}createRecordsBulk(t,n){return(0,Ns.createRecordsBulk)(this.dataverse,t,n)}updateRecord(t,n,r){return(0,Ns.updateRecord)(this.dataverse,t,n,r)}upsertRecord(t,n,r,i){return(0,Ns.upsertRecord)(this.dataverse,t,n,r,i)}deleteRecord(t,n){return(0,Ns.deleteRecord)(this.dataverse,t,n)}getRecord(t,n,r){return(0,Ns.getRecord)(this.dataverse,t,n,r)}queryRecords(t,n){return(0,Ns.queryRecords)(this.dataverse,t,n)}seedRecordGraph(t,n){return(0,C_e.seedRecordGraph)(this.dataverse,t,n)}resolveArtifact(t,n){return(0,q8.resolveArtifact)(this.dataverse,t,n)}findArtifact(t,n){return(0,q8.findArtifact)(this.dataverse,t,n)}async deleteAppCascade(t,n){await this.workspace.ensureReady();let r=await(0,v_e.deleteAppCascade)(this.dataverse,t,n),i=(0,Yl.normalizeGuid)(t,"appModuleId");return await this.workspace.readArtifact("app",i)&&await this.workspace.deleteArtifact("app",i),r}associateRecords(t,n,r){return(0,Ns.associateRecords)(this.dataverse,t,n,r)}disassociateRecords(t,n,r,i){return(0,Ns.disassociateRecords)(this.dataverse,t,n,r,i)}createWebResource(t){return(0,Kb.createWebResource)(this.dataverse,t)}updateWebResource(t,n){return(0,Kb.updateWebResource)(this.dataverse,t,n)}getWebResource(t){return(0,Kb.getWebResource)(this.dataverse,t)}deleteWebResource(t){return(0,Kb.deleteWebResource)(this.dataverse,t)}getAppSettings(t){return(0,gf.readAppSettings)(this.dataverse,t)}setAppSetting(t,n,r){return(0,gf.setAppSetting)(this.dataverse,t,n,r)}setHeaderAndNavigationRefresh(t,n){if(typeof n!="boolean")throw new le.ValidationError("app",t,[{pointer:"/headerAndNavigationRefresh",rule:h_e.HEADER_NAV_BOOLEAN_RULE,message:`enabled must be a boolean, got ${typeof n}`}]);return(0,gf.setAppSetting)(this.dataverse,t,gf.HEADER_AND_NAVIGATION_REFRESH,n?gf.APP_SETTING_ON:gf.APP_SETTING_OFF)}getAppTheme(t){return(0,x8.getAppTheme)(this.dataverse,t)}setAppTheme(t,n,r){return this.withArtifactLock("app",String(t),()=>(0,x8.setAppTheme)(this.dataverse,t,n,r??{}))}getSolution(t){return(0,Mn.getSolution)(this.dataverse,t)}createPublisher(t){return(0,Mn.createPublisher)(this.dataverse,t)}createSolution(t){return(0,Mn.createSolution)(this.dataverse,t)}setSolutionVersion(t,n){return(0,Mn.setSolutionVersion)(this.dataverse,t,n)}addSolutionComponent(t){return(0,Mn.addSolutionComponent)(this.dataverse,t)}removeSolutionComponent(t,n,r){return(0,Mn.removeSolutionComponent)(this.dataverse,t,n,r)}exportSolution(t){return(0,Mn.exportSolution)(this.dataverse,t)}importSolution(t){return this.schemaWrite(void 0,()=>(0,Mn.importSolution)(this.dataverse,t))}getDeploymentSettingsTemplate(t){return(0,Mn.getDeploymentSettingsTemplate)(this.dataverse,t)}deleteSolution(t){return this.schemaWrite(void 0,()=>(0,Mn.deleteSolution)(this.dataverse,t))}async inspectArtifact(t,n,r){var i;if(t!=="command"&&t!=="dashboard")throw new le.SdkError(le.INSPECTION_NOT_SUPPORTED_CODE,`inspectArtifact inspects 'command' and 'dashboard' only, not '${String(t)}'. Read another type with fetchArtifact.`);let o=(i=this.registrations.get(t))===null||i===void 0?void 0:i.inspect;if(!o)throw new le.SdkError(le.INSPECTION_NOT_SUPPORTED_CODE,`No inspection is registered for '${t}'.`);let a=(0,k8.readOnlyDataverse)(this.dataverse),s={languageCode:this.languageCode};if(t==="dashboard")return o(a,n,r,s);try{return await o(a,n,r,s)}catch(u){let l=u?.code;throw u instanceof le.InvalidArgumentError||l===le.INSPECTION_UNREADABLE_CODE?u:(0,l_e.inspectionUnreadable)(n,u)}}async getArtifact(t,n){return this.withArtifactLock(t,n,async()=>{let{artifact:r,meta:i}=await this.readWhole(t,n);return await this.acknowledgeRefresh(t,n,i),r})}async getArtifactUnlocked(t,n){return this.readRaw(t,n)}async readWhole(t,n){let{meta:r}=await this.revalidate(t,n);return{artifact:await this.readLocal(t,n),meta:r}}async acknowledgeRefresh(t,n,r){var i,o,a;let s=this.artifactKey(t,n),u=r===void 0?await this.versions.getMeta(t,n):r;this.baselineObserved.has(s)||this.baselineObserved.set(s,(i=u?.observedGeneration)!==null&&i!==void 0?i:0);let l=(o=u?.refreshGeneration)!==null&&o!==void 0?o:0;this.raiseGenerationHighWater(s,l),u&&l!==((a=u.observedGeneration)!==null&&a!==void 0?a:0)&&await this.versions.storeMeta(t,n,{...u,observedGeneration:l},u),this.observedGenerations.set(s,l)}raiseGenerationHighWater(t,n){var r;n>((r=this.generationHighWater.get(t))!==null&&r!==void 0?r:0)&&this.generationHighWater.set(t,n)}async observedAtInvocation(t,n,r){var i,o;if(r!==void 0)return r;let a=this.baselineObserved.get(this.artifactKey(t,n));return a!==void 0?a:(o=(i=await this.versions.getMeta(t,n))===null||i===void 0?void 0:i.observedGeneration)!==null&&o!==void 0?o:0}artifactKey(t,n){return`${t}\0${(0,W8.canonicalArtifactId)(n)}`}nextRefreshGeneration(t,n,r){var i,o,a;let s=this.artifactKey(t,n),u=Math.max((i=r?.refreshGeneration)!==null&&i!==void 0?i:0,(o=r?.observedGeneration)!==null&&o!==void 0?o:0,(a=this.generationHighWater.get(s))!==null&&a!==void 0?a:0)+1;return this.raiseGenerationHighWater(s,u),u}async readRaw(t,n){return await this.revalidateIfStale(t,n),this.readLocal(t,n)}async readForMutation(t,n,r,i){var o,a;let s=await this.observedAtInvocation(t,n,i);if(((a=(o=await this.versions.getMeta(t,n))===null||o===void 0?void 0:o.refreshGeneration)!==null&&a!==void 0?a:0)>s)throw new le.StaleArtifactError(t,n,r,"pushed");if(await this.revalidateIfStale(t,n)==="refreshed-changed")throw new le.StaleArtifactError(t,n,r);return this.readLocal(t,n)}async readLocal(t,n){let r=await this.workspace.readArtifact(t,n);if(!r)throw new le.ArtifactNotFoundError(t,n);return r}async revalidateIfStale(t,n){return(await this.revalidate(t,n)).outcome}async revalidate(t,n){let r=await this.versions.getMeta(t,n);if(!r)return{outcome:"skipped",meta:null};let i=r.fetchedAt?Date.parse(r.fetchedAt):NaN,o=Date.now()-i;if(!Number.isNaN(i)&&this.cacheStalenessMs>0&&o<=this.cacheStalenessMs)return{outcome:"fresh",meta:r};if(await this.versions.isDirty(t,n,r))return{outcome:"skipped",meta:r};let a=await this.workspace.readArtifact(t,n);await this.fetchArtifactUnlocked(t,n);let s=await this.workspace.readArtifact(t,n);return{outcome:(0,fo.deepEqual)(a,s)?"refreshed-unchanged":"refreshed-changed"}}async queryTree(t,n,r){return this.withArtifactLock(t,n,async()=>{let{artifact:i,meta:o}=await this.readWhole(t,n),a=co.JsonPointer.resolve(i,r);if(a===void 0)throw new le.PathNotFoundError(t,n,r);return r===""&&await this.acknowledgeRefresh(t,n,o),a})}async findElements(t,n,r){return this.withArtifactLock(t,n,async()=>(0,s_e.findElements)(await this.getArtifactUnlocked(t,n),r))}async withDirtyFlags(t){let n=[];for(let r of t)n.push({...r,isDirty:await this.versions.isDirty(r.type,r.id)});return n}async listArtifacts(t,n){return this.withDirtyFlags(await this.workspace.listArtifacts(t,n))}async getEntityMetadata(t){let n=await this.readCachedEntityMetadata(t);if(!n)throw new le.ArtifactNotFoundError("entityMetadata",t);return n}async getFieldMetadata(t,n){let i=(await this.getEntityMetadata(t)).attributes.find(o=>o.logicalName===n);if(!i)throw new le.PathNotFoundError("entityMetadata",t,n);return i}async updateElement(t,n,r,i){let o=this.observedGenerations.get(this.artifactKey(t,n));return this.withArtifactLock(t,n,async()=>{let a=await this.readForMutation(t,n,r,o),s=co.JsonPointer.resolve(a,r);if(s===void 0)throw new le.PathNotFoundError(t,n,r);let u=_s(s)&&_s(i)?{...s,...i}:i;return co.JsonPointer.set(a,r,(0,Go.cloneJson)(u)),this.assertStructurallyValid(t,n,a,r),await this.workspace.writeArtifact(t,n,a),this.getArtifactUnlocked(t,n)})}async addElement(t,n,r,i,o){let a=this.observedGenerations.get(this.artifactKey(t,n));return this.withArtifactLock(t,n,async()=>{let s=await this.readForMutation(t,n,r,a),u=co.JsonPointer.resolve(s,r);if(u===void 0)throw new le.PathNotFoundError(t,n,r);if(!Array.isArray(u)){if(!_s(u)||!_s(i))throw new le.ValidationError(t,n,r,"parent must be an array, or an object with an object of properties to add");if(o?.position!==void 0)throw new le.ValidationError(t,n,r,"position is not supported for an object parent");let d={};for(let f of Object.keys(i)){if(f==="id")throw new le.ValidationError(t,n,r,"refusing to write 'id' \u2014 that re-keys the node rather than adding a property");let p=(0,Go.cloneJson)(i[f]),m=(0,Jb.isValueMapKey)(f)||(0,Jb.pointerTouchesValueMap)(r);d[f]=m?p:Array.isArray(p)?p.map(h=>_s(h)?this.assignMissingIds(t,h):h):_s(p)?this.assignMissingIds(t,p):p}for(let f of Object.keys(d))co.JsonPointer.set(s,co.JsonPointer.append(r,f),d[f]);return this.assertStructurallyValid(t,n,s,r),await this.workspace.writeArtifact(t,n,s),this.getArtifactUnlocked(t,n)}let l=(0,Jb.pointerTouchesValueMap)(r)?(0,Go.cloneJson)(i):this.assignMissingIds(t,(0,Go.cloneJson)(i)),c=U_e(u,o?.position);return u.splice(c,0,l),this.assertStructurallyValid(t,n,s,r),await this.workspace.writeArtifact(t,n,s),this.getArtifactUnlocked(t,n)})}async moveElement(t,n,r,i,o){let a=this.observedGenerations.get(this.artifactKey(t,n));return this.withArtifactLock(t,n,async()=>{var s;let u=await this.readForMutation(t,n,r,a),l=co.JsonPointer.resolve(u,r);if(l===void 0)throw new le.PathNotFoundError(t,n,r);let c=co.JsonPointer.resolve(u,i);if(c===void 0)throw new le.PathNotFoundError(t,n,i);if(!Array.isArray(c))throw new le.ValidationError(t,n,i,"move target must be an array");if(i===r||i.startsWith(`${r}/`))throw new le.ValidationError(t,n,i,"cannot move an element into its own subtree");co.JsonPointer.remove(u,r);let d=(s=o?.index)!==null&&s!==void 0?s:c.length;c.splice(Math.max(0,Math.min(d,c.length)),0,l),j8(c);let f=co.JsonPointer.resolve(u,G8(r));return Array.isArray(f)&&f!==c&&j8(f),this.assertStructurallyValid(t,n,u,i),await this.workspace.writeArtifact(t,n,u),this.getArtifactUnlocked(t,n)})}async removeElement(t,n,r){let i=this.observedGenerations.get(this.artifactKey(t,n));return this.withArtifactLock(t,n,async()=>{let o=await this.readForMutation(t,n,r,i);if(co.JsonPointer.resolve(o,r)===void 0)throw new le.PathNotFoundError(t,n,r);return co.JsonPointer.remove(o,r),this.assertStructurallyValid(t,n,o,G8(r)),await this.workspace.writeArtifact(t,n,o),this.getArtifactUnlocked(t,n)})}assertStructurallyValid(t,n,r,i){var o,a,s;let u=this.registrations.get(t),l=(s=(a=u==null?void 0:(o=u.adapter).validate)===null||a===void 0?void 0:a.call(o,r,i))!==null&&s!==void 0?s:[];if(l.length>0)throw new le.ValidationError(t,n,l)}retrieveSetting(t,n){return(0,yf.retrieveSetting)(this.dataverse,t,n)}saveSettingValue(t,n,r){return(0,yf.saveSettingValue)(this.dataverse,t,n,r)}getAiReadiness(t){return(0,yf.getAiReadiness)(this.dataverse,t)}setAppAiFeatures(t,n,r){return(0,yf.setAppAiFeatures)(this.dataverse,t,n,r)}configureRowSummary(t,n){return(0,yf.configureRowSummary)(this.dataverse,t,n)}removeRowSummary(t){return(0,yf.removeRowSummary)(this.dataverse,t)}async enrichDefaultViews(t,n,r={}){let i=await(0,S_e.findDefaultViews)(this.dataverse,t,{excludeViewIds:r.excludeViewIds}),o=r.publish===!1,a=[],s=[],u=()=>({updated:[...a],results:[...s],pendingPublish:a.length>0?[{scope:(0,R8.boundEntityPublishScope)({entityLogicalName:t}),artifacts:a.map(c=>({type:"view",id:c}))}]:[]}),l;try{for(let c of i){await this.fetchArtifact("view",c.id),await this.updateElement("view",c.id,"/columns",n),l=c.id;let d=await this.pushArtifact("view",c.id);l=void 0,s.push(d),d.saved&&a.push(c.id)}}catch(c){throw l&&__e(c)&&a.push(l),o?(0,le.withPartialEnrichment)(c,u()):c}if(o)return u();if(a.length){let c=await this.publishArtifact("view",a[0]);if(c.publish.kind==="failed")throw new le.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,n){let r=this.requireRegistration(t,"createArtifact"),i=r.adapter.assignMissingIds(r.adapter.createDefault(n)),o=i.id;if(!o)throw new le.ValidationError(t,"(new)","/id","created artifact must have an id");return this.withArtifactLock(t,o,async()=>(await this.workspace.writeArtifact(t,o,i),(0,Go.cloneJson)(i)))}async deleteArtifact(t,n){return this.withArtifactLock(t,n,async()=>{await this.workspace.deleteArtifact(t,n)})}async deleteRemoteArtifact(t,n){return this.withArtifactLock(t,n,async()=>{var r;let i=this.requireRegistration(t,"deleteRemoteArtifact");if(await this.workspace.ensureReady(),i.guardedDelete){let o=await this.versions.getMeta(t,n);await i.api.delete(this.dataverse,n,{token:(r=o?.etag)!==null&&r!==void 0?r:null,snapshot:o?.snapshot})}else await i.api.delete(this.dataverse,n);await this.workspace.readArtifact(t,n)&&await this.workspace.deleteArtifact(t,n)})}async publishArtifact(t,n,r){let{result:i,siblings:o}=await this.withArtifactLock(t,n,()=>this.publishArtifactUnlocked(t,n,r));for(let a of o)await this.withArtifactLock(a.type,a.id,()=>this.adoptBracket(a));return i}async publishArtifacts(t,n){var r,i;let o=new Map;for(let g of t){let y=this.artifactKey(g.type,g.id);o.has(y)||o.set(y,{type:g.type,id:g.id})}let a=[];for(let[g,y]of o)a.push(await this.withArtifactLock(y.type,y.id,()=>this.preparePublish(g,y.type,y.id)));let s=new Set(o.keys()),u=[],l=new Set;for(let g of a){let y=((r=g.scope)===null||r===void 0?void 0:r.envelope)==="entity"?(i=g.scope.entityLogicalName)===null||i===void 0?void 0:i.toLowerCase():void 0;g.scope&&y&&!l.has(y)&&(l.add(y),u.push(g.scope))}let c=await this.captureSiblings(u,s),d=R_e(a),f=a.filter(g=>{var y;return(y=g.reg)===null||y===void 0?void 0:y.assertCombinablePublish}).sort((g,y)=>g.key<y.key?-1:g.key>y.key?1:0),p=async()=>{var g,y;for(let b of f)(y=(g=b.reg)===null||g===void 0?void 0:g.assertCombinablePublish)===null||y===void 0||y.call(g,this.dataverse,b.id);if(d)try{await(0,R8.publishXml)(this.dataverse,d);return}catch(b){return $u(b)}},m=await f.reduceRight((g,y)=>()=>this.withArtifactLock(y.type,y.id,g),p)(),h=new Map;for(let g of a)h.set(g.key,await this.withArtifactLock(g.type,g.id,()=>this.settlePublish(g,m,n)));for(let g of c)await this.withArtifactLock(g.type,g.id,()=>this.adoptBracket(g));return t.map(g=>({...h.get(this.artifactKey(g.type,g.id))}))}async preparePublish(t,n,r){var i,o;let a=await this.readRaw(n,r),s=this.registrations.get(n);if(!s?.publish)return{key:t,type:n,id:r,artifact:a,notApplicable:!0};let u=(i=s.publishScope)===null||i===void 0?void 0:i.call(s,r,a);if(!u||!P_e.has(u.envelope))throw new le.InvalidArgumentError(`publishArtifacts: ${n} '${r}' publishes through ${u?`a '${u.envelope}'`:"no declared"} scope, which one PublishXml envelope cannot carry. Publish it with publishArtifact.`);(o=s.assertCombinablePublish)===null||o===void 0||o.call(s,this.dataverse,r);let l=s.rebaselineAfterPublish==="bracket"?await this.captureBracket(s,n,r):void 0;return{key:t,type:n,id:r,artifact:a,reg:s,scope:u,...l?{own:l}:{}}}async settlePublish(t,n,r){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),n)return{type:i,id:o,shipped:!1,publish:{kind:"failed",error:n},...a};if(!r?.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,fo.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 u=await this.verifyPublished(i,o,t.artifact);return{type:i,id:o,shipped:u.kind==="verified",publish:u,...a}}async publishArtifactUnlocked(t,n,r){var i;let o=await this.readRaw(t,n),a=this.registrations.get(t);if(!a?.publish)return{result:{type:t,id:n,shipped:!1,publish:{kind:"notApplicable"}},siblings:[]};let s=(i=a.publishScope)===null||i===void 0?void 0:i.call(a,n,o),u=a.rebaselineAfterPublish==="bracket"?await this.captureBracket(a,t,n):void 0,l=s?await this.captureSiblings([s],new Set([this.artifactKey(t,n)])):[];try{await a.publish(this.dataverse,n,o)}catch(d){return{result:{type:t,id:n,shipped:!1,publish:{kind:"failed",error:$u(d)},...s?{publishScope:s}:{}},siblings:[]}}if(a.rebaselineAfterPublish==="snapshot"&&await this.rebaselineAfterPublish(a,t,n),u&&await this.adoptBracket(u),!r?.verify)return{result:{type:t,id:n,shipped:!1,publish:{kind:"submitted"},...s?{publishScope:s}:{}},siblings:l};let c=await this.verifyPublished(t,n,o);return{result:{type:t,id:n,shipped:c.kind==="verified",publish:c,...s?{publishScope:s}:{}},siblings:l}}async captureBracket(t,n,r){try{let i=await this.versions.getMeta(n,r),o=i?.etag;if(!(0,Dr.isVersionToken)(o)||!t.api.readContentThenToken)return;let{raw:a,etag:s,siblingEtags:u}=await t.api.readContentThenToken(this.dataverse,r),l=i?.siblingEtags;return s!==o||!x_e(l,u)?void 0:{type:n,id:r,reg:t,heldEtag:o,...l?{heldSiblings:l}:{},content:this.bracketContent(t,a)}}catch{return}}async captureSiblings(t,n){var r,i,o;let a=new Map;for(let l of t){let c=l.envelope==="entity"?(r=l.entityLogicalName)===null||r===void 0?void 0:r.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 l of s){let c=this.registrations.get(l.type);if(!(n.has(this.artifactKey(l.type,l.id))||c?.rebaselineAfterPublish!=="bracket"||!c.publishScope))try{let d=await this.workspace.readArtifact(l.type,l.id),f=d?c.publishScope(l.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(l))}catch{continue}}let u=[];for(let l of a.values())for(let c of l){let d=this.registrations.get(c.type),f=d?await this.captureBracket(d,c.type,c.id):void 0;f&&u.push(f)}return u}async adoptBracket(t){var n;try{let r=await this.versions.getMeta(t.type,t.id);if(!r||r.etag!==t.heldEtag||!(0,fo.deepEqual)((n=r.siblingEtags)!==null&&n!==void 0?n:void 0,t.heldSiblings))return;let{raw:i,etag:o,siblingEtags:a}=await t.reg.api.get(this.dataverse,t.id);if(!(0,Dr.isVersionToken)(o)||!H8(a,t.heldSiblings)||!K8(a)||!(o!==t.heldEtag||!(0,fo.deepEqual)(a??void 0,t.heldSiblings))||!(0,fo.deepEqual)(this.bracketContent(t.reg,i),t.content))return;await this.versions.storeMeta(t.type,t.id,{...r,etag:o,...t.heldSiblings?{siblingEtags:{...a}}:{},fetchedAt:(0,Dr.nowIso)()},r)}catch{}}bracketContent(t,n){var r,i,o;let a=t.adapter.fromApiResponse(n);return(o=(i=(r=t.adapter).baselineContent)===null||i===void 0?void 0:i.call(r,a))!==null&&o!==void 0?o:a}adoptReadBack(t,n){try{return{artifact:t.adapter.fromApiResponse(n)}}catch(r){return{warning:`The write was saved, but the record read back after it could not be read into the local copy (${$u(r).message}). The SDK holds no version for it now, so the next push is refused: re-fetch before editing again.`}}}adoptedAsSent(t,n,r,i){try{let o={...r,...i},a=t.adapter.fromApiResponse(t.adapter.completeAsStored?t.adapter.completeAsStored(o,r):o);return(0,fo.deepEqual)(n,a)}catch{return!1}}async rebaselineAfterPublish(t,n,r){try{let i=await this.versions.getMeta(n,r);if(!i)return;let{raw:o,etag:a,memberEtags:s,siblingEtags:u}=t.api.getForRebaseline?await t.api.getForRebaseline(this.dataverse,r):await t.api.get(this.dataverse,r),l=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,fo.deepEqual)(c(i.snapshot),c(l)))return;await this.versions.storeMeta(n,r,{...i,etag:a,fetchedAt:(0,Dr.nowIso)(),...s?{memberEtags:s}:{},...u?{siblingEtags:u}:{}},i)}catch{}}async verifyPublished(t,n,r){var i;if(t!=="app"){let o=this.registrations.get(t);return o?.api.getPublished?this.verifyPublishedContent(o,t,n,r):{kind:"unverifiable",reason:`published-projection verification is not characterised for '${t}'; the publish was submitted`}}try{let o=`/appmodules(${(0,Yl.normalizeGuid)(n,"id")})${(0,Yl.odataQuery)([["$select","appmoduleid,name,description"]])}`,a=await this.dataverse.get(o);if(a.status>=200&&a.status<300){let s=(i=a.body)!==null&&i!==void 0?i:{},u=r;if(!u)return{kind:"unverifiable",reason:"there is no local copy of the app to compare the published projection with"};let l=["name","description"].filter(d=>u[d]!==void 0);if(l.length===0)return{kind:"unverifiable",reason:"the local copy of the app holds neither a name nor a description to compare the published projection with, and its presence alone proves nothing for a re-publish"};let c=l.filter(d=>{var f,p;return((f=u[d])!==null&&f!==void 0?f:"")!==((p=s[d])!==null&&p!==void 0?p:"")});return c.length>0?{kind:"unverifiable",reason:`the published projection does not yet match the saved app (${c.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 ${a.status}`}}catch(o){return{kind:"unverifiable",reason:$u(o).message}}}async verifyPublishedContent(t,n,r,i){var o,a,s;try{let u=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},l=u(i),c=(o=await this.versions.getMeta(n,r))===null||o===void 0?void 0:o.snapshot;if(c===void 0||!(0,fo.deepEqual)(l,u(c)))return{kind:"unverifiable",reason:`the local ${n} 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,r));return d?(0,fo.deepEqual)(l,u(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 ${n} is not in the published projection yet. PublishXml is asynchronous \u2014 re-read shortly, or re-publish if it persists`}}catch(u){return{kind:"unverifiable",reason:$u(u).message}}}async pushArtifact(t,n){return this.withArtifactLock(t,n,()=>this.pushArtifactUnlocked(t,n))}async prepareArtifactUnlocked(t,n,r,i={client:this.dataverse,persistNormalized:!0}){var o,a;let s=this.requireRegistration(t,"pushArtifact"),u=await this.workspace.readArtifactWithText(t,n);if(!u)throw new le.ArtifactNotFoundError(t,n);let l=u.artifact,c=u.text,d=await this.versions.getMeta(t,n),f=(a=(o=s.adapter).normalize)===null||a===void 0?void 0:a.call(o,l,d?.snapshot);f&&f!==l&&(i.persistNormalized&&await this.workspace.writeArtifact(t,n,f),l=f,c=void 0),this.assertLanguageMatches(t,n,d,s),this.assertProjectionMatches(t,n,d);let p=await this.buildMetadataContext(s.adapter,l,d?.snapshot,i.client),m=await s.adapter.toApiPayload(l,d?.snapshot,p);return await this.assertSemanticallyComplete(s,t,n,l,d===null,d?.everActivated,r,i.client),{type:t,id:n,reg:s,json:l,...c!==void 0?{storedText:c}:{},meta:d,payload:m}}async assertSemanticallyComplete(t,n,r,i,o,a,s,u=this.dataverse){let l=t.adapter.issuesBlockingPush;if(!l)return;let c=i.entityLogicalName,f=(c?await this.columnsForCheck(t,c,i,s,u):[]).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(h=>({value:h.value,label:h.label}))}:{},...m.targets?{targets:m.targets}:{}})),p=l.call(t.adapter,i,f,{isCreate:o,everActivated:a});if(p.length>0)throw new le.ValidationError(n,r,p)}columnsForCheck(t,n,r,i,o=this.dataverse){var a,s,u;let l=(u=(s=(a=t.adapter).columnsCheckedAtPush)===null||s===void 0?void 0:s.call(a,r))!==null&&u!==void 0?u:[],c=async()=>{let p=await this.readCachedEntityMetadata(n);if(p)return p.attributes;try{return await(0,hf.readCheckColumns)(o,n,l)}catch{return[]}};if(!i)return c();let d=[n,...[...new Set(l)].sort()].join("\0"),f=i.get(d);return f||(f=c(),i.set(d,f)),f}async pushArtifactUnlocked(t,n,r){return this.executePrepared(await this.prepareArtifactUnlocked(t,n,r))}async executePrepared(t){var n,r,i,o,a,s,u,l,c,d,f;let{type:p,id:m,reg:h,json:g,meta:y,payload:b}=t,E=!1;try{let w;if(y)w=await h.api.update(this.dataverse,m,b,y.etag,y.memberEtags,y.siblingEtags);else{let S=await this.createWithMintedId(h,p,m,b,g);if("adopted"in S)return await this.persistAdoption(p,m,g,S.adopted);w=S.written}E=!0;let _=m;y||(w.serverIdentity&&h.adapter.applyServerIdentity&&h.adapter.applyServerIdentity(g,w.serverIdentity),w.id&&w.id!==m&&(g.id=w.id,await this.workspace.deleteArtifact(p,m),_=w.id));let I=y&&w.readBack!==void 0?this.adoptReadBack(h,w.readBack):void 0,T=I?.artifact?{artifact:I.artifact,baseline:I.artifact}:h.adapter.committed?h.adapter.committed(g,b,{intentPending:w.intentPending===!0,...w.serverState!==void 0?{serverState:w.serverState}:{}}):{artifact:g,baseline:g};await this.workspace.writeArtifact(p,_,T.artifact,y&&_===m?t.storedText:void 0);let O=I?.artifact!==void 0&&!(0,fo.deepEqual)(I.artifact,g),v=O?this.nextRefreshGeneration(p,_,y):(n=y?.refreshGeneration)!==null&&n!==void 0?n:0,N=[...(r=w.warnings)!==null&&r!==void 0?r:[],...I?.warning?[I.warning]:[],...I?.artifact!==void 0&&!this.adoptedAsSent(h,I.artifact,w.readBack,b)?[`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 ${p} 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(p,_,{etag:I&&!I.artifact?null:w.etag,...v>0?{refreshGeneration:v,observedGeneration:(i=y?.observedGeneration)!==null&&i!==void 0?i:0}:{},languageCode:this.languageCode,projectionVersion:mf.PROJECTION_VERSION,fetchedAt:(0,Dr.nowIso)(),snapshot:(0,Go.cloneJson)(T.baseline),...w.memberEtags?{memberEtags:w.memberEtags}:{},...w.siblingEtags?{siblingEtags:w.siblingEtags}:{}},_===m?y:void 0),{type:p,id:_,saved:!0,shipped:((o=w.publish)===null||o===void 0?void 0:o.kind)==="verified",publish:(a=w.publish)!==null&&a!==void 0?a:{kind:"notRequested"},...w.publish&&w.publish.kind!=="notRequested"?(()=>{var S;let R=(S=h.publishScope)===null||S===void 0?void 0:S.call(h,_,g);return R?{publishScope:R}:{}})():{},...O?{refreshed:!0}:{},...N.length>0?{warnings:N}:{},...w.appMainForms?{appMainForms:w.appMainForms}:{}}}catch(w){let _=(0,le.readPartialTokens)(w);if(_&&y){let I={...(s=y.memberEtags)!==null&&s!==void 0?s:{},...(u=_.memberEtags)!==null&&u!==void 0?u:{}},T={...(l=y.siblingEtags)!==null&&l!==void 0?l:{},...(c=_.siblingEtags)!==null&&c!==void 0?c:{}},O=h.adapter.partiallyCommitted&&y.snapshot!==void 0?h.adapter.partiallyCommitted(y.snapshot,b,Object.keys((d=_.memberEtags)!==null&&d!==void 0?d:{})):void 0;await this.versions.storeMeta(p,m,{...y,...O!==void 0&&O!==y.snapshot?{snapshot:(0,Go.cloneJson)(O)}:{},...Object.keys(I).length>0?{memberEtags:I}:{},...Object.keys(T).length>0?{siblingEtags:T}:{}},y)}if(w instanceof le.SdkError&&w.code===Pr.ALREADY_EXISTS_CODE)return{type:p,id:m,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:w};if(w instanceof le.SdkError&&w.code===P8.WFOM_API_UNAVAILABLE_CODE)return{type:p,id:m,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:w};if(w instanceof le.SdkError&&w.code===P8.BUSINESS_RULE_LEFT_DEACTIVATED_CODE)return{type:p,id:m,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:w};if(w instanceof le.SdkError&&w.code===Dr.VERSION_CONFLICT_CODE)return{type:p,id:m,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:(0,U8.isFailureAfterPrimaryWrite)(w)?w:new le.VersionConflictError(p,m,(f=y?.etag)!==null&&f!==void 0?f:null,null,w.message)};throw E?N_e(w):w}}assertLanguageMatches(t,n,r,i){if(i?.languageSensitive&&!(r?.languageCode===void 0||r.languageCode===this.languageCode))throw new le.SdkError("ARTIFACT_LANGUAGE_MISMATCH",`Refusing to push ${t} '${n}': it was fetched with languageCode ${r.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 ${r.languageCode}.`)}assertProjectionMatches(t,n,r){var i;if(r&&r.projectionVersion!==mf.PROJECTION_VERSION)throw new le.SdkError("ARTIFACT_PROJECTION_STALE",`Refusing to push ${t} '${n}': its workspace copy was produced by projection version ${(i=r.projectionVersion)!==null&&i!==void 0?i:"unknown (pre-versioning)"}, but this SDK produces version ${mf.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}', '${n}') and re-apply any local edits. A copy WITH local edits keeps them, and this version, through that fetch: read the edits first (getArtifact or diffArtifact), re-fetch with fetchArtifact('${t}', '${n}', { overwrite: true }) \u2014 which discards them \u2014 and re-apply them.`)}async createWithMintedId(t,n,r,i,o){try{return{written:await t.api.create(this.dataverse,i,r)}}catch(a){let s=n==="form"?(0,rT.readPrimaryCreateRefusal)(a):void 0;if(s?.status===404&&await(0,iT.formExistsAtId)(()=>t.api.get(this.dataverse,r),s.sent.formid)){let l=`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,le.attachCause)(new le.SdkError(Pr.ALREADY_EXISTS_CODE,Yb(n,r,l)+(this.createRecovery==="adoptExact"?` ${uT($_e)}`:"")),a)}if(!(a instanceof le.SdkError)||a.code!==Dr.VERSION_CONFLICT_CODE||(0,U8.isFailureAfterPrimaryWrite)(a))throw a;if(this.createRecovery==="adoptExact"&&s?.status===412){let u=await(0,iT.recoverFormCreate)({client:this.dataverse,read:()=>t.api.get(this.dataverse,r),sent:s.sent,authoredFormType:o.formType,project:l=>t.adapter.fromApiResponse(l)});if("adopted"in u)return{adopted:u.adopted};throw new le.SdkError(Pr.ALREADY_EXISTS_CODE,`${Yb(n,r)} ${uT(u.refused)}`)}throw new le.SdkError(Pr.ALREADY_EXISTS_CODE,Yb(n,r))}}async persistAdoption(t,n,r,i){let{artifact:o,etag:a}=i,s=!(0,fo.deepEqual)(o,r);return await this.versions.storeMeta(t,n,{etag:a,...s?{refreshGeneration:this.nextRefreshGeneration(t,n,null),observedGeneration:0}:{},languageCode:this.languageCode,projectionVersion:mf.PROJECTION_VERSION,fetchedAt:(0,Dr.nowIso)(),snapshot:(0,Go.cloneJson)(o)},null),s&&await this.workspace.writeArtifact(t,n,o),{type:t,id:n,saved:!1,adoptedExisting:!0,shipped:!1,publish:{kind:"notRequested"},...s?{refreshed:!0}:{}}}async buildMetadataContext(t,n,r,i=this.dataverse){var o,a,s,u;let l=(a=(o=t.metadataNeeds)===null||o===void 0?void 0:o.call(t,n,r))!==null&&a!==void 0?a:[],c=new Set(l.map(T=>T.entityLogicalName).filter(T=>!!T)),d=new Set(l.filter(T=>T.needsColumnDetail).map(T=>T.entityLogicalName)),f=new Set(l.filter(T=>T.needsColumnDetail||!T.fieldName).map(T=>T.entityLogicalName)),p=T=>l.filter(O=>O.entityLogicalName===T).every(O=>O.fetchRequired===!1),m=new Map,h=new Map;for(let T of c){let O=await this.readCachedEntityMetadata(T);if(O&&d.has(T)&&(O.columnDetailComplete!==!0||!(typeof O.columnDetailVersion=="number"&&O.columnDetailVersion>=hf.COLUMN_DETAIL_VERSION)||O.attributes.some(v=>typeof v.attributeTypeName!="string"))&&(O=null),!O&&!f.has(T)){if(!p(T)){let v=l.filter(N=>N.entityLogicalName===T).map(N=>N.fieldName);try{let N=await(0,hf.readColumnHints)(i,T,v);h.set(T,new Map(N.map(S=>[S.logicalName,S])))}catch{}}continue}if(!O&&!p(T))try{await this.loadMissedEntityMetadata(T,i),O=await this.readCachedEntityMetadata(T)}catch{}O&&m.set(T,O)}let g=(T,O)=>{var v,N,S;return(N=(v=m.get(T))===null||v===void 0?void 0:v.attributes.find(R=>R.logicalName===O))!==null&&N!==void 0?N:(S=h.get(T))===null||S===void 0?void 0:S.get(O)},y=this.languageCode,E=l.some(T=>{if(!T.needsLabel||!T.fieldName)return!1;let O=g(T.entityLogicalName,T.fieldName);return O?.localizedDisplayName!==void 0&&!O.localizedDisplayName[y]})?await this.readBaseLanguage(i):void 0,w=!((s=t.needsBaseLanguage)===null||s===void 0)&&s.call(t,n)?await this.readBaseLanguage(i):void 0,_=(u=t.customControlNeeds)===null||u===void 0?void 0:u.call(t,n,r),I=_&&(_.controls.length>0||_.columns.length>0)?await this.readPcfNeeds(_,i):void 0;return{resolveField:(T,O)=>{let v=g(T,O);return v?{displayName:F_e(v,y,E),attributeType:v.attributeType}:void 0},resolveEntity:T=>m.get(T),loadTypeScript:()=>this.compiler.load(),genPageIteration:this.genPageIteration,...w!==void 0?{baseLanguageCode:w}:{},...I?{pcf:I}:{}}}async readPcfNeeds(t,n=this.dataverse){let r=new Map;for(let o of t.controls)r.set(o,await(0,M8.readControlManifest)(n,o));let i=new Map;for(let o of t.columns)i.set(o,await(0,M8.readPcfColumn)(n,t.entityLogicalName,o,t.requireCreateEligibility?{requireCreateEligibility:!0}:void 0));return{control:o=>r.get(o),column:(o,a)=>o===t.entityLogicalName?i.get(a):void 0}}readBaseLanguage(t=this.dataverse){if(!this.baseLanguage){let n=(async()=>{var r,i,o;try{let a=await t.get("/organizations?$select=languagecode");if(a.status<200||a.status>=300)return;let s=Number((o=(i=(r=a.body)===null||r===void 0?void 0:r.value)===null||i===void 0?void 0:i[0])===null||o===void 0?void 0:o.languagecode);return Number.isInteger(s)&&s>0?s:void 0}catch{return}})();this.baseLanguage=n,n.then(r=>{r===void 0&&this.baseLanguage===n&&(this.baseLanguage=void 0)})}return this.baseLanguage}async pushAll(){let t=await this.getDirtyArtifacts();await this.warmBatchMetadata(t);let n=new Map,r=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,n))}catch(s){r.set(o,{type:a.type,id:a.id,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:$u(s)})}}if(r.size>0)return t.map((o,a)=>{var s;return(s=r.get(a))!==null&&s!==void 0?s:{type:o.type,id:o.id,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:new le.SdkError(Pr.PUSH_NOT_ATTEMPTED_CODE,`Not attempted: ${r.size} artifact(s) in this batch could not be prepared, so no writes were issued. Fix the reported failures and push again.`)}});let i=[];for(let o of t)try{i.push(await this.withArtifactLock(o.type,o.id,()=>this.pushArtifactUnlocked(o.type,o.id,n)))}catch(a){i.push({type:o.type,id:o.id,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:$u(a)})}return i}async warmBatchMetadata(t,n=this.dataverse){var r,i,o;let a=new Set;for(let s of t){let u=this.registrations.get(s.type);if(!u)continue;let l;try{l=await this.readLocal(s.type,s.id)}catch{continue}let c=l.entityLogicalName;c&&a.add(c);for(let d of(o=(i=(r=u.adapter).metadataNeeds)===null||i===void 0?void 0:i.call(r,l))!==null&&o!==void 0?o:[])d.entityLogicalName&&a.add(d.entityLogicalName)}for(let s of a)if(!await this.readCachedEntityMetadata(s))try{await this.loadMissedEntityMetadata(s,n)}catch{}}async getDirtyArtifacts(){return(await this.withDirtyFlags(await this.workspace.listArtifacts())).filter(n=>n.isDirty)}async diffArtifact(t,n){return this.versions.diff(t,n)}async previewPush(t,n,r){let{client:i,guard:o}=this.dataverse.readOnly(),a=this.targetSolutionReader(i);return this.withArtifactLock(t,n,()=>this.latched(o,async()=>(await this.previewUnlocked(t,n,i,o,a,r)).preview))}async previewPushAll(t){let{client:n,guard:r}=this.dataverse.readOnly();return this.latched(r,async()=>{let i=await this.getDirtyArtifacts(),o=r.gets;await this.warmBatchMetadata(i,n);let a=this.targetSolutionReader(n);await a();let s=r.gets-o,u=new Map,l=[];for(let d of i)l.push(await this.withArtifactLock(d.type,d.id,()=>this.previewUnlocked(d.type,d.id,n,r,a,t,u)));(0,nT.judgeBatchDependencies)(l.map(d=>d.preview));let c=l.filter(d=>!d.prepared).length;if(c>0)for(let d of l.filter(f=>f.prepared))d.preview.refusals.push({code:Pr.PUSH_NOT_ATTEMPTED_CODE,message:`Not attempted: ${c} artifact(s) in this batch could not be prepared, so pushAll would issue no writes. Fix the reported failures first.`}),d.preview.outcome="refused";return{wouldAttempt:i.length>0&&c===0,previews:l.map(d=>d.preview),sharedRequests:s}})}async latched(t,n){let r=()=>{if(t.refusedWrites.length>0)throw new le.SdkError("PREVIEW_WRITE_REFUSED",`A pre-push check attempted ${t.refusedWrites.length} write(s) (${t.refusedWrites[0]}); it may only read. Nothing was written. This is a defect in the SDK.`)},i;try{i=await n()}catch(o){throw r(),o}return r(),i}targetSolutionReader(t){let n=this.dataverse.solutionName,r;return()=>n?(r||(r=(0,nT.readTargetSolution)(t,n)),r):Promise.resolve(void 0)}async previewUnlocked(t,n,r,i,o,a,s){let u=this.requireRegistration(t,"previewPush"),l=await this.workspace.readArtifact(t,n);if(!l)throw new le.ArtifactNotFoundError(t,n);let c=await this.versions.getMeta(t,n),d=(await this.versions.diff(t,n)).changes,f=!1;return{preview:await(0,nT.previewArtifact)({type:t,id:n,reg:u,client:r,guard:i,options:a,meta:c,json:l,localChanges:d,prepare:async()=>{let m=await this.prepareArtifactUnlocked(t,n,s,{client:r,persistNormalized:!1});return f=!0,{payload:m.payload,json:m.json}},solution:o,alreadyExists:m=>Yb(t,n)+(m!==void 0?` ${uT(m)}`:""),...t==="form"&&this.createRecovery==="adoptExact"?{judgeAdoption:async(m,h)=>{let g=await(0,iT.recoverFormCreate)({client:r,read:()=>u.api.get(r,n),sent:Object.freeze({...(0,Dr.withClientMintedId)(m,"formid",n)}),authoredFormType:h.formType,project:y=>u.adapter.fromApiResponse(y)});return"adopted"in g?{eligible:!0}:{refused:g.refused}}}:{}}),prepared:f}}planDataFix(t){return(0,B8.planDataFix)(this.dataverse,t)}applyDataFix(t,n){return(0,B8.applyDataFix)(this.dataverse,t,n)}planPromotion(t,n){return t instanceof e?(0,L8.planPromotion)(this.promotionContext(),t.dataverse,n):Promise.reject((0,p_e.promotionError)("INVALID_ARGUMENT","preflight",{reason:"source must be an SDK created by createMakerSdk"}))}promote(t,n,r){return this.schemaWrite(void 0,()=>(0,f_e.promote)(this.promotionContext(),t,n,r))}promotionContext(){let{instanceUrl:t,clients:n}=this.promotionConnectivity;return{client:this.dataverse,issuedPlans:this.promotionIssued,listConnections:(r,i)=>{let o=()=>Promise.reject(new le.SdkError("PREVIEW_WRITE_REFUSED","A promotion plan attempted a write; it may only read.")),a=s=>s&&{get:(u,l)=>(i.spendGet(),s.get(u,l)),post:o,patch:o,delete:o};return new $8.ConnectivityRouter(r,t,{powerAppsServiceClient:a(n.powerAppsServiceClient),powerPlatformApiClient:a(n.powerPlatformApiClient)}).listConnections()}}}assignMissingIds(t,n){let r=this.registrations.get(t);return r?r.adapter.assignMissingIds(n):(0,Jb.assignMissingIds)(n)}async resolveComponentType(t){if(t.genPage)return"genPage";if(t.connectionReference)return"connectionReference";if(t.customApi==="api")return"customApi";switch(t.componentType){case Mn.SolutionComponentType.SavedQuery:return"view";case Mn.SolutionComponentType.SavedQueryVisualization:return"chart";case Mn.SolutionComponentType.AppModule:return"app";case Mn.SolutionComponentType.EnvironmentVariableDefinition:return"environmentVariable";case Mn.SolutionComponentType.FieldSecurityProfile:return"fieldSecurityProfile";case Mn.SolutionComponentType.DuplicateRule:return"duplicateRule";case Mn.SolutionComponentType.Workflow:return this.workflowArtifactType(t);case Mn.SolutionComponentType.SystemForm:return this.systemFormArtifactType(t.objectId);default:return}}async systemFormArtifactType(t){let n=await(0,Hb.readSystemFormType)(this.dataverse,t);if(Number.isNaN(n))throw new le.SdkError(aT,`System form '${t}' answered without a readable type, so whether it is a form or a dashboard cannot be told.`);return(0,Hb.systemFormKindOf)(n)}async workflowArtifactType(t){let n=(0,Yl.normalizeGuid)(t.objectId,"workflowId"),r=`/workflows(${n})${(0,Yl.odataQuery)([["$select","category,businessprocesstype"]])}`,o=(0,Dr.ensureSuccess)(await this.dataverse.get(r),this.dataverse.apiUrl(r)).body,a=(0,Hb.decodeCode)(o?.category);if(Number.isNaN(a))throw new le.SdkError(aT,`Workflow '${n}' answered without a readable category, so its kind cannot be told.`);if(t.workflowCategory=a,a===T_e)return"businessRule";if(a===O_e){let s=(0,Hb.decodeCode)(o?.businessprocesstype);if(Number.isNaN(s))throw new le.SdkError(aT,`Workflow '${n}' (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,n){let r=this.registrations.get(t);if(!r)throw new le.NotImplementedError(n,`no adapter registered for artifact type '${t}'`);return r}getSearchSettings(t){return(0,m_e.getSearchSettings)(this.dataverse,t)}};Pr.MakerSdk=Qb;function M_e(e){return new Qb(e)}Pr.createMakerSdk=M_e;function $u(e){return e instanceof Error?e:new Error(String(e))}function H8(e,t){let n=Object.keys(e??{}),r=Object.keys(t??{});return n.length===r.length&&n.every(i=>Object.prototype.hasOwnProperty.call(t??{},i))}function K8(e){return Object.values(e??{}).every(Dr.isVersionToken)}function x_e(e,t){return H8(e,t)&&K8(e)&&Object.keys(e??{}).every(n=>t?.[n]===e?.[n])}function uT(e){return`createRecovery 'adoptExact' did not adopt it: ${e}.`}function Yb(e,t,n){return`Cannot create ${e} '${t}': a record already exists at that id${n?` (${n})`:""}, 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 F_e(e,t,n){let r=e.localizedDisplayName;return r?.[t]||(n===void 0?void 0:r?.[n])||e.displayName}function _s(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function G8(e){let t=e.lastIndexOf("/");return t<=0?"":e.slice(0,t)}function j8(e){e.length===0||!e.every(t=>_s(t)&&typeof t.order=="number")||e.forEach((t,n)=>{t.order=n})}function U_e(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 r=e.findIndex(i=>_s(i)&&i.id===t.before);return r<0?e.length:r}let n=e.findIndex(r=>_s(r)&&r.id===t.after);return n<0?e.length:n+1}});var Y8=C(Xb=>{"use strict";Object.defineProperty(Xb,"__esModule",{value:!0});Xb.ARTIFACT_TYPES=void 0;Xb.ARTIFACT_TYPES=["form","view","businessRule","app","command","chart","dashboard","genPage","bpf","environmentVariable","connectionReference","fieldSecurityProfile","customApi","duplicateRule"]});var X8=C(Q8=>{"use strict";Object.defineProperty(Q8,"__esModule",{value:!0})});var e5=C(Z8=>{"use strict";Object.defineProperty(Z8,"__esModule",{value:!0})});var n5=C(t5=>{"use strict";Object.defineProperty(t5,"__esModule",{value:!0})});var i5=C(r5=>{"use strict";Object.defineProperty(r5,"__esModule",{value:!0})});var a5=C(o5=>{"use strict";Object.defineProperty(o5,"__esModule",{value:!0})});var u5=C(s5=>{"use strict";Object.defineProperty(s5,"__esModule",{value:!0})});var c5=C(l5=>{"use strict";Object.defineProperty(l5,"__esModule",{value:!0})});var f5=C(d5=>{"use strict";Object.defineProperty(d5,"__esModule",{value:!0})});var m5=C(p5=>{"use strict";Object.defineProperty(p5,"__esModule",{value:!0})});var g5=C(h5=>{"use strict";Object.defineProperty(h5,"__esModule",{value:!0})});var b5=C(y5=>{"use strict";Object.defineProperty(y5,"__esModule",{value:!0})});var w5=C(v5=>{"use strict";Object.defineProperty(v5,"__esModule",{value:!0})});var A5=C(E5=>{"use strict";Object.defineProperty(E5,"__esModule",{value:!0})});var S5=C(C5=>{"use strict";Object.defineProperty(C5,"__esModule",{value:!0})});var _5=C(N5=>{"use strict";Object.defineProperty(N5,"__esModule",{value:!0})});var T5=C(I5=>{"use strict";Object.defineProperty(I5,"__esModule",{value:!0})});var D5=C(O5=>{"use strict";Object.defineProperty(O5,"__esModule",{value:!0})});var R5=C(P5=>{"use strict";Object.defineProperty(P5,"__esModule",{value:!0})});var $5=C(k5=>{"use strict";Object.defineProperty(k5,"__esModule",{value:!0})});var M5=C(L5=>{"use strict";Object.defineProperty(L5,"__esModule",{value:!0})});var F5=C(x5=>{"use strict";Object.defineProperty(x5,"__esModule",{value:!0})});var q5=C(U5=>{"use strict";Object.defineProperty(U5,"__esModule",{value:!0})});var V5=C(B5=>{"use strict";Object.defineProperty(B5,"__esModule",{value:!0})});var j5=C(G5=>{"use strict";Object.defineProperty(G5,"__esModule",{value:!0})});var z5=C(W5=>{"use strict";Object.defineProperty(W5,"__esModule",{value:!0})});var K5=C(H5=>{"use strict";Object.defineProperty(H5,"__esModule",{value:!0})});var Y5=C(J5=>{"use strict";Object.defineProperty(J5,"__esModule",{value:!0})});var X5=C(Q5=>{"use strict";Object.defineProperty(Q5,"__esModule",{value:!0})});var e6=C(Z5=>{"use strict";Object.defineProperty(Z5,"__esModule",{value:!0})});var n6=C(t6=>{"use strict";Object.defineProperty(t6,"__esModule",{value:!0})});var i6=C(r6=>{"use strict";Object.defineProperty(r6,"__esModule",{value:!0})});var a6=C(ge=>{"use strict";var q_e=ge&&ge.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),Be=ge&&ge.__exportStar||function(e,t){for(var n in e)n!=="default"&&!Object.prototype.hasOwnProperty.call(t,n)&&q_e(t,e,n)};Object.defineProperty(ge,"__esModule",{value:!0});ge.projectConnectorOperationSchema=ge.projectConnectorOperations=ge.PromotionError=ge.createMakerSdk=void 0;var B_e=J8();Object.defineProperty(ge,"createMakerSdk",{enumerable:!0,get:function(){return B_e.createMakerSdk}});Be(Y8(),ge);Be(X8(),ge);Be(e5(),ge);Be(n5(),ge);Be(i5(),ge);Be(a5(),ge);Be(u5(),ge);Be(c5(),ge);Be(f5(),ge);Be(m5(),ge);Be(g5(),ge);Be(b5(),ge);Be(w5(),ge);Be(A5(),ge);Be(S5(),ge);Be(h0(),ge);Be(_5(),ge);Be(T5(),ge);Be(D5(),ge);Be(R5(),ge);Be($5(),ge);Be(M5(),ge);Be(F5(),ge);Be(q5(),ge);Be(V5(),ge);Be(j5(),ge);Be(z5(),ge);Be(K5(),ge);Be(Y5(),ge);Be(X5(),ge);Be(e6(),ge);Be(eA(),ge);Be(n6(),ge);Be(i6(),ge);Be(Y(),ge);var V_e=Y();Object.defineProperty(ge,"PromotionError",{enumerable:!0,get:function(){return V_e.PromotionError}});var o6=Zf();Object.defineProperty(ge,"projectConnectorOperations",{enumerable:!0,get:function(){return o6.projectConnectorOperations}});Object.defineProperty(ge,"projectConnectorOperationSchema",{enumerable:!0,get:function(){return o6.projectConnectorOperationSchema}})});var cT=C(Ra=>{"use strict";var G_e=Ra&&Ra.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),j_e=Ra&&Ra.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),l6=Ra&&Ra.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var n in e)n!=="default"&&Object.prototype.hasOwnProperty.call(e,n)&&G_e(t,e,n);return j_e(t,e),t};Object.defineProperty(Ra,"__esModule",{value:!0});Ra.NodeFileSystemStorage=void 0;var xn=l6(require("fs")),Rr=l6(require("path")),s6=Y(),u6=Uv();async function c6(e){let t;try{t=await xn.promises.lstat(e)}catch{return}if(t.isSymbolicLink()){try{await xn.promises.unlink(e)}catch{await xn.promises.rmdir(e)}return}if(!t.isDirectory()){await xn.promises.unlink(e);return}for(let n of await xn.promises.readdir(e))await c6(Rr.join(e,n));await xn.promises.rmdir(e)}var lT=class{constructor(t){this.root=t}getRoot(){return this.root}pathFor(t,n=!0){return this.assertWithinRoot(Rr.join(this.root,...t),n)}realPathThroughNearestAncestor(t){let n=t,r=[];for(;!xn.existsSync(n);){r.unshift(Rr.basename(n));let i=Rr.dirname(n);if(i===n)return Rr.resolve(t);n=i}return Rr.resolve(xn.realpathSync(n),...r)}assertWithinRoot(t,n){let r=Rr.resolve(this.root),i=Rr.resolve(t);if(i!==r&&!i.startsWith(r+Rr.sep))throw new s6.PathTraversalError(t,this.root);let o=this.realPathThroughNearestAncestor(r),a=n?this.realPathThroughNearestAncestor(i):Rr.resolve(this.realPathThroughNearestAncestor(Rr.dirname(i)),Rr.basename(i));if(a!==o&&!a.startsWith(o+Rr.sep))throw new s6.PathTraversalError(t,this.root);return i}async readText(t){let n=this.pathFor(t);if(!xn.existsSync(n))return null;try{return await(0,u6.retryTransientIoAsync)(()=>xn.promises.readFile(n,"utf8"))}catch(r){if(r.code==="ENOENT")return null;throw r}}async writeTextAtomic(t,n){let r=this.pathFor(t),i=Rr.dirname(r);await xn.promises.mkdir(i,{recursive:!0});let o=Rr.join(i,`.${Rr.basename(r)}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`);try{await xn.promises.writeFile(o,n,"utf8"),await(0,u6.retryTransientIoAsync)(()=>xn.promises.rename(o,r))}catch(a){try{xn.existsSync(o)&&await xn.promises.unlink(o)}catch{}throw a}}async deleteFile(t){let n=this.pathFor(t);xn.existsSync(n)&&await xn.promises.unlink(n)}async deleteByPrefix(t){await c6(this.pathFor(t,!1))}async ensureContainer(t){await xn.promises.mkdir(this.pathFor(t),{recursive:!0})}async exists(t){return xn.existsSync(this.pathFor(t))}};Ra.NodeFileSystemStorage=lT});var d6=C(Ni=>{"use strict";var W_e=Ni&&Ni.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),z_e=Ni&&Ni.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),H_e=Ni&&Ni.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var n in e)n!=="default"&&Object.prototype.hasOwnProperty.call(e,n)&&W_e(t,e,n);return z_e(t,e),t};Object.defineProperty(Ni,"__esModule",{value:!0});Ni.loadNodeTypeScript=Ni.createNodeWorkspaceStorage=Ni.NodeFileSystemStorage=void 0;var K_e=cT(),J_e=cT();Object.defineProperty(Ni,"NodeFileSystemStorage",{enumerable:!0,get:function(){return J_e.NodeFileSystemStorage}});function Y_e(e){return new K_e.NodeFileSystemStorage(e)}Ni.createNodeWorkspaceStorage=Y_e;async function Q_e(){return await Promise.resolve().then(()=>H_e(require("typescript")))}Ni.loadNodeTypeScript=Q_e});var Is={};module.exports=_i(Is);Os(Is,Xe(a6()),module.exports);Os(Is,Xe(d6()),module.exports);